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,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/NegateSaturate.Vector64.SByte.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 NegateSaturate_Vector64_SByte() { var test = new SimpleUnaryOpTest__NegateSaturate_Vector64_SByte(); 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__NegateSaturate_Vector64_SByte { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); 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<SByte, 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 Vector64<SByte> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = SByte.MinValue; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__NegateSaturate_Vector64_SByte testClass) { var result = AdvSimd.NegateSaturate(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__NegateSaturate_Vector64_SByte testClass) { fixed (Vector64<SByte>* pFld1 = &_fld1) { var result = AdvSimd.NegateSaturate( AdvSimd.LoadVector64((SByte*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static Vector64<SByte> _clsVar1; private Vector64<SByte> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__NegateSaturate_Vector64_SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = SByte.MinValue; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); } public SimpleUnaryOpTest__NegateSaturate_Vector64_SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = SByte.MinValue; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = SByte.MinValue; } _dataTable = new DataTable(_data1, new SByte[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.NegateSaturate( Unsafe.Read<Vector64<SByte>>(_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.NegateSaturate( AdvSimd.LoadVector64((SByte*)(_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).GetMethod(nameof(AdvSimd.NegateSaturate), new Type[] { typeof(Vector64<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.NegateSaturate), new Type[] { typeof(Vector64<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.NegateSaturate( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<SByte>* pClsVar1 = &_clsVar1) { var result = AdvSimd.NegateSaturate( AdvSimd.LoadVector64((SByte*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr); var result = AdvSimd.NegateSaturate(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)); var result = AdvSimd.NegateSaturate(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__NegateSaturate_Vector64_SByte(); var result = AdvSimd.NegateSaturate(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__NegateSaturate_Vector64_SByte(); fixed (Vector64<SByte>* pFld1 = &test._fld1) { var result = AdvSimd.NegateSaturate( AdvSimd.LoadVector64((SByte*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.NegateSaturate(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<SByte>* pFld1 = &_fld1) { var result = AdvSimd.NegateSaturate( AdvSimd.LoadVector64((SByte*)(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.NegateSaturate(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.NegateSaturate( AdvSimd.LoadVector64((SByte*)(&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(Vector64<SByte> op1, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.NegateSaturate(firstOp[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.NegateSaturate)}<SByte>(Vector64<SByte>): {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 NegateSaturate_Vector64_SByte() { var test = new SimpleUnaryOpTest__NegateSaturate_Vector64_SByte(); 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__NegateSaturate_Vector64_SByte { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); 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<SByte, 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 Vector64<SByte> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = SByte.MinValue; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__NegateSaturate_Vector64_SByte testClass) { var result = AdvSimd.NegateSaturate(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__NegateSaturate_Vector64_SByte testClass) { fixed (Vector64<SByte>* pFld1 = &_fld1) { var result = AdvSimd.NegateSaturate( AdvSimd.LoadVector64((SByte*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static Vector64<SByte> _clsVar1; private Vector64<SByte> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__NegateSaturate_Vector64_SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = SByte.MinValue; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); } public SimpleUnaryOpTest__NegateSaturate_Vector64_SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = SByte.MinValue; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = SByte.MinValue; } _dataTable = new DataTable(_data1, new SByte[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.NegateSaturate( Unsafe.Read<Vector64<SByte>>(_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.NegateSaturate( AdvSimd.LoadVector64((SByte*)(_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).GetMethod(nameof(AdvSimd.NegateSaturate), new Type[] { typeof(Vector64<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.NegateSaturate), new Type[] { typeof(Vector64<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.NegateSaturate( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<SByte>* pClsVar1 = &_clsVar1) { var result = AdvSimd.NegateSaturate( AdvSimd.LoadVector64((SByte*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr); var result = AdvSimd.NegateSaturate(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)); var result = AdvSimd.NegateSaturate(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__NegateSaturate_Vector64_SByte(); var result = AdvSimd.NegateSaturate(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__NegateSaturate_Vector64_SByte(); fixed (Vector64<SByte>* pFld1 = &test._fld1) { var result = AdvSimd.NegateSaturate( AdvSimd.LoadVector64((SByte*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.NegateSaturate(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<SByte>* pFld1 = &_fld1) { var result = AdvSimd.NegateSaturate( AdvSimd.LoadVector64((SByte*)(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.NegateSaturate(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.NegateSaturate( AdvSimd.LoadVector64((SByte*)(&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(Vector64<SByte> op1, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.NegateSaturate(firstOp[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.NegateSaturate)}<SByte>(Vector64<SByte>): {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,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Net.Http.WinHttpHandler/tests/UnitTests/FakeInterop.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.IO; using System.Net; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using System.Net.Http.WinHttpHandlerUnitTests; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; internal static partial class Interop { internal static partial class Crypt32 { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal unsafe struct CERT_CHAIN_POLICY_PARA { public uint cbSize; public uint dwFlags; public void* pvExtraPolicyPara; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal unsafe struct CERT_CHAIN_POLICY_STATUS { public uint cbSize; public uint dwError; public int lChainIndex; public int lElementIndex; public void* pvExtraPolicyStatus; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct CERT_CONTEXT { internal uint dwCertEncodingType; internal IntPtr pbCertEncoded; internal uint cbCertEncoded; internal IntPtr pCertInfo; internal IntPtr hCertStore; } public static bool CertFreeCertificateContext(IntPtr certContext) { return true; } public static bool CertVerifyCertificateChainPolicy( IntPtr pszPolicyOID, SafeX509ChainHandle pChainContext, ref CERT_CHAIN_POLICY_PARA pPolicyPara, ref CERT_CHAIN_POLICY_STATUS pPolicyStatus) { return true; } } internal static partial class Kernel32 { public static string GetMessage(int error, IntPtr moduleName) { string messageFormat = "Fake error message, error code: {0}"; return string.Format(messageFormat, error); } public static IntPtr GetModuleHandle(string moduleName) { return IntPtr.Zero; } } internal static partial class WinHttp { public static SafeWinHttpHandle WinHttpOpen( IntPtr userAgent, uint accessType, string proxyName, string proxyBypass, uint flags) { if (TestControl.WinHttpOpen.ErrorWithApiCall) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INVALID_HANDLE; return new FakeSafeWinHttpHandle(false); } if (accessType == Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY && !TestControl.WinHttpAutomaticProxySupport) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INVALID_PARAMETER; return new FakeSafeWinHttpHandle(false); } APICallHistory.ProxyInfo proxyInfo; proxyInfo.AccessType = accessType; proxyInfo.Proxy = proxyName; proxyInfo.ProxyBypass = proxyBypass; APICallHistory.SessionProxySettings = proxyInfo; return new FakeSafeWinHttpHandle(true); } public static bool WinHttpCloseHandle(IntPtr sessionHandle) { Marshal.FreeHGlobal(sessionHandle); return true; } public static SafeWinHttpHandle WinHttpConnect( SafeWinHttpHandle sessionHandle, string serverName, ushort serverPort, uint reserved) { return new FakeSafeWinHttpHandle(true); } public static bool WinHttpAddRequestHeaders( SafeWinHttpHandle requestHandle, StringBuilder headers, uint headersLength, uint modifiers) { return true; } public static bool WinHttpAddRequestHeaders( SafeWinHttpHandle requestHandle, string headers, uint headersLength, uint modifiers) { return true; } public static SafeWinHttpHandle WinHttpOpenRequest( SafeWinHttpHandle connectHandle, string verb, string objectName, string version, string referrer, string acceptTypes, uint flags) { return new FakeSafeWinHttpHandle(true); } public static bool WinHttpSendRequest( SafeWinHttpHandle requestHandle, IntPtr headers, uint headersLength, IntPtr optional, uint optionalLength, uint totalLength, IntPtr context) { Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; fakeHandle.Context = context; fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE, IntPtr.Zero, 0); }); return true; } public static bool WinHttpReceiveResponse(SafeWinHttpHandle requestHandle, IntPtr reserved) { Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpReceiveResponse.Delay); if (aborted || TestControl.WinHttpReadData.ErrorOnCompletion) { Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult; asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_RECEIVE_RESPONSE); asyncResult.dwError = aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED : Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR; TestControl.WinHttpReadData.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult); } else { TestControl.WinHttpReceiveResponse.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, IntPtr.Zero, 0); } }); return true; } public static bool WinHttpQueryDataAvailable( SafeWinHttpHandle requestHandle, IntPtr bytesAvailableShouldBeNullForAsync) { if (bytesAvailableShouldBeNullForAsync != IntPtr.Zero) { return false; } if (TestControl.WinHttpQueryDataAvailable.ErrorWithApiCall) { return false; } Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpReadData.Delay); if (aborted || TestControl.WinHttpQueryDataAvailable.ErrorOnCompletion) { Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult; asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_QUERY_DATA_AVAILABLE); asyncResult.dwError = aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED : Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR; TestControl.WinHttpQueryDataAvailable.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult); } else { int bufferSize = sizeof(int); IntPtr buffer = Marshal.AllocHGlobal(bufferSize); Marshal.WriteInt32(buffer, TestServer.DataAvailable); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE, buffer, (uint)bufferSize); Marshal.FreeHGlobal(buffer); } }); return true; } public static bool WinHttpReadData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, IntPtr bytesReadShouldBeNullForAsync) { if (bytesReadShouldBeNullForAsync != IntPtr.Zero) { return false; } if (TestControl.WinHttpReadData.ErrorWithApiCall) { return false; } uint bytesRead; TestServer.ReadFromResponseBody(buffer, bufferSize, out bytesRead); Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpReadData.Delay); if (aborted || TestControl.WinHttpReadData.ErrorOnCompletion) { Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult; asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_READ_DATA); asyncResult.dwError = aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED : Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR; TestControl.WinHttpReadData.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult); } else { TestControl.WinHttpReadData.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_READ_COMPLETE, buffer, bytesRead); } }); return true; } public static bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, IntPtr buffer, ref uint bufferLength, ref uint index) { string httpVersion = "HTTP/1.1"; string statusText = "OK"; if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_SET_COOKIE) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND; return false; } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_VERSION) { return CopyToBufferOrFailIfInsufficientBufferLength(httpVersion, buffer, ref bufferLength); } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_STATUS_TEXT) { return CopyToBufferOrFailIfInsufficientBufferLength(statusText, buffer, ref bufferLength); } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_CONTENT_ENCODING) { string compression = TestServer.ResponseHeaders.Contains("Content-Encoding: deflate") ? "deflate" : TestServer.ResponseHeaders.Contains("Content-Encoding: gzip") ? "gzip" : null; if (compression == null) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND; return false; } return CopyToBufferOrFailIfInsufficientBufferLength(compression, buffer, ref bufferLength); } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF) { return CopyToBufferOrFailIfInsufficientBufferLength(TestServer.ResponseHeaders, buffer, ref bufferLength); } return false; } private static bool CopyToBufferOrFailIfInsufficientBufferLength(string value, IntPtr buffer, ref uint bufferLength) { // The length of the string (plus terminating null char) in bytes. uint bufferLengthNeeded = ((uint)value.Length + 1) * sizeof(char); if (buffer == IntPtr.Zero || bufferLength < bufferLengthNeeded) { bufferLength = bufferLengthNeeded; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER; return false; } // Copy the string to the buffer. char[] temp = new char[value.Length + 1]; // null terminated. value.CopyTo(0, temp, 0, value.Length); Marshal.Copy(temp, 0, buffer, temp.Length); // The length in bytes, minus the length of the null char at the end. bufferLength = (uint)value.Length * sizeof(char); return true; } public static bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, ref uint number, ref uint bufferLength, IntPtr index) { infoLevel &= ~Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER; if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE) { number = (uint)HttpStatusCode.OK; return true; } return false; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, StringBuilder buffer, ref uint bufferSize) { string uri = "http://www.contoso.com/"; if (option == Interop.WinHttp.WINHTTP_OPTION_URL) { if (buffer == null) { bufferSize = ((uint)uri.Length + 1) * 2; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER; return false; } buffer.Append(uri); return true; } return false; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, ref IntPtr buffer, ref uint bufferSize) { return true; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, IntPtr buffer, ref uint bufferSize) { return true; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, ref uint buffer, ref uint bufferSize) { if (option == WINHTTP_OPTION_STREAM_ERROR_CODE) { TestControl.LastWin32Error = (int)ERROR_INVALID_PARAMETER; return false; } return true; } public static bool WinHttpWriteData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, IntPtr bytesWrittenShouldBeNullForAsync) { if (bytesWrittenShouldBeNullForAsync != IntPtr.Zero) { return false; } if (TestControl.WinHttpWriteData.ErrorWithApiCall) { return false; } uint bytesWritten; TestServer.WriteToRequestBody(buffer, bufferSize); bytesWritten = bufferSize; Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpWriteData.Delay); if (aborted || TestControl.WinHttpWriteData.ErrorOnCompletion) { Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult; asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_WRITE_DATA); asyncResult.dwError = Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR; TestControl.WinHttpWriteData.Wait(); fakeHandle.InvokeCallback(aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED : Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult); } else { TestControl.WinHttpWriteData.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, IntPtr.Zero, 0); } }); return true; } public static bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, ref uint optionData, uint optionLength = sizeof(uint)) { if (option == Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION & !TestControl.WinHttpDecompressionSupport) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION; return false; } if (option == Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE && optionData == Interop.WinHttp.WINHTTP_DISABLE_COOKIES) { APICallHistory.WinHttpOptionDisableCookies = true; } else if (option == Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE && optionData == Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION) { APICallHistory.WinHttpOptionEnableSslRevocation = true; } else if (option == Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS) { APICallHistory.WinHttpOptionSecureProtocols = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS) { APICallHistory.WinHttpOptionSecurityFlags = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS) { APICallHistory.WinHttpOptionMaxHttpAutomaticRedirects = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY) { APICallHistory.WinHttpOptionRedirectPolicy = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_RECEIVE_TIMEOUT) { APICallHistory.WinHttpOptionReceiveTimeout = optionData; } return true; } public static bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, string optionData, uint optionLength) { if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY_USERNAME) { APICallHistory.ProxyUsernameWithDomain = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY_PASSWORD) { APICallHistory.ProxyPassword = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_USERNAME) { APICallHistory.ServerUsernameWithDomain = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_PASSWORD) { APICallHistory.ServerPassword = optionData; } return true; } public unsafe static bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, IntPtr optionData, uint optionLength) { if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY) { var proxyInfo = Marshal.PtrToStructure<Interop.WinHttp.WINHTTP_PROXY_INFO>(optionData); var proxyInfoHistory = new APICallHistory.ProxyInfo(); proxyInfoHistory.AccessType = proxyInfo.AccessType; proxyInfoHistory.Proxy = Marshal.PtrToStringUni(proxyInfo.Proxy); proxyInfoHistory.ProxyBypass = Marshal.PtrToStringUni(proxyInfo.ProxyBypass); APICallHistory.RequestProxySettings = proxyInfoHistory; } else if (option == Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT) { APICallHistory.WinHttpOptionClientCertContext.Add(optionData); } else if (option == Interop.WinHttp.WINHTTP_OPTION_TCP_KEEPALIVE) { Interop.WinHttp.tcp_keepalive* ptr = (Interop.WinHttp.tcp_keepalive*)optionData; APICallHistory.WinHttpOptionTcpKeepAlive = (ptr->onoff, ptr->keepalivetime, ptr->keepaliveinterval); } return true; } public static bool WinHttpSetCredentials( SafeWinHttpHandle requestHandle, uint authTargets, uint authScheme, string userName, string password, IntPtr reserved) { return true; } public static bool WinHttpQueryAuthSchemes( SafeWinHttpHandle requestHandle, out uint supportedSchemes, out uint firstScheme, out uint authTarget) { supportedSchemes = 0; firstScheme = 0; authTarget = 0; return true; } public static bool WinHttpSetTimeouts( SafeWinHttpHandle handle, int resolveTimeout, int connectTimeout, int sendTimeout, int receiveTimeout) { return true; } public static bool WinHttpGetIEProxyConfigForCurrentUser( out Interop.WinHttp.WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig) { if (FakeRegistry.WinInetProxySettings.RegistryKeyMissing) { proxyConfig.AutoDetect = 0; proxyConfig.AutoConfigUrl = IntPtr.Zero; proxyConfig.Proxy = IntPtr.Zero; proxyConfig.ProxyBypass = IntPtr.Zero; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_FILE_NOT_FOUND; return false; } proxyConfig.AutoDetect = FakeRegistry.WinInetProxySettings.AutoDetect ? 1 : 0; proxyConfig.AutoConfigUrl = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.AutoConfigUrl); proxyConfig.Proxy = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.Proxy); proxyConfig.ProxyBypass = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.ProxyBypass); return true; } public static bool WinHttpGetProxyForUrl( SafeWinHttpHandle sessionHandle, string url, ref Interop.WinHttp.WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions, out Interop.WinHttp.WINHTTP_PROXY_INFO proxyInfo) { if (TestControl.PACFileNotDetectedOnNetwork) { proxyInfo.AccessType = WINHTTP_ACCESS_TYPE_NO_PROXY; proxyInfo.Proxy = IntPtr.Zero; proxyInfo.ProxyBypass = IntPtr.Zero; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_AUTODETECTION_FAILED; return false; } proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY; proxyInfo.Proxy = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.Proxy); proxyInfo.ProxyBypass = IntPtr.Zero; return true; } public static IntPtr WinHttpSetStatusCallback( SafeWinHttpHandle handle, Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback, uint notificationFlags, IntPtr reserved) { if (handle == null) { throw new ArgumentNullException(nameof(handle)); } var fakeHandle = (FakeSafeWinHttpHandle)handle; fakeHandle.Callback = callback; return 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; using System.Collections.Generic; using System.IO; using System.Net; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using System.Net.Http.WinHttpHandlerUnitTests; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; internal static partial class Interop { internal static partial class Crypt32 { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal unsafe struct CERT_CHAIN_POLICY_PARA { public uint cbSize; public uint dwFlags; public void* pvExtraPolicyPara; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal unsafe struct CERT_CHAIN_POLICY_STATUS { public uint cbSize; public uint dwError; public int lChainIndex; public int lElementIndex; public void* pvExtraPolicyStatus; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct CERT_CONTEXT { internal uint dwCertEncodingType; internal IntPtr pbCertEncoded; internal uint cbCertEncoded; internal IntPtr pCertInfo; internal IntPtr hCertStore; } public static bool CertFreeCertificateContext(IntPtr certContext) { return true; } public static bool CertVerifyCertificateChainPolicy( IntPtr pszPolicyOID, SafeX509ChainHandle pChainContext, ref CERT_CHAIN_POLICY_PARA pPolicyPara, ref CERT_CHAIN_POLICY_STATUS pPolicyStatus) { return true; } } internal static partial class Kernel32 { public static string GetMessage(int error, IntPtr moduleName) { string messageFormat = "Fake error message, error code: {0}"; return string.Format(messageFormat, error); } public static IntPtr GetModuleHandle(string moduleName) { return IntPtr.Zero; } } internal static partial class WinHttp { public static SafeWinHttpHandle WinHttpOpen( IntPtr userAgent, uint accessType, string proxyName, string proxyBypass, uint flags) { if (TestControl.WinHttpOpen.ErrorWithApiCall) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INVALID_HANDLE; return new FakeSafeWinHttpHandle(false); } if (accessType == Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY && !TestControl.WinHttpAutomaticProxySupport) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INVALID_PARAMETER; return new FakeSafeWinHttpHandle(false); } APICallHistory.ProxyInfo proxyInfo; proxyInfo.AccessType = accessType; proxyInfo.Proxy = proxyName; proxyInfo.ProxyBypass = proxyBypass; APICallHistory.SessionProxySettings = proxyInfo; return new FakeSafeWinHttpHandle(true); } public static bool WinHttpCloseHandle(IntPtr sessionHandle) { Marshal.FreeHGlobal(sessionHandle); return true; } public static SafeWinHttpHandle WinHttpConnect( SafeWinHttpHandle sessionHandle, string serverName, ushort serverPort, uint reserved) { return new FakeSafeWinHttpHandle(true); } public static bool WinHttpAddRequestHeaders( SafeWinHttpHandle requestHandle, StringBuilder headers, uint headersLength, uint modifiers) { return true; } public static bool WinHttpAddRequestHeaders( SafeWinHttpHandle requestHandle, string headers, uint headersLength, uint modifiers) { return true; } public static SafeWinHttpHandle WinHttpOpenRequest( SafeWinHttpHandle connectHandle, string verb, string objectName, string version, string referrer, string acceptTypes, uint flags) { return new FakeSafeWinHttpHandle(true); } public static bool WinHttpSendRequest( SafeWinHttpHandle requestHandle, IntPtr headers, uint headersLength, IntPtr optional, uint optionalLength, uint totalLength, IntPtr context) { Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; fakeHandle.Context = context; fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE, IntPtr.Zero, 0); }); return true; } public static bool WinHttpReceiveResponse(SafeWinHttpHandle requestHandle, IntPtr reserved) { Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpReceiveResponse.Delay); if (aborted || TestControl.WinHttpReadData.ErrorOnCompletion) { Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult; asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_RECEIVE_RESPONSE); asyncResult.dwError = aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED : Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR; TestControl.WinHttpReadData.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult); } else { TestControl.WinHttpReceiveResponse.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, IntPtr.Zero, 0); } }); return true; } public static bool WinHttpQueryDataAvailable( SafeWinHttpHandle requestHandle, IntPtr bytesAvailableShouldBeNullForAsync) { if (bytesAvailableShouldBeNullForAsync != IntPtr.Zero) { return false; } if (TestControl.WinHttpQueryDataAvailable.ErrorWithApiCall) { return false; } Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpReadData.Delay); if (aborted || TestControl.WinHttpQueryDataAvailable.ErrorOnCompletion) { Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult; asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_QUERY_DATA_AVAILABLE); asyncResult.dwError = aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED : Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR; TestControl.WinHttpQueryDataAvailable.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult); } else { int bufferSize = sizeof(int); IntPtr buffer = Marshal.AllocHGlobal(bufferSize); Marshal.WriteInt32(buffer, TestServer.DataAvailable); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE, buffer, (uint)bufferSize); Marshal.FreeHGlobal(buffer); } }); return true; } public static bool WinHttpReadData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, IntPtr bytesReadShouldBeNullForAsync) { if (bytesReadShouldBeNullForAsync != IntPtr.Zero) { return false; } if (TestControl.WinHttpReadData.ErrorWithApiCall) { return false; } uint bytesRead; TestServer.ReadFromResponseBody(buffer, bufferSize, out bytesRead); Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpReadData.Delay); if (aborted || TestControl.WinHttpReadData.ErrorOnCompletion) { Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult; asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_READ_DATA); asyncResult.dwError = aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED : Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR; TestControl.WinHttpReadData.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult); } else { TestControl.WinHttpReadData.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_READ_COMPLETE, buffer, bytesRead); } }); return true; } public static bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, IntPtr buffer, ref uint bufferLength, ref uint index) { string httpVersion = "HTTP/1.1"; string statusText = "OK"; if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_SET_COOKIE) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND; return false; } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_VERSION) { return CopyToBufferOrFailIfInsufficientBufferLength(httpVersion, buffer, ref bufferLength); } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_STATUS_TEXT) { return CopyToBufferOrFailIfInsufficientBufferLength(statusText, buffer, ref bufferLength); } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_CONTENT_ENCODING) { string compression = TestServer.ResponseHeaders.Contains("Content-Encoding: deflate") ? "deflate" : TestServer.ResponseHeaders.Contains("Content-Encoding: gzip") ? "gzip" : null; if (compression == null) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND; return false; } return CopyToBufferOrFailIfInsufficientBufferLength(compression, buffer, ref bufferLength); } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF) { return CopyToBufferOrFailIfInsufficientBufferLength(TestServer.ResponseHeaders, buffer, ref bufferLength); } return false; } private static bool CopyToBufferOrFailIfInsufficientBufferLength(string value, IntPtr buffer, ref uint bufferLength) { // The length of the string (plus terminating null char) in bytes. uint bufferLengthNeeded = ((uint)value.Length + 1) * sizeof(char); if (buffer == IntPtr.Zero || bufferLength < bufferLengthNeeded) { bufferLength = bufferLengthNeeded; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER; return false; } // Copy the string to the buffer. char[] temp = new char[value.Length + 1]; // null terminated. value.CopyTo(0, temp, 0, value.Length); Marshal.Copy(temp, 0, buffer, temp.Length); // The length in bytes, minus the length of the null char at the end. bufferLength = (uint)value.Length * sizeof(char); return true; } public static bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, ref uint number, ref uint bufferLength, IntPtr index) { infoLevel &= ~Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER; if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE) { number = (uint)HttpStatusCode.OK; return true; } return false; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, StringBuilder buffer, ref uint bufferSize) { string uri = "http://www.contoso.com/"; if (option == Interop.WinHttp.WINHTTP_OPTION_URL) { if (buffer == null) { bufferSize = ((uint)uri.Length + 1) * 2; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER; return false; } buffer.Append(uri); return true; } return false; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, ref IntPtr buffer, ref uint bufferSize) { return true; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, IntPtr buffer, ref uint bufferSize) { return true; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, ref uint buffer, ref uint bufferSize) { if (option == WINHTTP_OPTION_STREAM_ERROR_CODE) { TestControl.LastWin32Error = (int)ERROR_INVALID_PARAMETER; return false; } return true; } public static bool WinHttpWriteData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, IntPtr bytesWrittenShouldBeNullForAsync) { if (bytesWrittenShouldBeNullForAsync != IntPtr.Zero) { return false; } if (TestControl.WinHttpWriteData.ErrorWithApiCall) { return false; } uint bytesWritten; TestServer.WriteToRequestBody(buffer, bufferSize); bytesWritten = bufferSize; Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpWriteData.Delay); if (aborted || TestControl.WinHttpWriteData.ErrorOnCompletion) { Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult; asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_WRITE_DATA); asyncResult.dwError = Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR; TestControl.WinHttpWriteData.Wait(); fakeHandle.InvokeCallback(aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED : Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult); } else { TestControl.WinHttpWriteData.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, IntPtr.Zero, 0); } }); return true; } public static bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, ref uint optionData, uint optionLength = sizeof(uint)) { if (option == Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION & !TestControl.WinHttpDecompressionSupport) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION; return false; } if (option == Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE && optionData == Interop.WinHttp.WINHTTP_DISABLE_COOKIES) { APICallHistory.WinHttpOptionDisableCookies = true; } else if (option == Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE && optionData == Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION) { APICallHistory.WinHttpOptionEnableSslRevocation = true; } else if (option == Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS) { APICallHistory.WinHttpOptionSecureProtocols = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS) { APICallHistory.WinHttpOptionSecurityFlags = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS) { APICallHistory.WinHttpOptionMaxHttpAutomaticRedirects = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY) { APICallHistory.WinHttpOptionRedirectPolicy = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_RECEIVE_TIMEOUT) { APICallHistory.WinHttpOptionReceiveTimeout = optionData; } return true; } public static bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, string optionData, uint optionLength) { if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY_USERNAME) { APICallHistory.ProxyUsernameWithDomain = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY_PASSWORD) { APICallHistory.ProxyPassword = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_USERNAME) { APICallHistory.ServerUsernameWithDomain = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_PASSWORD) { APICallHistory.ServerPassword = optionData; } return true; } public unsafe static bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, IntPtr optionData, uint optionLength) { if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY) { var proxyInfo = Marshal.PtrToStructure<Interop.WinHttp.WINHTTP_PROXY_INFO>(optionData); var proxyInfoHistory = new APICallHistory.ProxyInfo(); proxyInfoHistory.AccessType = proxyInfo.AccessType; proxyInfoHistory.Proxy = Marshal.PtrToStringUni(proxyInfo.Proxy); proxyInfoHistory.ProxyBypass = Marshal.PtrToStringUni(proxyInfo.ProxyBypass); APICallHistory.RequestProxySettings = proxyInfoHistory; } else if (option == Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT) { APICallHistory.WinHttpOptionClientCertContext.Add(optionData); } else if (option == Interop.WinHttp.WINHTTP_OPTION_TCP_KEEPALIVE) { Interop.WinHttp.tcp_keepalive* ptr = (Interop.WinHttp.tcp_keepalive*)optionData; APICallHistory.WinHttpOptionTcpKeepAlive = (ptr->onoff, ptr->keepalivetime, ptr->keepaliveinterval); } return true; } public static bool WinHttpSetCredentials( SafeWinHttpHandle requestHandle, uint authTargets, uint authScheme, string userName, string password, IntPtr reserved) { return true; } public static bool WinHttpQueryAuthSchemes( SafeWinHttpHandle requestHandle, out uint supportedSchemes, out uint firstScheme, out uint authTarget) { supportedSchemes = 0; firstScheme = 0; authTarget = 0; return true; } public static bool WinHttpSetTimeouts( SafeWinHttpHandle handle, int resolveTimeout, int connectTimeout, int sendTimeout, int receiveTimeout) { return true; } public static bool WinHttpGetIEProxyConfigForCurrentUser( out Interop.WinHttp.WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig) { if (FakeRegistry.WinInetProxySettings.RegistryKeyMissing) { proxyConfig.AutoDetect = 0; proxyConfig.AutoConfigUrl = IntPtr.Zero; proxyConfig.Proxy = IntPtr.Zero; proxyConfig.ProxyBypass = IntPtr.Zero; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_FILE_NOT_FOUND; return false; } proxyConfig.AutoDetect = FakeRegistry.WinInetProxySettings.AutoDetect ? 1 : 0; proxyConfig.AutoConfigUrl = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.AutoConfigUrl); proxyConfig.Proxy = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.Proxy); proxyConfig.ProxyBypass = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.ProxyBypass); return true; } public static bool WinHttpGetProxyForUrl( SafeWinHttpHandle sessionHandle, string url, ref Interop.WinHttp.WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions, out Interop.WinHttp.WINHTTP_PROXY_INFO proxyInfo) { if (TestControl.PACFileNotDetectedOnNetwork) { proxyInfo.AccessType = WINHTTP_ACCESS_TYPE_NO_PROXY; proxyInfo.Proxy = IntPtr.Zero; proxyInfo.ProxyBypass = IntPtr.Zero; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_AUTODETECTION_FAILED; return false; } proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY; proxyInfo.Proxy = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.Proxy); proxyInfo.ProxyBypass = IntPtr.Zero; return true; } public static IntPtr WinHttpSetStatusCallback( SafeWinHttpHandle handle, Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback, uint notificationFlags, IntPtr reserved) { if (handle == null) { throw new ArgumentNullException(nameof(handle)); } var fakeHandle = (FakeSafeWinHttpHandle)handle; fakeHandle.Callback = callback; return IntPtr.Zero; } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSection.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; using System.IO; using System.Runtime.Versioning; using System.Xml; namespace System.Configuration { public abstract class ConfigurationSection : ConfigurationElement { protected ConfigurationSection() { SectionInformation = new SectionInformation(this); } public SectionInformation SectionInformation { get; } protected internal virtual object GetRuntimeObject() { return this; } protected internal override bool IsModified() { return SectionInformation.IsModifiedFlags() || base.IsModified(); } protected internal override void ResetModified() { SectionInformation.ResetModifiedFlags(); base.ResetModified(); } protected internal virtual void DeserializeSection(XmlReader reader) { if (!reader.Read() || (reader.NodeType != XmlNodeType.Element)) throw new ConfigurationErrorsException(SR.Config_base_expected_to_find_element, reader); DeserializeElement(reader, false); } protected internal virtual string SerializeSection(ConfigurationElement parentElement, string name, ConfigurationSaveMode saveMode) { if ((CurrentConfiguration != null) && (CurrentConfiguration.TargetFramework != null) && !ShouldSerializeSectionInTargetVersion(CurrentConfiguration.TargetFramework)) return string.Empty; ValidateElement(this, null, true); ConfigurationElement tempElement = CreateElement(GetType()); tempElement.Unmerge(this, parentElement, saveMode); StringWriter strWriter = new StringWriter(CultureInfo.InvariantCulture); XmlTextWriter writer = new XmlTextWriter(strWriter) { Formatting = Formatting.Indented, Indentation = 4, IndentChar = ' ' }; tempElement.DataToWriteInternal = saveMode != ConfigurationSaveMode.Minimal; if ((CurrentConfiguration != null) && (CurrentConfiguration.TargetFramework != null)) _configRecord.SectionsStack.Push(this); tempElement.SerializeToXmlElement(writer, name); if ((CurrentConfiguration != null) && (CurrentConfiguration.TargetFramework != null)) _configRecord.SectionsStack.Pop(); writer.Flush(); return strWriter.ToString(); } protected internal virtual bool ShouldSerializePropertyInTargetVersion(ConfigurationProperty property, string propertyName, FrameworkName targetFramework, ConfigurationElement parentConfigurationElement) { return true; } protected internal virtual bool ShouldSerializeElementInTargetVersion(ConfigurationElement element, string elementName, FrameworkName targetFramework) { return true; } protected internal virtual bool ShouldSerializeSectionInTargetVersion(FrameworkName targetFramework) { return true; } } }
// 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; using System.IO; using System.Runtime.Versioning; using System.Xml; namespace System.Configuration { public abstract class ConfigurationSection : ConfigurationElement { protected ConfigurationSection() { SectionInformation = new SectionInformation(this); } public SectionInformation SectionInformation { get; } protected internal virtual object GetRuntimeObject() { return this; } protected internal override bool IsModified() { return SectionInformation.IsModifiedFlags() || base.IsModified(); } protected internal override void ResetModified() { SectionInformation.ResetModifiedFlags(); base.ResetModified(); } protected internal virtual void DeserializeSection(XmlReader reader) { if (!reader.Read() || (reader.NodeType != XmlNodeType.Element)) throw new ConfigurationErrorsException(SR.Config_base_expected_to_find_element, reader); DeserializeElement(reader, false); } protected internal virtual string SerializeSection(ConfigurationElement parentElement, string name, ConfigurationSaveMode saveMode) { if ((CurrentConfiguration != null) && (CurrentConfiguration.TargetFramework != null) && !ShouldSerializeSectionInTargetVersion(CurrentConfiguration.TargetFramework)) return string.Empty; ValidateElement(this, null, true); ConfigurationElement tempElement = CreateElement(GetType()); tempElement.Unmerge(this, parentElement, saveMode); StringWriter strWriter = new StringWriter(CultureInfo.InvariantCulture); XmlTextWriter writer = new XmlTextWriter(strWriter) { Formatting = Formatting.Indented, Indentation = 4, IndentChar = ' ' }; tempElement.DataToWriteInternal = saveMode != ConfigurationSaveMode.Minimal; if ((CurrentConfiguration != null) && (CurrentConfiguration.TargetFramework != null)) _configRecord.SectionsStack.Push(this); tempElement.SerializeToXmlElement(writer, name); if ((CurrentConfiguration != null) && (CurrentConfiguration.TargetFramework != null)) _configRecord.SectionsStack.Pop(); writer.Flush(); return strWriter.ToString(); } protected internal virtual bool ShouldSerializePropertyInTargetVersion(ConfigurationProperty property, string propertyName, FrameworkName targetFramework, ConfigurationElement parentConfigurationElement) { return true; } protected internal virtual bool ShouldSerializeElementInTargetVersion(ConfigurationElement element, string elementName, FrameworkName targetFramework) { return true; } protected internal virtual bool ShouldSerializeSectionInTargetVersion(FrameworkName targetFramework) { return true; } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/tests/JIT/HardwareIntrinsics/X86/Sse1/CompareScalarOrderedGreaterThan.Boolean.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 CompareScalarOrderedGreaterThanBoolean() { var test = new BooleanBinaryOpTest__CompareScalarOrderedGreaterThanBoolean(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.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 (Sse.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 (Sse.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 (Sse.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 (Sse.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 (Sse.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 (Sse.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 BooleanBinaryOpTest__CompareScalarOrderedGreaterThanBoolean { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, 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 Dispose() { inHandle1.Free(); inHandle2.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 Vector128<Single> _fld2; 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>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(BooleanBinaryOpTest__CompareScalarOrderedGreaterThanBoolean testClass) { var result = Sse.CompareScalarOrderedGreaterThan(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } public void RunStructFldScenario_Load(BooleanBinaryOpTest__CompareScalarOrderedGreaterThanBoolean testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareScalarOrderedGreaterThan( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); testClass.ValidateResult(_fld1, _fld2, result); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static BooleanBinaryOpTest__CompareScalarOrderedGreaterThanBoolean() { 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>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public BooleanBinaryOpTest__CompareScalarOrderedGreaterThanBoolean() { 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 < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse.CompareScalarOrderedGreaterThan( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse.CompareScalarOrderedGreaterThan( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse.CompareScalarOrderedGreaterThan( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarOrderedGreaterThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarOrderedGreaterThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarOrderedGreaterThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse.CompareScalarOrderedGreaterThan( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse.CompareScalarOrderedGreaterThan( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); ValidateResult(_clsVar1, _clsVar2, result); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.CompareScalarOrderedGreaterThan(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareScalarOrderedGreaterThan(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareScalarOrderedGreaterThan(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new BooleanBinaryOpTest__CompareScalarOrderedGreaterThanBoolean(); var result = Sse.CompareScalarOrderedGreaterThan(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new BooleanBinaryOpTest__CompareScalarOrderedGreaterThanBoolean(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse.CompareScalarOrderedGreaterThan( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); ValidateResult(test._fld1, test._fld2, result); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse.CompareScalarOrderedGreaterThan(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareScalarOrderedGreaterThan( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); ValidateResult(_fld1, _fld2, result); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse.CompareScalarOrderedGreaterThan(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse.CompareScalarOrderedGreaterThan( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); ValidateResult(test._fld1, test._fld2, result); } 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, Vector128<Single> op2, bool result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; 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 inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Single[] left, Single[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; if ((left[0] > right[0]) != result) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.CompareScalarOrderedGreaterThan)}<Boolean>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({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 CompareScalarOrderedGreaterThanBoolean() { var test = new BooleanBinaryOpTest__CompareScalarOrderedGreaterThanBoolean(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.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 (Sse.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 (Sse.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 (Sse.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 (Sse.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 (Sse.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 (Sse.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 BooleanBinaryOpTest__CompareScalarOrderedGreaterThanBoolean { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, 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 Dispose() { inHandle1.Free(); inHandle2.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 Vector128<Single> _fld2; 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>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(BooleanBinaryOpTest__CompareScalarOrderedGreaterThanBoolean testClass) { var result = Sse.CompareScalarOrderedGreaterThan(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } public void RunStructFldScenario_Load(BooleanBinaryOpTest__CompareScalarOrderedGreaterThanBoolean testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareScalarOrderedGreaterThan( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); testClass.ValidateResult(_fld1, _fld2, result); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static BooleanBinaryOpTest__CompareScalarOrderedGreaterThanBoolean() { 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>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public BooleanBinaryOpTest__CompareScalarOrderedGreaterThanBoolean() { 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 < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse.CompareScalarOrderedGreaterThan( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse.CompareScalarOrderedGreaterThan( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse.CompareScalarOrderedGreaterThan( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarOrderedGreaterThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarOrderedGreaterThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarOrderedGreaterThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse.CompareScalarOrderedGreaterThan( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse.CompareScalarOrderedGreaterThan( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); ValidateResult(_clsVar1, _clsVar2, result); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.CompareScalarOrderedGreaterThan(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareScalarOrderedGreaterThan(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareScalarOrderedGreaterThan(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new BooleanBinaryOpTest__CompareScalarOrderedGreaterThanBoolean(); var result = Sse.CompareScalarOrderedGreaterThan(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new BooleanBinaryOpTest__CompareScalarOrderedGreaterThanBoolean(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse.CompareScalarOrderedGreaterThan( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); ValidateResult(test._fld1, test._fld2, result); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse.CompareScalarOrderedGreaterThan(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareScalarOrderedGreaterThan( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); ValidateResult(_fld1, _fld2, result); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse.CompareScalarOrderedGreaterThan(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse.CompareScalarOrderedGreaterThan( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); ValidateResult(test._fld1, test._fld2, result); } 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, Vector128<Single> op2, bool result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; 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 inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Single[] left, Single[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; if ((left[0] > right[0]) != result) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.CompareScalarOrderedGreaterThan)}<Boolean>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/RoundToZero.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 RoundToZero_Vector128_Single() { var test = new SimpleUnaryOpTest__RoundToZero_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__RoundToZero_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__RoundToZero_Vector128_Single testClass) { var result = AdvSimd.RoundToZero(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToZero_Vector128_Single testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) { var result = AdvSimd.RoundToZero( 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<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__RoundToZero_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__RoundToZero_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.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.RoundToZero( 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.RoundToZero( 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).GetMethod(nameof(AdvSimd.RoundToZero), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.RoundToZero), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.RoundToZero( _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.RoundToZero( 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.RoundToZero(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.RoundToZero(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__RoundToZero_Vector128_Single(); var result = AdvSimd.RoundToZero(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__RoundToZero_Vector128_Single(); fixed (Vector128<Single>* pFld1 = &test._fld1) { var result = AdvSimd.RoundToZero( 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.RoundToZero(_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.RoundToZero( 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.RoundToZero(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.RoundToZero( 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<Vector128<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<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(Helpers.RoundToZero(firstOp[i])) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.RoundToZero)}<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 RoundToZero_Vector128_Single() { var test = new SimpleUnaryOpTest__RoundToZero_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__RoundToZero_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__RoundToZero_Vector128_Single testClass) { var result = AdvSimd.RoundToZero(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToZero_Vector128_Single testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) { var result = AdvSimd.RoundToZero( 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<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__RoundToZero_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__RoundToZero_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.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.RoundToZero( 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.RoundToZero( 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).GetMethod(nameof(AdvSimd.RoundToZero), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.RoundToZero), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.RoundToZero( _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.RoundToZero( 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.RoundToZero(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.RoundToZero(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__RoundToZero_Vector128_Single(); var result = AdvSimd.RoundToZero(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__RoundToZero_Vector128_Single(); fixed (Vector128<Single>* pFld1 = &test._fld1) { var result = AdvSimd.RoundToZero( 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.RoundToZero(_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.RoundToZero( 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.RoundToZero(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.RoundToZero( 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<Vector128<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<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(Helpers.RoundToZero(firstOp[i])) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.RoundToZero)}<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,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/coreclr/System.Private.CoreLib/src/System/Reflection/AssemblyName.CoreCLR.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.Configuration.Assemblies; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace System.Reflection { public sealed partial class AssemblyName : ICloneable, IDeserializationCallback, ISerializable { internal AssemblyName(string? name, byte[]? publicKey, byte[]? publicKeyToken, Version? version, CultureInfo? cultureInfo, AssemblyHashAlgorithm hashAlgorithm, AssemblyVersionCompatibility versionCompatibility, string? codeBase, AssemblyNameFlags flags) { _name = name; _publicKey = publicKey; _publicKeyToken = publicKeyToken; _version = version; _cultureInfo = cultureInfo; _hashAlgorithm = hashAlgorithm; _versionCompatibility = versionCompatibility; _codeBase = codeBase; _flags = flags; } internal void SetProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm) { #pragma warning disable SYSLIB0037 // AssemblyName.ProcessorArchitecture is obsolete ProcessorArchitecture = CalculateProcArchIndex(pek, ifm, _flags); #pragma warning restore SYSLIB0037 } internal static ProcessorArchitecture CalculateProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm, AssemblyNameFlags flags) { if (((uint)flags & 0xF0) == 0x70) return ProcessorArchitecture.None; if ((pek & PortableExecutableKinds.PE32Plus) == PortableExecutableKinds.PE32Plus) { switch (ifm) { case ImageFileMachine.IA64: return ProcessorArchitecture.IA64; case ImageFileMachine.AMD64: return ProcessorArchitecture.Amd64; case ImageFileMachine.I386: if ((pek & PortableExecutableKinds.ILOnly) == PortableExecutableKinds.ILOnly) return ProcessorArchitecture.MSIL; break; } } else { if (ifm == ImageFileMachine.I386) { if ((pek & PortableExecutableKinds.Required32Bit) == PortableExecutableKinds.Required32Bit) return ProcessorArchitecture.X86; if ((pek & PortableExecutableKinds.ILOnly) == PortableExecutableKinds.ILOnly) return ProcessorArchitecture.MSIL; return ProcessorArchitecture.X86; } if (ifm == ImageFileMachine.ARM) { return ProcessorArchitecture.Arm; } } return ProcessorArchitecture.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.Configuration.Assemblies; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace System.Reflection { public sealed partial class AssemblyName : ICloneable, IDeserializationCallback, ISerializable { internal AssemblyName(string? name, byte[]? publicKey, byte[]? publicKeyToken, Version? version, CultureInfo? cultureInfo, AssemblyHashAlgorithm hashAlgorithm, AssemblyVersionCompatibility versionCompatibility, string? codeBase, AssemblyNameFlags flags) { _name = name; _publicKey = publicKey; _publicKeyToken = publicKeyToken; _version = version; _cultureInfo = cultureInfo; _hashAlgorithm = hashAlgorithm; _versionCompatibility = versionCompatibility; _codeBase = codeBase; _flags = flags; } internal void SetProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm) { #pragma warning disable SYSLIB0037 // AssemblyName.ProcessorArchitecture is obsolete ProcessorArchitecture = CalculateProcArchIndex(pek, ifm, _flags); #pragma warning restore SYSLIB0037 } internal static ProcessorArchitecture CalculateProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm, AssemblyNameFlags flags) { if (((uint)flags & 0xF0) == 0x70) return ProcessorArchitecture.None; if ((pek & PortableExecutableKinds.PE32Plus) == PortableExecutableKinds.PE32Plus) { switch (ifm) { case ImageFileMachine.IA64: return ProcessorArchitecture.IA64; case ImageFileMachine.AMD64: return ProcessorArchitecture.Amd64; case ImageFileMachine.I386: if ((pek & PortableExecutableKinds.ILOnly) == PortableExecutableKinds.ILOnly) return ProcessorArchitecture.MSIL; break; } } else { if (ifm == ImageFileMachine.I386) { if ((pek & PortableExecutableKinds.Required32Bit) == PortableExecutableKinds.Required32Bit) return ProcessorArchitecture.X86; if ((pek & PortableExecutableKinds.ILOnly) == PortableExecutableKinds.ILOnly) return ProcessorArchitecture.MSIL; return ProcessorArchitecture.X86; } if (ifm == ImageFileMachine.ARM) { return ProcessorArchitecture.Arm; } } return ProcessorArchitecture.None; } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Data.Common/src/System/Data/Common/SQLTypes/SQLBinaryStorage.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.Xml; using System.Data.SqlTypes; using System.Diagnostics; using System.IO; using System.Xml.Serialization; using System.Collections; using System.Diagnostics.CodeAnalysis; namespace System.Data.Common { internal sealed class SqlBinaryStorage : DataStorage { private SqlBinary[] _values = default!; // Late-initialized public SqlBinaryStorage(DataColumn column) : base(column, typeof(SqlBinary), SqlBinary.Null, SqlBinary.Null, StorageType.SqlBinary) { } public override object Aggregate(int[] records, AggregateType kind) { try { switch (kind) { case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } return null!; case AggregateType.Count: int count = 0; for (int i = 0; i < records.Length; i++) { if (!IsNull(records[i])) count++; } return count; } } catch (OverflowException) { throw ExprException.Overflow(typeof(SqlBinary)); } throw ExceptionBuilder.AggregateException(kind, _dataType); } public override int Compare(int recordNo1, int recordNo2) { return _values[recordNo1].CompareTo(_values[recordNo2]); } public override int CompareValueTo(int recordNo, object? value) { Debug.Assert(null != value, "null value"); return _values[recordNo].CompareTo((SqlBinary)value); } public override object ConvertValue(object? value) { if (null != value) { return SqlConvert.ConvertToSqlBinary(value); } return _nullValue; } public override void Copy(int recordNo1, int recordNo2) { _values[recordNo2] = _values[recordNo1]; } public override object Get(int record) { return _values[record]; } public override bool IsNull(int record) { return (_values[record].IsNull); } public override void Set(int record, object value) { _values[record] = SqlConvert.ConvertToSqlBinary(value); } public override void SetCapacity(int capacity) { SqlBinary[] newValues = new SqlBinary[capacity]; if (null != _values) { Array.Copy(_values, newValues, Math.Min(capacity, _values.Length)); } _values = newValues; } [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] public override object ConvertXmlToObject(string s) { SqlBinary newValue = default; string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader StringReader strReader = new StringReader(tempStr); IXmlSerializable tmp = newValue; using (XmlTextReader xmlTextReader = new XmlTextReader(strReader)) { tmp.ReadXml(xmlTextReader); } return ((SqlBinary)tmp); } [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] public override string ConvertObjectToXml(object value) { Debug.Assert(!DataStorage.IsObjectNull(value), "we should have null here"); Debug.Assert((value.GetType() == typeof(SqlBinary)), "wrong input type"); StringWriter strwriter = new StringWriter(FormatProvider); using (XmlTextWriter xmlTextWriter = new XmlTextWriter(strwriter)) { ((IXmlSerializable)value).WriteXml(xmlTextWriter); } return (strwriter.ToString()); } protected override object GetEmptyStorage(int recordCount) { return new SqlBinary[recordCount]; } protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { SqlBinary[] typedStore = (SqlBinary[])store; typedStore[storeIndex] = _values[record]; nullbits.Set(storeIndex, IsNull(record)); } protected override void SetStorage(object store, BitArray nullbits) { _values = (SqlBinary[])store; //SetNullStorage(nullbits); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Xml; using System.Data.SqlTypes; using System.Diagnostics; using System.IO; using System.Xml.Serialization; using System.Collections; using System.Diagnostics.CodeAnalysis; namespace System.Data.Common { internal sealed class SqlBinaryStorage : DataStorage { private SqlBinary[] _values = default!; // Late-initialized public SqlBinaryStorage(DataColumn column) : base(column, typeof(SqlBinary), SqlBinary.Null, SqlBinary.Null, StorageType.SqlBinary) { } public override object Aggregate(int[] records, AggregateType kind) { try { switch (kind) { case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } return null!; case AggregateType.Count: int count = 0; for (int i = 0; i < records.Length; i++) { if (!IsNull(records[i])) count++; } return count; } } catch (OverflowException) { throw ExprException.Overflow(typeof(SqlBinary)); } throw ExceptionBuilder.AggregateException(kind, _dataType); } public override int Compare(int recordNo1, int recordNo2) { return _values[recordNo1].CompareTo(_values[recordNo2]); } public override int CompareValueTo(int recordNo, object? value) { Debug.Assert(null != value, "null value"); return _values[recordNo].CompareTo((SqlBinary)value); } public override object ConvertValue(object? value) { if (null != value) { return SqlConvert.ConvertToSqlBinary(value); } return _nullValue; } public override void Copy(int recordNo1, int recordNo2) { _values[recordNo2] = _values[recordNo1]; } public override object Get(int record) { return _values[record]; } public override bool IsNull(int record) { return (_values[record].IsNull); } public override void Set(int record, object value) { _values[record] = SqlConvert.ConvertToSqlBinary(value); } public override void SetCapacity(int capacity) { SqlBinary[] newValues = new SqlBinary[capacity]; if (null != _values) { Array.Copy(_values, newValues, Math.Min(capacity, _values.Length)); } _values = newValues; } [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] public override object ConvertXmlToObject(string s) { SqlBinary newValue = default; string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader StringReader strReader = new StringReader(tempStr); IXmlSerializable tmp = newValue; using (XmlTextReader xmlTextReader = new XmlTextReader(strReader)) { tmp.ReadXml(xmlTextReader); } return ((SqlBinary)tmp); } [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] public override string ConvertObjectToXml(object value) { Debug.Assert(!DataStorage.IsObjectNull(value), "we should have null here"); Debug.Assert((value.GetType() == typeof(SqlBinary)), "wrong input type"); StringWriter strwriter = new StringWriter(FormatProvider); using (XmlTextWriter xmlTextWriter = new XmlTextWriter(strwriter)) { ((IXmlSerializable)value).WriteXml(xmlTextWriter); } return (strwriter.ToString()); } protected override object GetEmptyStorage(int recordCount) { return new SqlBinary[recordCount]; } protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { SqlBinary[] typedStore = (SqlBinary[])store; typedStore[storeIndex] = _values[record]; nullbits.Set(storeIndex, IsNull(record)); } protected override void SetStorage(object store, BitArray nullbits) { _values = (SqlBinary[])store; //SetNullStorage(nullbits); } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Net.Requests/src/System/Net/IAuthenticationModule.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.Net { public interface IAuthenticationModule { Authorization? Authenticate(string challenge, WebRequest request, ICredentials credentials); Authorization? PreAuthenticate(WebRequest request, ICredentials credentials); bool CanPreAuthenticate { get; } string AuthenticationType { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Net { public interface IAuthenticationModule { Authorization? Authenticate(string challenge, WebRequest request, ICredentials credentials); Authorization? PreAuthenticate(WebRequest request, ICredentials credentials); bool CanPreAuthenticate { get; } string AuthenticationType { get; } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/mono/mono/tests/tailcall-interface.cs
/* Author: Jay Krell ([email protected]) Copyright 2018 Microsoft Licensed under the MIT license. See LICENSE file in the project root for full license information. */ using System; using System.Runtime.CompilerServices; using static System.Runtime.CompilerServices.MethodImplOptions; public struct Point { public int x; public int y; } interface I1 { void perturb_interface_offset1 ( ); [MethodImpl (NoInlining)] int F1 (I2 i2, long counter, long initial_stack, long current_stack = 0); [MethodImpl (NoInlining)] int GF1<TF> (I2 i2, long counter, long initial_stack, long current_stack = 0); } interface GI1<TC> { void perturb_interface_offset1 ( ); void perturb_interface_offset2 ( ); [MethodImpl (NoInlining)] int F1 (GI2<TC> i2, long counter, long initial_stack, long current_stack = 0); [MethodImpl (NoInlining)] int GF1<TF> (GI2<TC> i2, long counter, long initial_stack, long current_stack = 0); [MethodImpl (NoInlining)] int HF1<TF> (GI2<TF> i2, long counter, long initial_stack, long current_stack = 0); } interface I2 { void perturb_interface_offset1 ( ); void perturb_interface_offset2 ( ); void perturb_interface_offset3 ( ); [MethodImpl (NoInlining)] int F2 (I1 i1, long counter, long initial_stack, long current_stack = 0); [MethodImpl (NoInlining)] int GF2<TF> (I1 i1, long counter, long initial_stack, long current_stack = 0); } interface GI2<TC> { void perturb_interface_offset1 ( ); void perturb_interface_offset2 ( ); void perturb_interface_offset3 ( ); void perturb_interface_offset4 ( ); [MethodImpl (NoInlining)] int F2 (GI1<TC> i1, long counter, long initial_stack, long current_stack = 0); [MethodImpl (NoInlining)] int GF2<TF> (GI1<TC> i1, long counter, long initial_stack, long current_stack = 0); [MethodImpl (NoInlining)] int HF2<TF> (GI1<TF> i1, long counter, long initial_stack, long current_stack = 0); } unsafe public class C1 : I1 { void I1.perturb_interface_offset1 ( ) { } static int i; static public int errors; public static int check (long stack1, long stack2) { // NOTE: This is odd in order to feed into the edited IL. ++i; if (stack1 != 0) return 0; int error = (stack1 != stack2) ? 1 : 0; if (error == 0) return 0; errors += 1; Console.WriteLine ("{0} tailcall failure", i); return error; } [MethodImpl (NoInlining)] int I1.F1 (I2 i2, long counter, long initial_stack, long current_stack) { if (counter > 0) return i2.F2 (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } [MethodImpl (NoInlining)] int I1.GF1<TF> (I2 i2, long counter, long initial_stack, long current_stack) { if (counter > 0) return i2.GF2<TF> (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } } unsafe public class GC1<TC> : GI1<TC> { void GI1<TC>.perturb_interface_offset1 ( ) { } void GI1<TC>.perturb_interface_offset2 ( ) { } public static int check (long stack1, long stack2) { return C1.check (stack1, stack2); } [MethodImpl (NoInlining)] int GI1<TC>.F1 (GI2<TC> i2, long counter, long initial_stack, long current_stack) { if (counter > 0) return i2.F2 (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } [MethodImpl (NoInlining)] int GI1<TC>.GF1<TF> (GI2<TC> i2, long counter, long initial_stack, long current_stack) { if (counter > 0) return i2.GF2<TF> (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } [MethodImpl (NoInlining)] int GI1<TC>.HF1<TF> (GI2<TF> i2, long counter, long initial_stack, long current_stack) { if (counter > 0) return i2.HF2<TC> (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } } unsafe public class C2 : I2 { void I2.perturb_interface_offset1 ( ) { } void I2.perturb_interface_offset2 ( ) { } void I2.perturb_interface_offset3 ( ) { } static int check (long stack1, long stack2) { return C1.check (stack1, stack2); } [MethodImpl (NoInlining)] int I2.F2 (I1 i1, long counter, long initial_stack, long current_stack) { if (counter > 0) return i1.F1 (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } [MethodImpl (NoInlining)] int I2.GF2<TF> (I1 i1, long counter, long initial_stack, long current_stack) { if (counter > 0) return i1.GF1<TF> (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } } unsafe public class GC2<TC> : GI2<TC> { void GI2<TC>.perturb_interface_offset1 ( ) { } void GI2<TC>.perturb_interface_offset2 ( ) { } void GI2<TC>.perturb_interface_offset3 ( ) { } void GI2<TC>.perturb_interface_offset4 ( ) { } public static int check (long stack1, long stack2) { return C1.check (stack1, stack2); } [MethodImpl (NoInlining)] int GI2<TC>.F2 (GI1<TC> i1, long counter, long initial_stack, long current_stack) { if (counter > 0) return i1.F1 (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } [MethodImpl (NoInlining)] int GI2<TC>.GF2<TF> (GI1<TC> i1, long counter, long initial_stack, long current_stack) { if (counter > 0) return i1.GF1<TF> (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } [MethodImpl (NoInlining)] int GI2<TC>.HF2<TF> (GI1<TF> i1, long counter, long initial_stack, long current_stack) { if (counter > 0) return i1.HF1<TC> (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } } public class A { } public class B { } interface IC { [MethodImpl (NoInlining)] T cast1<T> (object o, long counter = 100, long stack = 0); [MethodImpl (NoInlining)] B cast2 (object o, long counter = 100, long stack = 0); [MethodImpl (NoInlining)] T cast3<T> (object o, long counter = 100, long stack = 0); [MethodImpl (NoInlining)] B[] cast4 (object o, long counter = 100, long stack = 0); [MethodImpl (NoInlining)] T[] cast5<T> (object o, long counter = 100, long stack = 0); } unsafe public class C { [MethodImpl (NoInlining)] public static void check (long stack1, long stack2) { C1.check (stack1, stack2); } [MethodImpl (NoInlining)] public T cast1<T> (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast1<T> (o, counter - 1, (long)&counter); check ((long)&counter, stack); return (T)o; } [MethodImpl (NoInlining)] public B cast2 (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast2 (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<B> (o); } [MethodImpl (NoInlining)] public T cast3<T> (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast3<T> (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<T> (o); } [MethodImpl (NoInlining)] public B[] cast4 (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast4 (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<B[]> (o); } [MethodImpl (NoInlining)] public T[] cast5<T> (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast5<T> (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<T[]> (o); } } unsafe public class D<T1> { [MethodImpl (NoInlining)] public static void check (long stack1, long stack2) { C.check (stack1, stack2); } [MethodImpl (NoInlining)] public static T cast1<T> (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast1<T> (o, counter - 1, (long)&counter); check ((long)&counter, stack); return (T)o; } [MethodImpl (NoInlining)] public B cast2 (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast2 (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<B> (o); } [MethodImpl (NoInlining)] public T cast3<T> (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast3<T> (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<T> (o); } [MethodImpl (NoInlining)] public B[] cast4 (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast4 (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<B[]> (o); } [MethodImpl (NoInlining)] public T[] cast5<T> (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast5<T> (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<T[]> (o); } [MethodImpl (NoInlining)] public T1 cast6 (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast6 (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<T1> (o); } [MethodImpl (NoInlining)] public T1 cast7<T> (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast7<T> (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<T1> (o); } [MethodImpl (NoInlining)] public T1[] cast8 (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast8 (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast3<T1[]> (o); } [MethodImpl (NoInlining)] public T1[] cast9<T> (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast9<T> (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast3<T1[]> (o); } } unsafe class C3 { int i; [MethodImpl (NoInlining)] void print (object o) { ++i; //Console.WriteLine("{0} {1}", i, o); //Console.WriteLine(i); } [MethodImpl (NoInlining)] public void Main() { var da = new D<A> (); var db = new D<B> (); var dba = new D<B[]> (); var c = new C (); var b = new B (); var ba = new B [1]; int stack; var c1 = (I1)new C1 (); var c2 = (I2)new C2 (); int result; var c1o = (GI1<object>)new GC1<object> (); var c1oa = (GI1<object[]>)new GC1<object[]> (); var c1i = (GI1<int>)new GC1<int> (); var c1ia = (GI1<int[]>)new GC1<int[]> (); var c1s = (GI1<Point>)new GC1<Point> (); var c1sa = (GI1<Point[]>)new GC1<Point[]> (); var c2o = (GI2<object>)new GC2<object> (); var c2oa = (GI2<object[]>)new GC2<object[]> (); var c2i = (GI2<int>)new GC2<int> (); var c2ia = (GI2<int[]>)new GC2<int[]> (); var c2s = (GI2<Point>)new GC2<Point> (); var c2sa = (GI2<Point[]>)new GC2<Point[]> (); print (da.cast2 (b)); print (da.cast3<B> (b)); print (da.cast3<B[]> (ba)); print (da.cast4 (ba)); print (da.cast5<B> (ba)); print (db.cast6 (b)); print (db.cast7<A> (b)); print (dba.cast7<A[]> (ba)); print (db.cast8 (ba)); print (db.cast9<A> (ba)); print (c.cast2 (b)); print (c.cast3<B> (b)); print (c.cast3<B[]> (ba)); print (c.cast4 (ba)); print (c.cast5<B> (ba)); //Console.WriteLine("done"); //Console.WriteLine("success"); result = c1.F1 (c2, 100, (long)&stack, 0) + c1.GF1<object> (c2, 100, (long)&stack, 0) + c1.GF1<A> (c2, 100, (long)&stack, 0) + c1.GF1<A[]> (c2, 100, (long)&stack, 0) + c1.GF1<int> (c2, 100, (long)&stack, 0) + c1.GF1<int[]> (c2, 100, (long)&stack, 0) + c1o.F1 (c2o, 100, (long)&stack) + c1o.GF1<object> (c2o, 100, (long)&stack) + c1o.GF1<A> (c2o, 100, (long)&stack) + c1o.GF1<A[]> (c2o, 100, (long)&stack) + c1o.GF1<int> (c2o, 100, (long)&stack) + c1o.GF1<int[]> (c2o, 100, (long)&stack) + c1oa.GF1<object[]> (c2oa, 100, (long)&stack) + c1oa.GF1<A> (c2oa, 100, (long)&stack) + c1oa.GF1<A[]> (c2oa, 100, (long)&stack) + c1oa.GF1<int> (c2oa, 100, (long)&stack) + c1oa.GF1<int[]> (c2oa, 100, (long)&stack) + c1i.GF1<object> (c2i, 100, (long)&stack) + c1i.GF1<A> (c2i, 100, (long)&stack) + c1i.GF1<A[]> (c2i, 100, (long)&stack) + c1i.GF1<int> (c2i, 100, (long)&stack) + c1i.GF1<int[]> (c2i, 100, (long)&stack) + c1ia.GF1<object> (c2ia, 100, (long)&stack) + c1ia.GF1<A> (c2ia, 100, (long)&stack) + c1ia.GF1<A[]> (c2ia, 100, (long)&stack) + c1ia.GF1<int> (c2ia, 100, (long)&stack) + c1ia.GF1<int[]> (c2ia, 100, (long)&stack) + c1s.GF1<object> (c2s, 100, (long)&stack) + c1s.GF1<A> (c2s, 100, (long)&stack) + c1s.GF1<A[]> (c2s, 100, (long)&stack) + c1s.GF1<int> (c2s, 100, (long)&stack) + c1s.GF1<int[]> (c2s, 100, (long)&stack) + c1sa.GF1<object> (c2sa, 100, (long)&stack) + c1sa.GF1<A> (c2sa, 100, (long)&stack) + c1sa.GF1<A[]> (c2sa, 100, (long)&stack) + c1sa.GF1<int> (c2sa, 100, (long)&stack) + c1sa.GF1<int[]> (c2sa, 100, (long)&stack) + C1.errors; //Console.WriteLine (result == 0 ? "success" : "failure {0}", result); Environment.Exit (result); } [MethodImpl (NoInlining)] public static void Main(string[] args) { new C3 ().Main (); } }
/* Author: Jay Krell ([email protected]) Copyright 2018 Microsoft Licensed under the MIT license. See LICENSE file in the project root for full license information. */ using System; using System.Runtime.CompilerServices; using static System.Runtime.CompilerServices.MethodImplOptions; public struct Point { public int x; public int y; } interface I1 { void perturb_interface_offset1 ( ); [MethodImpl (NoInlining)] int F1 (I2 i2, long counter, long initial_stack, long current_stack = 0); [MethodImpl (NoInlining)] int GF1<TF> (I2 i2, long counter, long initial_stack, long current_stack = 0); } interface GI1<TC> { void perturb_interface_offset1 ( ); void perturb_interface_offset2 ( ); [MethodImpl (NoInlining)] int F1 (GI2<TC> i2, long counter, long initial_stack, long current_stack = 0); [MethodImpl (NoInlining)] int GF1<TF> (GI2<TC> i2, long counter, long initial_stack, long current_stack = 0); [MethodImpl (NoInlining)] int HF1<TF> (GI2<TF> i2, long counter, long initial_stack, long current_stack = 0); } interface I2 { void perturb_interface_offset1 ( ); void perturb_interface_offset2 ( ); void perturb_interface_offset3 ( ); [MethodImpl (NoInlining)] int F2 (I1 i1, long counter, long initial_stack, long current_stack = 0); [MethodImpl (NoInlining)] int GF2<TF> (I1 i1, long counter, long initial_stack, long current_stack = 0); } interface GI2<TC> { void perturb_interface_offset1 ( ); void perturb_interface_offset2 ( ); void perturb_interface_offset3 ( ); void perturb_interface_offset4 ( ); [MethodImpl (NoInlining)] int F2 (GI1<TC> i1, long counter, long initial_stack, long current_stack = 0); [MethodImpl (NoInlining)] int GF2<TF> (GI1<TC> i1, long counter, long initial_stack, long current_stack = 0); [MethodImpl (NoInlining)] int HF2<TF> (GI1<TF> i1, long counter, long initial_stack, long current_stack = 0); } unsafe public class C1 : I1 { void I1.perturb_interface_offset1 ( ) { } static int i; static public int errors; public static int check (long stack1, long stack2) { // NOTE: This is odd in order to feed into the edited IL. ++i; if (stack1 != 0) return 0; int error = (stack1 != stack2) ? 1 : 0; if (error == 0) return 0; errors += 1; Console.WriteLine ("{0} tailcall failure", i); return error; } [MethodImpl (NoInlining)] int I1.F1 (I2 i2, long counter, long initial_stack, long current_stack) { if (counter > 0) return i2.F2 (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } [MethodImpl (NoInlining)] int I1.GF1<TF> (I2 i2, long counter, long initial_stack, long current_stack) { if (counter > 0) return i2.GF2<TF> (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } } unsafe public class GC1<TC> : GI1<TC> { void GI1<TC>.perturb_interface_offset1 ( ) { } void GI1<TC>.perturb_interface_offset2 ( ) { } public static int check (long stack1, long stack2) { return C1.check (stack1, stack2); } [MethodImpl (NoInlining)] int GI1<TC>.F1 (GI2<TC> i2, long counter, long initial_stack, long current_stack) { if (counter > 0) return i2.F2 (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } [MethodImpl (NoInlining)] int GI1<TC>.GF1<TF> (GI2<TC> i2, long counter, long initial_stack, long current_stack) { if (counter > 0) return i2.GF2<TF> (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } [MethodImpl (NoInlining)] int GI1<TC>.HF1<TF> (GI2<TF> i2, long counter, long initial_stack, long current_stack) { if (counter > 0) return i2.HF2<TC> (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } } unsafe public class C2 : I2 { void I2.perturb_interface_offset1 ( ) { } void I2.perturb_interface_offset2 ( ) { } void I2.perturb_interface_offset3 ( ) { } static int check (long stack1, long stack2) { return C1.check (stack1, stack2); } [MethodImpl (NoInlining)] int I2.F2 (I1 i1, long counter, long initial_stack, long current_stack) { if (counter > 0) return i1.F1 (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } [MethodImpl (NoInlining)] int I2.GF2<TF> (I1 i1, long counter, long initial_stack, long current_stack) { if (counter > 0) return i1.GF1<TF> (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } } unsafe public class GC2<TC> : GI2<TC> { void GI2<TC>.perturb_interface_offset1 ( ) { } void GI2<TC>.perturb_interface_offset2 ( ) { } void GI2<TC>.perturb_interface_offset3 ( ) { } void GI2<TC>.perturb_interface_offset4 ( ) { } public static int check (long stack1, long stack2) { return C1.check (stack1, stack2); } [MethodImpl (NoInlining)] int GI2<TC>.F2 (GI1<TC> i1, long counter, long initial_stack, long current_stack) { if (counter > 0) return i1.F1 (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } [MethodImpl (NoInlining)] int GI2<TC>.GF2<TF> (GI1<TC> i1, long counter, long initial_stack, long current_stack) { if (counter > 0) return i1.GF1<TF> (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } [MethodImpl (NoInlining)] int GI2<TC>.HF2<TF> (GI1<TF> i1, long counter, long initial_stack, long current_stack) { if (counter > 0) return i1.HF1<TC> (this, counter - 1, initial_stack, (long)&counter); return check ((long)&counter, current_stack); } } public class A { } public class B { } interface IC { [MethodImpl (NoInlining)] T cast1<T> (object o, long counter = 100, long stack = 0); [MethodImpl (NoInlining)] B cast2 (object o, long counter = 100, long stack = 0); [MethodImpl (NoInlining)] T cast3<T> (object o, long counter = 100, long stack = 0); [MethodImpl (NoInlining)] B[] cast4 (object o, long counter = 100, long stack = 0); [MethodImpl (NoInlining)] T[] cast5<T> (object o, long counter = 100, long stack = 0); } unsafe public class C { [MethodImpl (NoInlining)] public static void check (long stack1, long stack2) { C1.check (stack1, stack2); } [MethodImpl (NoInlining)] public T cast1<T> (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast1<T> (o, counter - 1, (long)&counter); check ((long)&counter, stack); return (T)o; } [MethodImpl (NoInlining)] public B cast2 (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast2 (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<B> (o); } [MethodImpl (NoInlining)] public T cast3<T> (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast3<T> (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<T> (o); } [MethodImpl (NoInlining)] public B[] cast4 (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast4 (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<B[]> (o); } [MethodImpl (NoInlining)] public T[] cast5<T> (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast5<T> (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<T[]> (o); } } unsafe public class D<T1> { [MethodImpl (NoInlining)] public static void check (long stack1, long stack2) { C.check (stack1, stack2); } [MethodImpl (NoInlining)] public static T cast1<T> (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast1<T> (o, counter - 1, (long)&counter); check ((long)&counter, stack); return (T)o; } [MethodImpl (NoInlining)] public B cast2 (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast2 (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<B> (o); } [MethodImpl (NoInlining)] public T cast3<T> (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast3<T> (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<T> (o); } [MethodImpl (NoInlining)] public B[] cast4 (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast4 (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<B[]> (o); } [MethodImpl (NoInlining)] public T[] cast5<T> (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast5<T> (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<T[]> (o); } [MethodImpl (NoInlining)] public T1 cast6 (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast6 (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<T1> (o); } [MethodImpl (NoInlining)] public T1 cast7<T> (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast7<T> (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast1<T1> (o); } [MethodImpl (NoInlining)] public T1[] cast8 (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast8 (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast3<T1[]> (o); } [MethodImpl (NoInlining)] public T1[] cast9<T> (object o, long counter = 100, long stack = 0) { if (counter > 0) return cast9<T> (o, counter - 1, (long)&counter); check ((long)&counter, stack); return cast3<T1[]> (o); } } unsafe class C3 { int i; [MethodImpl (NoInlining)] void print (object o) { ++i; //Console.WriteLine("{0} {1}", i, o); //Console.WriteLine(i); } [MethodImpl (NoInlining)] public void Main() { var da = new D<A> (); var db = new D<B> (); var dba = new D<B[]> (); var c = new C (); var b = new B (); var ba = new B [1]; int stack; var c1 = (I1)new C1 (); var c2 = (I2)new C2 (); int result; var c1o = (GI1<object>)new GC1<object> (); var c1oa = (GI1<object[]>)new GC1<object[]> (); var c1i = (GI1<int>)new GC1<int> (); var c1ia = (GI1<int[]>)new GC1<int[]> (); var c1s = (GI1<Point>)new GC1<Point> (); var c1sa = (GI1<Point[]>)new GC1<Point[]> (); var c2o = (GI2<object>)new GC2<object> (); var c2oa = (GI2<object[]>)new GC2<object[]> (); var c2i = (GI2<int>)new GC2<int> (); var c2ia = (GI2<int[]>)new GC2<int[]> (); var c2s = (GI2<Point>)new GC2<Point> (); var c2sa = (GI2<Point[]>)new GC2<Point[]> (); print (da.cast2 (b)); print (da.cast3<B> (b)); print (da.cast3<B[]> (ba)); print (da.cast4 (ba)); print (da.cast5<B> (ba)); print (db.cast6 (b)); print (db.cast7<A> (b)); print (dba.cast7<A[]> (ba)); print (db.cast8 (ba)); print (db.cast9<A> (ba)); print (c.cast2 (b)); print (c.cast3<B> (b)); print (c.cast3<B[]> (ba)); print (c.cast4 (ba)); print (c.cast5<B> (ba)); //Console.WriteLine("done"); //Console.WriteLine("success"); result = c1.F1 (c2, 100, (long)&stack, 0) + c1.GF1<object> (c2, 100, (long)&stack, 0) + c1.GF1<A> (c2, 100, (long)&stack, 0) + c1.GF1<A[]> (c2, 100, (long)&stack, 0) + c1.GF1<int> (c2, 100, (long)&stack, 0) + c1.GF1<int[]> (c2, 100, (long)&stack, 0) + c1o.F1 (c2o, 100, (long)&stack) + c1o.GF1<object> (c2o, 100, (long)&stack) + c1o.GF1<A> (c2o, 100, (long)&stack) + c1o.GF1<A[]> (c2o, 100, (long)&stack) + c1o.GF1<int> (c2o, 100, (long)&stack) + c1o.GF1<int[]> (c2o, 100, (long)&stack) + c1oa.GF1<object[]> (c2oa, 100, (long)&stack) + c1oa.GF1<A> (c2oa, 100, (long)&stack) + c1oa.GF1<A[]> (c2oa, 100, (long)&stack) + c1oa.GF1<int> (c2oa, 100, (long)&stack) + c1oa.GF1<int[]> (c2oa, 100, (long)&stack) + c1i.GF1<object> (c2i, 100, (long)&stack) + c1i.GF1<A> (c2i, 100, (long)&stack) + c1i.GF1<A[]> (c2i, 100, (long)&stack) + c1i.GF1<int> (c2i, 100, (long)&stack) + c1i.GF1<int[]> (c2i, 100, (long)&stack) + c1ia.GF1<object> (c2ia, 100, (long)&stack) + c1ia.GF1<A> (c2ia, 100, (long)&stack) + c1ia.GF1<A[]> (c2ia, 100, (long)&stack) + c1ia.GF1<int> (c2ia, 100, (long)&stack) + c1ia.GF1<int[]> (c2ia, 100, (long)&stack) + c1s.GF1<object> (c2s, 100, (long)&stack) + c1s.GF1<A> (c2s, 100, (long)&stack) + c1s.GF1<A[]> (c2s, 100, (long)&stack) + c1s.GF1<int> (c2s, 100, (long)&stack) + c1s.GF1<int[]> (c2s, 100, (long)&stack) + c1sa.GF1<object> (c2sa, 100, (long)&stack) + c1sa.GF1<A> (c2sa, 100, (long)&stack) + c1sa.GF1<A[]> (c2sa, 100, (long)&stack) + c1sa.GF1<int> (c2sa, 100, (long)&stack) + c1sa.GF1<int[]> (c2sa, 100, (long)&stack) + C1.errors; //Console.WriteLine (result == 0 ? "success" : "failure {0}", result); Environment.Exit (result); } [MethodImpl (NoInlining)] public static void Main(string[] args) { new C3 ().Main (); } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/SectionHeader.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.Reflection.PortableExecutable { public readonly struct SectionHeader { /// <summary> /// The name of the section. /// </summary> public string Name { get; } /// <summary> /// The total size of the section when loaded into memory. /// If this value is greater than <see cref="SizeOfRawData"/>, the section is zero-padded. /// This field is valid only for PE images and should be set to zero for object files. /// </summary> public int VirtualSize { get; } /// <summary> /// For PE images, the address of the first byte of the section relative to the image base when the /// section is loaded into memory. For object files, this field is the address of the first byte before /// relocation is applied; for simplicity, compilers should set this to zero. Otherwise, /// it is an arbitrary value that is subtracted from offsets during relocation. /// </summary> public int VirtualAddress { get; } /// <summary> /// The size of the section (for object files) or the size of the initialized data on disk (for image files). /// For PE images, this must be a multiple of <see cref="PEHeader.FileAlignment"/>. /// If this is less than <see cref="VirtualSize"/>, the remainder of the section is zero-filled. /// Because the <see cref="SizeOfRawData"/> field is rounded but the <see cref="VirtualSize"/> field is not, /// it is possible for <see cref="SizeOfRawData"/> to be greater than <see cref="VirtualSize"/> as well. /// When a section contains only uninitialized data, this field should be zero. /// </summary> public int SizeOfRawData { get; } /// <summary> /// The file pointer to the first page of the section within the COFF file. /// For PE images, this must be a multiple of <see cref="PEHeader.FileAlignment"/>. /// For object files, the value should be aligned on a 4 byte boundary for best performance. /// When a section contains only uninitialized data, this field should be zero. /// </summary> public int PointerToRawData { get; } /// <summary> /// The file pointer to the beginning of relocation entries for the section. /// This is set to zero for PE images or if there are no relocations. /// </summary> public int PointerToRelocations { get; } /// <summary> /// The file pointer to the beginning of line-number entries for the section. /// This is set to zero if there are no COFF line numbers. /// This value should be zero for an image because COFF debugging information is deprecated. /// </summary> public int PointerToLineNumbers { get; } /// <summary> /// The number of relocation entries for the section. This is set to zero for PE images. /// </summary> public ushort NumberOfRelocations { get; } /// <summary> /// The number of line-number entries for the section. /// This value should be zero for an image because COFF debugging information is deprecated. /// </summary> public ushort NumberOfLineNumbers { get; } /// <summary> /// The flags that describe the characteristics of the section. /// </summary> public SectionCharacteristics SectionCharacteristics { get; } internal const int NameSize = 8; internal const int Size = NameSize + sizeof(int) + // VirtualSize sizeof(int) + // VirtualAddress sizeof(int) + // SizeOfRawData sizeof(int) + // PointerToRawData sizeof(int) + // PointerToRelocations sizeof(int) + // PointerToLineNumbers sizeof(short) + // NumberOfRelocations sizeof(short) + // NumberOfLineNumbers sizeof(int); // SectionCharacteristics internal SectionHeader(ref PEBinaryReader reader) { Name = reader.ReadNullPaddedUTF8(NameSize); VirtualSize = reader.ReadInt32(); VirtualAddress = reader.ReadInt32(); SizeOfRawData = reader.ReadInt32(); PointerToRawData = reader.ReadInt32(); PointerToRelocations = reader.ReadInt32(); PointerToLineNumbers = reader.ReadInt32(); NumberOfRelocations = reader.ReadUInt16(); NumberOfLineNumbers = reader.ReadUInt16(); SectionCharacteristics = (SectionCharacteristics)reader.ReadUInt32(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Reflection.PortableExecutable { public readonly struct SectionHeader { /// <summary> /// The name of the section. /// </summary> public string Name { get; } /// <summary> /// The total size of the section when loaded into memory. /// If this value is greater than <see cref="SizeOfRawData"/>, the section is zero-padded. /// This field is valid only for PE images and should be set to zero for object files. /// </summary> public int VirtualSize { get; } /// <summary> /// For PE images, the address of the first byte of the section relative to the image base when the /// section is loaded into memory. For object files, this field is the address of the first byte before /// relocation is applied; for simplicity, compilers should set this to zero. Otherwise, /// it is an arbitrary value that is subtracted from offsets during relocation. /// </summary> public int VirtualAddress { get; } /// <summary> /// The size of the section (for object files) or the size of the initialized data on disk (for image files). /// For PE images, this must be a multiple of <see cref="PEHeader.FileAlignment"/>. /// If this is less than <see cref="VirtualSize"/>, the remainder of the section is zero-filled. /// Because the <see cref="SizeOfRawData"/> field is rounded but the <see cref="VirtualSize"/> field is not, /// it is possible for <see cref="SizeOfRawData"/> to be greater than <see cref="VirtualSize"/> as well. /// When a section contains only uninitialized data, this field should be zero. /// </summary> public int SizeOfRawData { get; } /// <summary> /// The file pointer to the first page of the section within the COFF file. /// For PE images, this must be a multiple of <see cref="PEHeader.FileAlignment"/>. /// For object files, the value should be aligned on a 4 byte boundary for best performance. /// When a section contains only uninitialized data, this field should be zero. /// </summary> public int PointerToRawData { get; } /// <summary> /// The file pointer to the beginning of relocation entries for the section. /// This is set to zero for PE images or if there are no relocations. /// </summary> public int PointerToRelocations { get; } /// <summary> /// The file pointer to the beginning of line-number entries for the section. /// This is set to zero if there are no COFF line numbers. /// This value should be zero for an image because COFF debugging information is deprecated. /// </summary> public int PointerToLineNumbers { get; } /// <summary> /// The number of relocation entries for the section. This is set to zero for PE images. /// </summary> public ushort NumberOfRelocations { get; } /// <summary> /// The number of line-number entries for the section. /// This value should be zero for an image because COFF debugging information is deprecated. /// </summary> public ushort NumberOfLineNumbers { get; } /// <summary> /// The flags that describe the characteristics of the section. /// </summary> public SectionCharacteristics SectionCharacteristics { get; } internal const int NameSize = 8; internal const int Size = NameSize + sizeof(int) + // VirtualSize sizeof(int) + // VirtualAddress sizeof(int) + // SizeOfRawData sizeof(int) + // PointerToRawData sizeof(int) + // PointerToRelocations sizeof(int) + // PointerToLineNumbers sizeof(short) + // NumberOfRelocations sizeof(short) + // NumberOfLineNumbers sizeof(int); // SectionCharacteristics internal SectionHeader(ref PEBinaryReader reader) { Name = reader.ReadNullPaddedUTF8(NameSize); VirtualSize = reader.ReadInt32(); VirtualAddress = reader.ReadInt32(); SizeOfRawData = reader.ReadInt32(); PointerToRawData = reader.ReadInt32(); PointerToRelocations = reader.ReadInt32(); PointerToLineNumbers = reader.ReadInt32(); NumberOfRelocations = reader.ReadUInt16(); NumberOfLineNumbers = reader.ReadUInt16(); SectionCharacteristics = (SectionCharacteristics)reader.ReadUInt32(); } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/RoundToNearest.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 RoundToNearest_Vector128_Single() { var test = new SimpleUnaryOpTest__RoundToNearest_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__RoundToNearest_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__RoundToNearest_Vector128_Single testClass) { var result = AdvSimd.RoundToNearest(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToNearest_Vector128_Single testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) { var result = AdvSimd.RoundToNearest( 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<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__RoundToNearest_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__RoundToNearest_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.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.RoundToNearest( 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.RoundToNearest( 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).GetMethod(nameof(AdvSimd.RoundToNearest), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.RoundToNearest), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.RoundToNearest( _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.RoundToNearest( 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.RoundToNearest(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.RoundToNearest(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__RoundToNearest_Vector128_Single(); var result = AdvSimd.RoundToNearest(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__RoundToNearest_Vector128_Single(); fixed (Vector128<Single>* pFld1 = &test._fld1) { var result = AdvSimd.RoundToNearest( 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.RoundToNearest(_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.RoundToNearest( 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.RoundToNearest(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.RoundToNearest( 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<Vector128<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<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(Helpers.RoundToNearest(firstOp[i])) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.RoundToNearest)}<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 RoundToNearest_Vector128_Single() { var test = new SimpleUnaryOpTest__RoundToNearest_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__RoundToNearest_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__RoundToNearest_Vector128_Single testClass) { var result = AdvSimd.RoundToNearest(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToNearest_Vector128_Single testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) { var result = AdvSimd.RoundToNearest( 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<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__RoundToNearest_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__RoundToNearest_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.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.RoundToNearest( 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.RoundToNearest( 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).GetMethod(nameof(AdvSimd.RoundToNearest), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.RoundToNearest), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.RoundToNearest( _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.RoundToNearest( 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.RoundToNearest(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.RoundToNearest(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__RoundToNearest_Vector128_Single(); var result = AdvSimd.RoundToNearest(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__RoundToNearest_Vector128_Single(); fixed (Vector128<Single>* pFld1 = &test._fld1) { var result = AdvSimd.RoundToNearest( 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.RoundToNearest(_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.RoundToNearest( 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.RoundToNearest(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.RoundToNearest( 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<Vector128<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<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(Helpers.RoundToNearest(firstOp[i])) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.RoundToNearest)}<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,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/tests/JIT/HardwareIntrinsics/General/Vector64_1/ToVector128.UInt64.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 ToVector128UInt64() { var test = new VectorExtend__ToVector128UInt64(); // Validates basic functionality works test.RunBasicScenario(); // 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 VectorExtend__ToVector128UInt64 { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<UInt64>>() / sizeof(UInt64); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); UInt64[] values = new UInt64[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt64(); } Vector64<UInt64> value = Vector64.Create(values[0]); Vector128<UInt64> result = value.ToVector128(); ValidateResult(result, values, isUnsafe: false); Vector128<UInt64> unsafeResult = value.ToVector128Unsafe(); ValidateResult(unsafeResult, values, isUnsafe: true); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); UInt64[] values = new UInt64[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt64(); } Vector64<UInt64> value = Vector64.Create(values[0]); object result = typeof(Vector64) .GetMethod(nameof(Vector64.ToVector128)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<UInt64>)(result), values, isUnsafe: false); object unsafeResult = typeof(Vector64) .GetMethod(nameof(Vector64.ToVector128)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<UInt64>)(unsafeResult), values, isUnsafe: true); } private void ValidateResult(Vector128<UInt64> result, UInt64[] values, bool isUnsafe, [CallerMemberName] string method = "") { UInt64[] resultElements = new UInt64[ElementCount * 2]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref resultElements[0]), result); ValidateResult(resultElements, values, isUnsafe, method); } private void ValidateResult(UInt64[] result, UInt64[] values, bool isUnsafe, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if (result[i] != values[i]) { succeeded = false; break; } } if (!isUnsafe) { for (int i = ElementCount; i < ElementCount * 2; i++) { if (result[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<UInt64>.ToVector128{(isUnsafe ? "Unsafe" : "")}(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); 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\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 ToVector128UInt64() { var test = new VectorExtend__ToVector128UInt64(); // Validates basic functionality works test.RunBasicScenario(); // 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 VectorExtend__ToVector128UInt64 { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<UInt64>>() / sizeof(UInt64); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); UInt64[] values = new UInt64[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt64(); } Vector64<UInt64> value = Vector64.Create(values[0]); Vector128<UInt64> result = value.ToVector128(); ValidateResult(result, values, isUnsafe: false); Vector128<UInt64> unsafeResult = value.ToVector128Unsafe(); ValidateResult(unsafeResult, values, isUnsafe: true); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); UInt64[] values = new UInt64[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt64(); } Vector64<UInt64> value = Vector64.Create(values[0]); object result = typeof(Vector64) .GetMethod(nameof(Vector64.ToVector128)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<UInt64>)(result), values, isUnsafe: false); object unsafeResult = typeof(Vector64) .GetMethod(nameof(Vector64.ToVector128)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<UInt64>)(unsafeResult), values, isUnsafe: true); } private void ValidateResult(Vector128<UInt64> result, UInt64[] values, bool isUnsafe, [CallerMemberName] string method = "") { UInt64[] resultElements = new UInt64[ElementCount * 2]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref resultElements[0]), result); ValidateResult(resultElements, values, isUnsafe, method); } private void ValidateResult(UInt64[] result, UInt64[] values, bool isUnsafe, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if (result[i] != values[i]) { succeeded = false; break; } } if (!isUnsafe) { for (int i = ElementCount; i < ElementCount * 2; i++) { if (result[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<UInt64>.ToVector128{(isUnsafe ? "Unsafe" : "")}(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/mono/mono/tests/virtual-method.cs
using System; namespace Obj { interface Bah { int H (); } class A : Bah { public int F () {return 1;} public virtual int G () {return 2;} public int H () {return 10;} } class B : A { public new int F () {return 3;} public override int G () {return 4;} public new int H () {return 11;} } class Test { static public int Main () { int result = 0; B b = new B (); A a = b; if (a.F () != 1) result |= 1 << 0; if (b.F () != 3) result |= 1 << 1; if (b.G () != 4) result |= 1 << 2; if (a.G () != 4) result |= 1 << 3; if (a.H () != 10) result |= 1 << 4; if (b.H () != 11) result |= 1 << 5; if (((A)b).H () != 10) result |= 1 << 6; if (((B)a).H () != 11) result |= 1 << 7; return result; } }; };
using System; namespace Obj { interface Bah { int H (); } class A : Bah { public int F () {return 1;} public virtual int G () {return 2;} public int H () {return 10;} } class B : A { public new int F () {return 3;} public override int G () {return 4;} public new int H () {return 11;} } class Test { static public int Main () { int result = 0; B b = new B (); A a = b; if (a.F () != 1) result |= 1 << 0; if (b.F () != 3) result |= 1 << 1; if (b.G () != 4) result |= 1 << 2; if (a.G () != 4) result |= 1 << 3; if (a.H () != 10) result |= 1 << 4; if (b.H () != 11) result |= 1 << 5; if (((A)b).H () != 10) result |= 1 << 6; if (((B)a).H () != 11) result |= 1 << 7; return result; } }; };
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/tests/JIT/Methodical/NaN/arithm64.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // namespace JitTest { using System; class Test { static void RunTests(double nan, double plusinf, double minusinf) { if (!Double.IsNaN(nan + nan)) throw new Exception("! Double.IsNaN(nan + nan)"); if (!Double.IsNaN(nan + plusinf)) throw new Exception("! Double.IsNaN(nan + plusinf)"); if (!Double.IsNaN(nan + minusinf)) throw new Exception("! Double.IsNaN(nan + minusinf)"); if (!Double.IsNaN(plusinf + nan)) throw new Exception("! Double.IsNaN(plusinf + nan)"); if (!Double.IsPositiveInfinity(plusinf + plusinf)) throw new Exception("! Double.IsPositiveInfinity(plusinf + plusinf)"); if (!Double.IsNaN(plusinf + minusinf)) throw new Exception("! Double.IsNaN(plusinf + minusinf)"); if (!Double.IsNaN(minusinf + nan)) throw new Exception("! Double.IsNaN(minusinf + nan)"); if (!Double.IsNaN(minusinf + plusinf)) throw new Exception("! Double.IsNaN(minusinf + plusinf)"); if (!Double.IsNegativeInfinity(minusinf + minusinf)) throw new Exception("! Double.IsNegativeInfinity(minusinf + minusinf)"); if (!Double.IsNaN(nan + nan)) throw new Exception("! Double.IsNaN(nan + nan)"); if (!Double.IsNaN(nan + plusinf)) throw new Exception("! Double.IsNaN(nan + plusinf)"); if (!Double.IsNaN(nan + minusinf)) throw new Exception("! Double.IsNaN(nan + minusinf)"); if (!Double.IsNaN(plusinf + nan)) throw new Exception("! Double.IsNaN(plusinf + nan)"); if (!Double.IsPositiveInfinity(plusinf + plusinf)) throw new Exception("! Double.IsPositiveInfinity(plusinf + plusinf)"); if (!Double.IsNaN(plusinf + minusinf)) throw new Exception("! Double.IsNaN(plusinf + minusinf)"); if (!Double.IsNaN(minusinf + nan)) throw new Exception("! Double.IsNaN(minusinf + nan)"); if (!Double.IsNaN(minusinf + plusinf)) throw new Exception("! Double.IsNaN(minusinf + plusinf)"); if (!Double.IsNegativeInfinity(minusinf + minusinf)) throw new Exception("! Double.IsNegativeInfinity(minusinf + minusinf)"); if (!Double.IsNaN(nan + nan)) throw new Exception("! Double.IsNaN(nan + nan)"); if (!Double.IsNaN(nan + plusinf)) throw new Exception("! Double.IsNaN(nan + plusinf)"); if (!Double.IsNaN(nan + minusinf)) throw new Exception("! Double.IsNaN(nan + minusinf)"); if (!Double.IsNaN(plusinf + nan)) throw new Exception("! Double.IsNaN(plusinf + nan)"); if (!Double.IsPositiveInfinity(plusinf + plusinf)) throw new Exception("! Double.IsPositiveInfinity(plusinf + plusinf)"); if (!Double.IsNaN(plusinf + minusinf)) throw new Exception("! Double.IsNaN(plusinf + minusinf)"); if (!Double.IsNaN(minusinf + nan)) throw new Exception("! Double.IsNaN(minusinf + nan)"); if (!Double.IsNaN(minusinf + plusinf)) throw new Exception("! Double.IsNaN(minusinf + plusinf)"); if (!Double.IsNegativeInfinity(minusinf + minusinf)) throw new Exception("! Double.IsNegativeInfinity(minusinf + minusinf)"); if (!Double.IsNaN(nan + nan)) throw new Exception("! Double.IsNaN(nan + nan)"); if (!Double.IsNaN(nan + plusinf)) throw new Exception("! Double.IsNaN(nan + plusinf)"); if (!Double.IsNaN(nan + minusinf)) throw new Exception("! Double.IsNaN(nan + minusinf)"); if (!Double.IsNaN(plusinf + nan)) throw new Exception("! Double.IsNaN(plusinf + nan)"); if (!Double.IsPositiveInfinity(plusinf + plusinf)) throw new Exception("! Double.IsPositiveInfinity(plusinf + plusinf)"); if (!Double.IsNaN(plusinf + minusinf)) throw new Exception("! Double.IsNaN(plusinf + minusinf)"); if (!Double.IsNaN(minusinf + nan)) throw new Exception("! Double.IsNaN(minusinf + nan)"); if (!Double.IsNaN(minusinf + plusinf)) throw new Exception("! Double.IsNaN(minusinf + plusinf)"); if (!Double.IsNegativeInfinity(minusinf + minusinf)) throw new Exception("! Double.IsNegativeInfinity(minusinf + minusinf)"); } static int Main() { RunTests(Double.NaN, Double.PositiveInfinity, Double.NegativeInfinity); Console.WriteLine("=== PASSED ==="); return 100; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // namespace JitTest { using System; class Test { static void RunTests(double nan, double plusinf, double minusinf) { if (!Double.IsNaN(nan + nan)) throw new Exception("! Double.IsNaN(nan + nan)"); if (!Double.IsNaN(nan + plusinf)) throw new Exception("! Double.IsNaN(nan + plusinf)"); if (!Double.IsNaN(nan + minusinf)) throw new Exception("! Double.IsNaN(nan + minusinf)"); if (!Double.IsNaN(plusinf + nan)) throw new Exception("! Double.IsNaN(plusinf + nan)"); if (!Double.IsPositiveInfinity(plusinf + plusinf)) throw new Exception("! Double.IsPositiveInfinity(plusinf + plusinf)"); if (!Double.IsNaN(plusinf + minusinf)) throw new Exception("! Double.IsNaN(plusinf + minusinf)"); if (!Double.IsNaN(minusinf + nan)) throw new Exception("! Double.IsNaN(minusinf + nan)"); if (!Double.IsNaN(minusinf + plusinf)) throw new Exception("! Double.IsNaN(minusinf + plusinf)"); if (!Double.IsNegativeInfinity(minusinf + minusinf)) throw new Exception("! Double.IsNegativeInfinity(minusinf + minusinf)"); if (!Double.IsNaN(nan + nan)) throw new Exception("! Double.IsNaN(nan + nan)"); if (!Double.IsNaN(nan + plusinf)) throw new Exception("! Double.IsNaN(nan + plusinf)"); if (!Double.IsNaN(nan + minusinf)) throw new Exception("! Double.IsNaN(nan + minusinf)"); if (!Double.IsNaN(plusinf + nan)) throw new Exception("! Double.IsNaN(plusinf + nan)"); if (!Double.IsPositiveInfinity(plusinf + plusinf)) throw new Exception("! Double.IsPositiveInfinity(plusinf + plusinf)"); if (!Double.IsNaN(plusinf + minusinf)) throw new Exception("! Double.IsNaN(plusinf + minusinf)"); if (!Double.IsNaN(minusinf + nan)) throw new Exception("! Double.IsNaN(minusinf + nan)"); if (!Double.IsNaN(minusinf + plusinf)) throw new Exception("! Double.IsNaN(minusinf + plusinf)"); if (!Double.IsNegativeInfinity(minusinf + minusinf)) throw new Exception("! Double.IsNegativeInfinity(minusinf + minusinf)"); if (!Double.IsNaN(nan + nan)) throw new Exception("! Double.IsNaN(nan + nan)"); if (!Double.IsNaN(nan + plusinf)) throw new Exception("! Double.IsNaN(nan + plusinf)"); if (!Double.IsNaN(nan + minusinf)) throw new Exception("! Double.IsNaN(nan + minusinf)"); if (!Double.IsNaN(plusinf + nan)) throw new Exception("! Double.IsNaN(plusinf + nan)"); if (!Double.IsPositiveInfinity(plusinf + plusinf)) throw new Exception("! Double.IsPositiveInfinity(plusinf + plusinf)"); if (!Double.IsNaN(plusinf + minusinf)) throw new Exception("! Double.IsNaN(plusinf + minusinf)"); if (!Double.IsNaN(minusinf + nan)) throw new Exception("! Double.IsNaN(minusinf + nan)"); if (!Double.IsNaN(minusinf + plusinf)) throw new Exception("! Double.IsNaN(minusinf + plusinf)"); if (!Double.IsNegativeInfinity(minusinf + minusinf)) throw new Exception("! Double.IsNegativeInfinity(minusinf + minusinf)"); if (!Double.IsNaN(nan + nan)) throw new Exception("! Double.IsNaN(nan + nan)"); if (!Double.IsNaN(nan + plusinf)) throw new Exception("! Double.IsNaN(nan + plusinf)"); if (!Double.IsNaN(nan + minusinf)) throw new Exception("! Double.IsNaN(nan + minusinf)"); if (!Double.IsNaN(plusinf + nan)) throw new Exception("! Double.IsNaN(plusinf + nan)"); if (!Double.IsPositiveInfinity(plusinf + plusinf)) throw new Exception("! Double.IsPositiveInfinity(plusinf + plusinf)"); if (!Double.IsNaN(plusinf + minusinf)) throw new Exception("! Double.IsNaN(plusinf + minusinf)"); if (!Double.IsNaN(minusinf + nan)) throw new Exception("! Double.IsNaN(minusinf + nan)"); if (!Double.IsNaN(minusinf + plusinf)) throw new Exception("! Double.IsNaN(minusinf + plusinf)"); if (!Double.IsNegativeInfinity(minusinf + minusinf)) throw new Exception("! Double.IsNegativeInfinity(minusinf + minusinf)"); } static int Main() { RunTests(Double.NaN, Double.PositiveInfinity, Double.NegativeInfinity); Console.WriteLine("=== PASSED ==="); return 100; } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetEventSource.NetworkInformation.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.Tracing; namespace System.Net { [EventSource(Name = "Private.InternalDiagnostics.System.Net.NetworkInformation")] internal sealed partial class NetEventSource { } }
// 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.Tracing; namespace System.Net { [EventSource(Name = "Private.InternalDiagnostics.System.Net.NetworkInformation")] internal sealed partial class NetEventSource { } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Private.CoreLib/src/System/Reflection/ConstructorInfo.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; using System.Runtime.CompilerServices; namespace System.Reflection { public abstract partial class ConstructorInfo : MethodBase { protected ConstructorInfo() { } public override MemberTypes MemberType => MemberTypes.Constructor; [DebuggerHidden] [DebuggerStepThrough] public object Invoke(object?[]? parameters) => Invoke(BindingFlags.Default, binder: null, parameters: parameters, culture: null); public abstract object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture); public override bool Equals(object? obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(ConstructorInfo? left, ConstructorInfo? right) { // Test "right" first to allow branch elimination when inlined for null checks (== null) // so it can become a simple test if (right is null) { // return true/false not the test result https://github.com/dotnet/runtime/issues/4207 return (left is null) ? true : false; } // Try fast reference equality and opposite null check prior to calling the slower virtual Equals if ((object?)left == (object)right) { return true; } return (left is null) ? false : left.Equals(right); } public static bool operator !=(ConstructorInfo? left, ConstructorInfo? right) => !(left == right); public static readonly string ConstructorName = ".ctor"; public static readonly string TypeConstructorName = ".cctor"; } }
// 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; using System.Runtime.CompilerServices; namespace System.Reflection { public abstract partial class ConstructorInfo : MethodBase { protected ConstructorInfo() { } public override MemberTypes MemberType => MemberTypes.Constructor; [DebuggerHidden] [DebuggerStepThrough] public object Invoke(object?[]? parameters) => Invoke(BindingFlags.Default, binder: null, parameters: parameters, culture: null); public abstract object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture); public override bool Equals(object? obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(ConstructorInfo? left, ConstructorInfo? right) { // Test "right" first to allow branch elimination when inlined for null checks (== null) // so it can become a simple test if (right is null) { // return true/false not the test result https://github.com/dotnet/runtime/issues/4207 return (left is null) ? true : false; } // Try fast reference equality and opposite null check prior to calling the slower virtual Equals if ((object?)left == (object)right) { return true; } return (left is null) ? false : left.Equals(right); } public static bool operator !=(ConstructorInfo? left, ConstructorInfo? right) => !(left == right); public static readonly string ConstructorName = ".ctor"; public static readonly string TypeConstructorName = ".cctor"; } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.OpenSsl.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.IO; using Microsoft.Win32.SafeHandles; namespace System.Security.Cryptography.X509Certificates { internal sealed partial class StorePal { internal static partial IStorePal FromHandle(IntPtr storeHandle) { throw new PlatformNotSupportedException(); } internal static partial ILoaderPal FromBlob(ReadOnlySpan<byte> rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { Debug.Assert(password != null); ICertificatePal? singleCert; bool ephemeralSpecified = keyStorageFlags.HasFlag(X509KeyStorageFlags.EphemeralKeySet); if (OpenSslX509CertificateReader.TryReadX509Der(rawData, out singleCert) || OpenSslX509CertificateReader.TryReadX509Pem(rawData, out singleCert)) { // The single X509 structure methods shouldn't return true and out null, only empty // collections have that behavior. Debug.Assert(singleCert != null); return SingleCertToLoaderPal(singleCert); } List<ICertificatePal>? certPals; Exception? openSslException; if (OpenSslPkcsFormatReader.TryReadPkcs7Der(rawData, out certPals) || OpenSslPkcsFormatReader.TryReadPkcs7Pem(rawData, out certPals) || OpenSslPkcsFormatReader.TryReadPkcs12(rawData, password, ephemeralSpecified, out certPals, out openSslException)) { Debug.Assert(certPals != null); return ListToLoaderPal(certPals); } Debug.Assert(openSslException != null); throw openSslException; } internal static partial ILoaderPal FromFile(string fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { bool ephemeralSpecified = keyStorageFlags.HasFlag(X509KeyStorageFlags.EphemeralKeySet); using (SafeBioHandle bio = Interop.Crypto.BioNewFile(fileName, "rb")) { Interop.Crypto.CheckValidOpenSslHandle(bio); return FromBio(fileName, bio, password, ephemeralSpecified); } } private static ILoaderPal FromBio( string fileName, SafeBioHandle bio, SafePasswordHandle password, bool ephemeralSpecified) { int bioPosition = Interop.Crypto.BioTell(bio); Debug.Assert(bioPosition >= 0); ICertificatePal? singleCert; if (OpenSslX509CertificateReader.TryReadX509Pem(bio, out singleCert)) { return SingleCertToLoaderPal(singleCert); } // Rewind, try again. OpenSslX509CertificateReader.RewindBio(bio, bioPosition); if (OpenSslX509CertificateReader.TryReadX509Der(bio, out singleCert)) { return SingleCertToLoaderPal(singleCert); } // Rewind, try again. OpenSslX509CertificateReader.RewindBio(bio, bioPosition); List<ICertificatePal>? certPals; if (OpenSslPkcsFormatReader.TryReadPkcs7Pem(bio, out certPals)) { return ListToLoaderPal(certPals); } // Rewind, try again. OpenSslX509CertificateReader.RewindBio(bio, bioPosition); if (OpenSslPkcsFormatReader.TryReadPkcs7Der(bio, out certPals)) { return ListToLoaderPal(certPals); } // Rewind, try again. OpenSslX509CertificateReader.RewindBio(bio, bioPosition); // Capture the exception so in case of failure, the call to BioSeek does not override it. Exception? openSslException; byte[] data = File.ReadAllBytes(fileName); if (OpenSslPkcsFormatReader.TryReadPkcs12(data, password, ephemeralSpecified, out certPals, out openSslException)) { return ListToLoaderPal(certPals); } // Since we aren't going to finish reading, leaving the buffer where it was when we got // it seems better than leaving it in some arbitrary other position. // // Use BioSeek directly for the last seek attempt, because any failure here should instead // report the already created (but not yet thrown) exception. if (Interop.Crypto.BioSeek(bio, bioPosition) < 0) { Interop.Crypto.ErrClearError(); } Debug.Assert(openSslException != null); throw openSslException; } internal static partial IExportPal FromCertificate(ICertificatePalCore cert) { return new OpenSslExportProvider(cert); } internal static partial IExportPal LinkFromCertificateCollection(X509Certificate2Collection certificates) { return new OpenSslExportProvider(certificates); } internal static partial IStorePal FromSystemStore(string storeName, StoreLocation storeLocation, OpenFlags openFlags) { if (storeLocation == StoreLocation.CurrentUser) { if (X509Store.DisallowedStoreName.Equals(storeName, StringComparison.OrdinalIgnoreCase)) { return OpenSslDirectoryBasedStoreProvider.OpenDisallowedStore(openFlags); } return new OpenSslDirectoryBasedStoreProvider(storeName, openFlags); } Debug.Assert(storeLocation == StoreLocation.LocalMachine); if ((openFlags & OpenFlags.ReadWrite) == OpenFlags.ReadWrite) { throw new CryptographicException( SR.Cryptography_Unix_X509_MachineStoresReadOnly, new PlatformNotSupportedException(SR.Cryptography_Unix_X509_MachineStoresReadOnly)); } // The static store approach here is making an optimization based on not // having write support. Once writing is permitted the stores would need // to fresh-read whenever being requested. if (X509Store.RootStoreName.Equals(storeName, StringComparison.OrdinalIgnoreCase)) { return OpenSslCachedSystemStoreProvider.MachineRoot; } if (X509Store.IntermediateCAStoreName.Equals(storeName, StringComparison.OrdinalIgnoreCase)) { return OpenSslCachedSystemStoreProvider.MachineIntermediate; } throw new CryptographicException( SR.Cryptography_Unix_X509_MachineStoresRootOnly, new PlatformNotSupportedException(SR.Cryptography_Unix_X509_MachineStoresRootOnly)); } private static ILoaderPal SingleCertToLoaderPal(ICertificatePal singleCert) { return new OpenSslSingleCertLoader(singleCert); } private static ILoaderPal ListToLoaderPal(List<ICertificatePal> certPals) { return new CertCollectionLoader(certPals); } } }
// 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.IO; using Microsoft.Win32.SafeHandles; namespace System.Security.Cryptography.X509Certificates { internal sealed partial class StorePal { internal static partial IStorePal FromHandle(IntPtr storeHandle) { throw new PlatformNotSupportedException(); } internal static partial ILoaderPal FromBlob(ReadOnlySpan<byte> rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { Debug.Assert(password != null); ICertificatePal? singleCert; bool ephemeralSpecified = keyStorageFlags.HasFlag(X509KeyStorageFlags.EphemeralKeySet); if (OpenSslX509CertificateReader.TryReadX509Der(rawData, out singleCert) || OpenSslX509CertificateReader.TryReadX509Pem(rawData, out singleCert)) { // The single X509 structure methods shouldn't return true and out null, only empty // collections have that behavior. Debug.Assert(singleCert != null); return SingleCertToLoaderPal(singleCert); } List<ICertificatePal>? certPals; Exception? openSslException; if (OpenSslPkcsFormatReader.TryReadPkcs7Der(rawData, out certPals) || OpenSslPkcsFormatReader.TryReadPkcs7Pem(rawData, out certPals) || OpenSslPkcsFormatReader.TryReadPkcs12(rawData, password, ephemeralSpecified, out certPals, out openSslException)) { Debug.Assert(certPals != null); return ListToLoaderPal(certPals); } Debug.Assert(openSslException != null); throw openSslException; } internal static partial ILoaderPal FromFile(string fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { bool ephemeralSpecified = keyStorageFlags.HasFlag(X509KeyStorageFlags.EphemeralKeySet); using (SafeBioHandle bio = Interop.Crypto.BioNewFile(fileName, "rb")) { Interop.Crypto.CheckValidOpenSslHandle(bio); return FromBio(fileName, bio, password, ephemeralSpecified); } } private static ILoaderPal FromBio( string fileName, SafeBioHandle bio, SafePasswordHandle password, bool ephemeralSpecified) { int bioPosition = Interop.Crypto.BioTell(bio); Debug.Assert(bioPosition >= 0); ICertificatePal? singleCert; if (OpenSslX509CertificateReader.TryReadX509Pem(bio, out singleCert)) { return SingleCertToLoaderPal(singleCert); } // Rewind, try again. OpenSslX509CertificateReader.RewindBio(bio, bioPosition); if (OpenSslX509CertificateReader.TryReadX509Der(bio, out singleCert)) { return SingleCertToLoaderPal(singleCert); } // Rewind, try again. OpenSslX509CertificateReader.RewindBio(bio, bioPosition); List<ICertificatePal>? certPals; if (OpenSslPkcsFormatReader.TryReadPkcs7Pem(bio, out certPals)) { return ListToLoaderPal(certPals); } // Rewind, try again. OpenSslX509CertificateReader.RewindBio(bio, bioPosition); if (OpenSslPkcsFormatReader.TryReadPkcs7Der(bio, out certPals)) { return ListToLoaderPal(certPals); } // Rewind, try again. OpenSslX509CertificateReader.RewindBio(bio, bioPosition); // Capture the exception so in case of failure, the call to BioSeek does not override it. Exception? openSslException; byte[] data = File.ReadAllBytes(fileName); if (OpenSslPkcsFormatReader.TryReadPkcs12(data, password, ephemeralSpecified, out certPals, out openSslException)) { return ListToLoaderPal(certPals); } // Since we aren't going to finish reading, leaving the buffer where it was when we got // it seems better than leaving it in some arbitrary other position. // // Use BioSeek directly for the last seek attempt, because any failure here should instead // report the already created (but not yet thrown) exception. if (Interop.Crypto.BioSeek(bio, bioPosition) < 0) { Interop.Crypto.ErrClearError(); } Debug.Assert(openSslException != null); throw openSslException; } internal static partial IExportPal FromCertificate(ICertificatePalCore cert) { return new OpenSslExportProvider(cert); } internal static partial IExportPal LinkFromCertificateCollection(X509Certificate2Collection certificates) { return new OpenSslExportProvider(certificates); } internal static partial IStorePal FromSystemStore(string storeName, StoreLocation storeLocation, OpenFlags openFlags) { if (storeLocation == StoreLocation.CurrentUser) { if (X509Store.DisallowedStoreName.Equals(storeName, StringComparison.OrdinalIgnoreCase)) { return OpenSslDirectoryBasedStoreProvider.OpenDisallowedStore(openFlags); } return new OpenSslDirectoryBasedStoreProvider(storeName, openFlags); } Debug.Assert(storeLocation == StoreLocation.LocalMachine); if ((openFlags & OpenFlags.ReadWrite) == OpenFlags.ReadWrite) { throw new CryptographicException( SR.Cryptography_Unix_X509_MachineStoresReadOnly, new PlatformNotSupportedException(SR.Cryptography_Unix_X509_MachineStoresReadOnly)); } // The static store approach here is making an optimization based on not // having write support. Once writing is permitted the stores would need // to fresh-read whenever being requested. if (X509Store.RootStoreName.Equals(storeName, StringComparison.OrdinalIgnoreCase)) { return OpenSslCachedSystemStoreProvider.MachineRoot; } if (X509Store.IntermediateCAStoreName.Equals(storeName, StringComparison.OrdinalIgnoreCase)) { return OpenSslCachedSystemStoreProvider.MachineIntermediate; } throw new CryptographicException( SR.Cryptography_Unix_X509_MachineStoresRootOnly, new PlatformNotSupportedException(SR.Cryptography_Unix_X509_MachineStoresRootOnly)); } private static ILoaderPal SingleCertToLoaderPal(ICertificatePal singleCert) { return new OpenSslSingleCertLoader(singleCert); } private static ILoaderPal ListToLoaderPal(List<ICertificatePal> certPals) { return new CertCollectionLoader(certPals); } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Linq.Expressions/tests/Unary/UnaryConvertTests.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.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public static class UnaryConvertTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertBoxingTest(bool useInterpreter) { foreach (var e in ConvertBoxing()) { VerifyUnaryConvert(e, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertUnboxingTest(bool useInterpreter) { foreach (var e in ConvertUnboxing()) { VerifyUnaryConvert(e, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertDelegatesTest(bool useInterpreter) { foreach (var e in ConvertDelegates()) { VerifyUnaryConvert(e, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertUnboxingInvalidCastTest(bool useInterpreter) { foreach (var e in ConvertUnboxingInvalidCast()) { VerifyUnaryConvertThrows<InvalidCastException>(e, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryConvertBooleanToNumericTest(bool useInterpreter) { foreach (var kv in ConvertBooleanToNumeric()) { VerifyUnaryConvert(kv.Key, kv.Value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertNullToNonNullableValueTest(bool useInterpreter) { foreach (var e in ConvertNullToNonNullableValue()) { VerifyUnaryConvertThrows<NullReferenceException>(e, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertNullToNullableValueTest(bool useInterpreter) { foreach (var e in ConvertNullToNullableValue()) { VerifyUnaryConvert(e, null, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertUnderlyingTypeToEnumTypeTest(bool useInterpreter) { DayOfWeek enumValue = DayOfWeek.Monday; var value = (int)enumValue; foreach (var o in new[] { Expression.Constant(value, typeof(int)), Expression.Constant(value, typeof(ValueType)), Expression.Constant(value, typeof(object)) }) { VerifyUnaryConvert(Expression.Convert(o, typeof(DayOfWeek)), enumValue, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertUnderlyingTypeToNullableEnumTypeTest(bool useInterpreter) { DayOfWeek enumValue = DayOfWeek.Monday; var value = (int)enumValue; ConstantExpression cInt = Expression.Constant(value, typeof(int)); VerifyUnaryConvert(Expression.Convert(cInt, typeof(DayOfWeek?)), enumValue, useInterpreter); ConstantExpression cObj = Expression.Constant(value, typeof(object)); VerifyUnaryConvertThrows<InvalidCastException>(Expression.Convert(cObj, typeof(DayOfWeek?)), useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertArrayToIncompatibleTypeTest(bool useInterpreter) { var arr = new object[] { "bar" }; foreach (var t in new[] { typeof(string[]), typeof(IEnumerable<char>[]) }) { VerifyUnaryConvertThrows<InvalidCastException>(Expression.Convert(Expression.Constant(arr), t), useInterpreter); } } [Fact] public static void ToStringTest() { // NB: Unlike TypeAs, the output does not include the type we're converting to UnaryExpression e1 = Expression.Convert(Expression.Parameter(typeof(object), "o"), typeof(int)); Assert.Equal("Convert(o, Int32)", e1.ToString()); UnaryExpression e2 = Expression.ConvertChecked(Expression.Parameter(typeof(long), "x"), typeof(int)); Assert.Equal("ConvertChecked(x, Int32)", e2.ToString()); } private static IEnumerable<KeyValuePair<Expression, object>> ConvertBooleanToNumeric() { ConstantExpression boolF = Expression.Constant(false); ConstantExpression boolT = Expression.Constant(true); var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { foreach (var b in new[] { false, true }) { yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(byte)), (byte)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(sbyte)), (sbyte)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(ushort)), (ushort)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(short)), (short)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(uint)), (uint)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(int)), (int)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(ulong)), (ulong)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(long)), (long)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(float)), (float)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(double)), (double)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(char)), (char)(b ? 1 : 0)); } } } private static IEnumerable<Expression> ConvertNullToNonNullableValue() { ConstantExpression nullC = Expression.Constant(null); var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { foreach (var b in new[] { false, true }) { yield return factory(nullC, typeof(byte)); yield return factory(nullC, typeof(sbyte)); yield return factory(nullC, typeof(ushort)); yield return factory(nullC, typeof(short)); yield return factory(nullC, typeof(uint)); yield return factory(nullC, typeof(int)); yield return factory(nullC, typeof(ulong)); yield return factory(nullC, typeof(long)); yield return factory(nullC, typeof(float)); yield return factory(nullC, typeof(double)); yield return factory(nullC, typeof(char)); yield return factory(nullC, typeof(TimeSpan)); yield return factory(nullC, typeof(DayOfWeek)); } } } private static IEnumerable<Expression> ConvertNullToNullableValue() { ConstantExpression nullC = Expression.Constant(null); var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { foreach (var b in new[] { false, true }) { yield return factory(nullC, typeof(byte?)); yield return factory(nullC, typeof(sbyte?)); yield return factory(nullC, typeof(ushort?)); yield return factory(nullC, typeof(short?)); yield return factory(nullC, typeof(uint?)); yield return factory(nullC, typeof(int?)); yield return factory(nullC, typeof(ulong?)); yield return factory(nullC, typeof(long?)); yield return factory(nullC, typeof(float?)); yield return factory(nullC, typeof(double?)); yield return factory(nullC, typeof(char?)); yield return factory(nullC, typeof(TimeSpan?)); yield return factory(nullC, typeof(DayOfWeek?)); } } } private static IEnumerable<Expression> ConvertBoxing() { // C# Language Specification - 4.3.1 Boxing conversions // ---------------------------------------------------- var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { // >>> From any value-type to the type object. // >>> From any value-type to the type System.ValueType. foreach (var t in new[] { typeof(object), typeof(ValueType) }) { yield return factory(Expression.Constant(1, typeof(int)), t); yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(DayOfWeek)), t); yield return factory(Expression.Constant(new TimeSpan(3, 14, 15), typeof(TimeSpan)), t); yield return factory(Expression.Constant(1, typeof(int?)), t); yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(DayOfWeek?)), t); yield return factory(Expression.Constant(new TimeSpan(3, 14, 15), typeof(TimeSpan?)), t); yield return factory(Expression.Constant(null, typeof(int?)), t); yield return factory(Expression.Constant(null, typeof(DayOfWeek?)), t); yield return factory(Expression.Constant(null, typeof(TimeSpan?)), t); } // >>> From any non-nullable-value-type to any interface-type implemented by the value-type. foreach (var o in new object[] { 1, DayOfWeek.Monday, new TimeSpan(3, 14, 15) }) { Type t = o.GetType(); ConstantExpression c = Expression.Constant(o, t); foreach (var i in t.GetTypeInfo().ImplementedInterfaces) { yield return factory(c, i); } } // >>> From any nullable-type to any interface-type implemented by the underlying type of the nullable-type. foreach (var o in new object[] { (int?)1, (DayOfWeek?)DayOfWeek.Monday, (TimeSpan?)new TimeSpan(3, 14, 15) }) { Type t = o.GetType(); Type n = typeof(Nullable<>).MakeGenericType(t); foreach (var c in new[] { Expression.Constant(o, n), Expression.Constant(null, n) }) { foreach (var i in t.GetTypeInfo().ImplementedInterfaces) { yield return factory(c, i); } } } // >>> From any enum-type to the type System.Enum. { yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(DayOfWeek)), typeof(Enum)); } // >>> From any nullable-type with an underlying enum-type to the type System.Enum. { yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(DayOfWeek?)), typeof(Enum)); yield return factory(Expression.Constant(null, typeof(DayOfWeek?)), typeof(Enum)); } } } private static IEnumerable<Expression> ConvertUnboxing() { // C# Language Specification - 4.3.2 Unboxing conversions // ------------------------------------------------------ var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { // >>> From the type object to any value-type. // >>> From the type System.ValueType to any value-type. foreach (var o in new object[] { 1, DayOfWeek.Monday, new TimeSpan(3, 14, 15) }) { Type t = o.GetType(); Type n = typeof(Nullable<>).MakeGenericType(t); foreach (var f in new[] { typeof(object), typeof(ValueType) }) { yield return factory(Expression.Constant(o, typeof(object)), t); yield return factory(Expression.Constant(o, typeof(object)), n); } } // >>> From any interface-type to any non-nullable-value-type that implements the interface-type. foreach (var o in new object[] { 1, DayOfWeek.Monday, new TimeSpan(3, 14, 15) }) { Type t = o.GetType(); foreach (var i in t.GetTypeInfo().ImplementedInterfaces) { yield return factory(Expression.Constant(o, i), t); } } // >>> From any interface-type to any nullable-type whose underlying type implements the interface-type. foreach (var o in new object[] { 1, DayOfWeek.Monday, new TimeSpan(3, 14, 15) }) { Type t = o.GetType(); Type n = typeof(Nullable<>).MakeGenericType(t); foreach (var i in t.GetTypeInfo().ImplementedInterfaces) { yield return factory(Expression.Constant(o, i), n); } } // >>> From the type System.Enum to any enum-type. { yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(Enum)), typeof(DayOfWeek)); } // >>> From the type System.Enum to any nullable-type with an underlying enum-type. { yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(Enum)), typeof(DayOfWeek?)); yield return factory(Expression.Constant(null, typeof(Enum)), typeof(DayOfWeek?)); } } } private static IEnumerable<Expression> ConvertDelegates() { var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { yield return factory(Expression.Constant((Action)(() => { })), typeof(Action)); yield return factory(Expression.Constant((Action<int>)(x => { })), typeof(Action<int>)); yield return factory(Expression.Constant((Action<int, object>)((x, o) => { })), typeof(Action<int, object>)); yield return factory(Expression.Constant((Action<int, object>)((x, o) => { })), typeof(Action<int, string>)); // contravariant yield return factory(Expression.Constant((Action<object, int>)((o, x) => { })), typeof(Action<string, int>)); // contravariant yield return factory(Expression.Constant((Func<int>)(() => 42)), typeof(Func<int>)); yield return factory(Expression.Constant((Func<string>)(() => "bar")), typeof(Func<string>)); yield return factory(Expression.Constant((Func<string>)(() => "bar")), typeof(Func<object>)); // covariant yield return factory(Expression.Constant((Func<int, string>)(x => "bar")), typeof(Func<int, object>)); // covariant yield return factory(Expression.Constant((Func<object, string>)(o => "bar")), typeof(Func<string, object>)); // contravariant and covariant yield return factory(Expression.Constant((Func<object, int, string>)((o, x) => "bar")), typeof(Func<string, int, object>)); // contravariant and covariant yield return factory(Expression.Constant((Func<int, object, string>)((x, o) => "bar")), typeof(Func<int, string, object>)); // contravariant and covariant } } private static IEnumerable<Expression> ConvertUnboxingInvalidCast() { var objs = new object[] { 1, 1L, 1.0f, 1.0, true, TimeSpan.FromSeconds(1), "bar" }; Type[] types = objs.Select(o => o.GetType()).ToArray(); foreach (var o in objs) { ConstantExpression c = Expression.Constant(o, typeof(object)); foreach (var t in types) { if (t != o.GetType()) { yield return Expression.Convert(c, t); if (t.IsValueType) { Type n = typeof(Nullable<>).MakeGenericType(t); yield return Expression.Convert(c, n); } } } } } #endregion #region Test verifiers private static void VerifyUnaryConvert(Expression e, object o, bool useInterpreter) { Expression<Func<object>> f = Expression.Lambda<Func<object>>( Expression.Convert(e, typeof(object))); Func<object> c = f.Compile(useInterpreter); Assert.Equal(o, c()); } private static void VerifyUnaryConvertThrows<T>(Expression e, bool useInterpreter) where T : Exception { Expression<Func<object>> f = Expression.Lambda<Func<object>>( Expression.Convert(e, typeof(object))); Func<object> c = f.Compile(useInterpreter); Assert.Throws<T>(() => c()); } private static void VerifyUnaryConvert(Expression e, bool useInterpreter) { Expression<Func<object>> f = Expression.Lambda<Func<object>>( Expression.Convert(e, typeof(object))); Func<object> c = f.Compile(useInterpreter); c(); // should not throw } #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.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public static class UnaryConvertTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertBoxingTest(bool useInterpreter) { foreach (var e in ConvertBoxing()) { VerifyUnaryConvert(e, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertUnboxingTest(bool useInterpreter) { foreach (var e in ConvertUnboxing()) { VerifyUnaryConvert(e, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertDelegatesTest(bool useInterpreter) { foreach (var e in ConvertDelegates()) { VerifyUnaryConvert(e, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertUnboxingInvalidCastTest(bool useInterpreter) { foreach (var e in ConvertUnboxingInvalidCast()) { VerifyUnaryConvertThrows<InvalidCastException>(e, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryConvertBooleanToNumericTest(bool useInterpreter) { foreach (var kv in ConvertBooleanToNumeric()) { VerifyUnaryConvert(kv.Key, kv.Value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertNullToNonNullableValueTest(bool useInterpreter) { foreach (var e in ConvertNullToNonNullableValue()) { VerifyUnaryConvertThrows<NullReferenceException>(e, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertNullToNullableValueTest(bool useInterpreter) { foreach (var e in ConvertNullToNullableValue()) { VerifyUnaryConvert(e, null, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertUnderlyingTypeToEnumTypeTest(bool useInterpreter) { DayOfWeek enumValue = DayOfWeek.Monday; var value = (int)enumValue; foreach (var o in new[] { Expression.Constant(value, typeof(int)), Expression.Constant(value, typeof(ValueType)), Expression.Constant(value, typeof(object)) }) { VerifyUnaryConvert(Expression.Convert(o, typeof(DayOfWeek)), enumValue, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertUnderlyingTypeToNullableEnumTypeTest(bool useInterpreter) { DayOfWeek enumValue = DayOfWeek.Monday; var value = (int)enumValue; ConstantExpression cInt = Expression.Constant(value, typeof(int)); VerifyUnaryConvert(Expression.Convert(cInt, typeof(DayOfWeek?)), enumValue, useInterpreter); ConstantExpression cObj = Expression.Constant(value, typeof(object)); VerifyUnaryConvertThrows<InvalidCastException>(Expression.Convert(cObj, typeof(DayOfWeek?)), useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertArrayToIncompatibleTypeTest(bool useInterpreter) { var arr = new object[] { "bar" }; foreach (var t in new[] { typeof(string[]), typeof(IEnumerable<char>[]) }) { VerifyUnaryConvertThrows<InvalidCastException>(Expression.Convert(Expression.Constant(arr), t), useInterpreter); } } [Fact] public static void ToStringTest() { // NB: Unlike TypeAs, the output does not include the type we're converting to UnaryExpression e1 = Expression.Convert(Expression.Parameter(typeof(object), "o"), typeof(int)); Assert.Equal("Convert(o, Int32)", e1.ToString()); UnaryExpression e2 = Expression.ConvertChecked(Expression.Parameter(typeof(long), "x"), typeof(int)); Assert.Equal("ConvertChecked(x, Int32)", e2.ToString()); } private static IEnumerable<KeyValuePair<Expression, object>> ConvertBooleanToNumeric() { ConstantExpression boolF = Expression.Constant(false); ConstantExpression boolT = Expression.Constant(true); var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { foreach (var b in new[] { false, true }) { yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(byte)), (byte)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(sbyte)), (sbyte)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(ushort)), (ushort)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(short)), (short)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(uint)), (uint)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(int)), (int)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(ulong)), (ulong)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(long)), (long)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(float)), (float)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(double)), (double)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(char)), (char)(b ? 1 : 0)); } } } private static IEnumerable<Expression> ConvertNullToNonNullableValue() { ConstantExpression nullC = Expression.Constant(null); var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { foreach (var b in new[] { false, true }) { yield return factory(nullC, typeof(byte)); yield return factory(nullC, typeof(sbyte)); yield return factory(nullC, typeof(ushort)); yield return factory(nullC, typeof(short)); yield return factory(nullC, typeof(uint)); yield return factory(nullC, typeof(int)); yield return factory(nullC, typeof(ulong)); yield return factory(nullC, typeof(long)); yield return factory(nullC, typeof(float)); yield return factory(nullC, typeof(double)); yield return factory(nullC, typeof(char)); yield return factory(nullC, typeof(TimeSpan)); yield return factory(nullC, typeof(DayOfWeek)); } } } private static IEnumerable<Expression> ConvertNullToNullableValue() { ConstantExpression nullC = Expression.Constant(null); var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { foreach (var b in new[] { false, true }) { yield return factory(nullC, typeof(byte?)); yield return factory(nullC, typeof(sbyte?)); yield return factory(nullC, typeof(ushort?)); yield return factory(nullC, typeof(short?)); yield return factory(nullC, typeof(uint?)); yield return factory(nullC, typeof(int?)); yield return factory(nullC, typeof(ulong?)); yield return factory(nullC, typeof(long?)); yield return factory(nullC, typeof(float?)); yield return factory(nullC, typeof(double?)); yield return factory(nullC, typeof(char?)); yield return factory(nullC, typeof(TimeSpan?)); yield return factory(nullC, typeof(DayOfWeek?)); } } } private static IEnumerable<Expression> ConvertBoxing() { // C# Language Specification - 4.3.1 Boxing conversions // ---------------------------------------------------- var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { // >>> From any value-type to the type object. // >>> From any value-type to the type System.ValueType. foreach (var t in new[] { typeof(object), typeof(ValueType) }) { yield return factory(Expression.Constant(1, typeof(int)), t); yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(DayOfWeek)), t); yield return factory(Expression.Constant(new TimeSpan(3, 14, 15), typeof(TimeSpan)), t); yield return factory(Expression.Constant(1, typeof(int?)), t); yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(DayOfWeek?)), t); yield return factory(Expression.Constant(new TimeSpan(3, 14, 15), typeof(TimeSpan?)), t); yield return factory(Expression.Constant(null, typeof(int?)), t); yield return factory(Expression.Constant(null, typeof(DayOfWeek?)), t); yield return factory(Expression.Constant(null, typeof(TimeSpan?)), t); } // >>> From any non-nullable-value-type to any interface-type implemented by the value-type. foreach (var o in new object[] { 1, DayOfWeek.Monday, new TimeSpan(3, 14, 15) }) { Type t = o.GetType(); ConstantExpression c = Expression.Constant(o, t); foreach (var i in t.GetTypeInfo().ImplementedInterfaces) { yield return factory(c, i); } } // >>> From any nullable-type to any interface-type implemented by the underlying type of the nullable-type. foreach (var o in new object[] { (int?)1, (DayOfWeek?)DayOfWeek.Monday, (TimeSpan?)new TimeSpan(3, 14, 15) }) { Type t = o.GetType(); Type n = typeof(Nullable<>).MakeGenericType(t); foreach (var c in new[] { Expression.Constant(o, n), Expression.Constant(null, n) }) { foreach (var i in t.GetTypeInfo().ImplementedInterfaces) { yield return factory(c, i); } } } // >>> From any enum-type to the type System.Enum. { yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(DayOfWeek)), typeof(Enum)); } // >>> From any nullable-type with an underlying enum-type to the type System.Enum. { yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(DayOfWeek?)), typeof(Enum)); yield return factory(Expression.Constant(null, typeof(DayOfWeek?)), typeof(Enum)); } } } private static IEnumerable<Expression> ConvertUnboxing() { // C# Language Specification - 4.3.2 Unboxing conversions // ------------------------------------------------------ var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { // >>> From the type object to any value-type. // >>> From the type System.ValueType to any value-type. foreach (var o in new object[] { 1, DayOfWeek.Monday, new TimeSpan(3, 14, 15) }) { Type t = o.GetType(); Type n = typeof(Nullable<>).MakeGenericType(t); foreach (var f in new[] { typeof(object), typeof(ValueType) }) { yield return factory(Expression.Constant(o, typeof(object)), t); yield return factory(Expression.Constant(o, typeof(object)), n); } } // >>> From any interface-type to any non-nullable-value-type that implements the interface-type. foreach (var o in new object[] { 1, DayOfWeek.Monday, new TimeSpan(3, 14, 15) }) { Type t = o.GetType(); foreach (var i in t.GetTypeInfo().ImplementedInterfaces) { yield return factory(Expression.Constant(o, i), t); } } // >>> From any interface-type to any nullable-type whose underlying type implements the interface-type. foreach (var o in new object[] { 1, DayOfWeek.Monday, new TimeSpan(3, 14, 15) }) { Type t = o.GetType(); Type n = typeof(Nullable<>).MakeGenericType(t); foreach (var i in t.GetTypeInfo().ImplementedInterfaces) { yield return factory(Expression.Constant(o, i), n); } } // >>> From the type System.Enum to any enum-type. { yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(Enum)), typeof(DayOfWeek)); } // >>> From the type System.Enum to any nullable-type with an underlying enum-type. { yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(Enum)), typeof(DayOfWeek?)); yield return factory(Expression.Constant(null, typeof(Enum)), typeof(DayOfWeek?)); } } } private static IEnumerable<Expression> ConvertDelegates() { var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { yield return factory(Expression.Constant((Action)(() => { })), typeof(Action)); yield return factory(Expression.Constant((Action<int>)(x => { })), typeof(Action<int>)); yield return factory(Expression.Constant((Action<int, object>)((x, o) => { })), typeof(Action<int, object>)); yield return factory(Expression.Constant((Action<int, object>)((x, o) => { })), typeof(Action<int, string>)); // contravariant yield return factory(Expression.Constant((Action<object, int>)((o, x) => { })), typeof(Action<string, int>)); // contravariant yield return factory(Expression.Constant((Func<int>)(() => 42)), typeof(Func<int>)); yield return factory(Expression.Constant((Func<string>)(() => "bar")), typeof(Func<string>)); yield return factory(Expression.Constant((Func<string>)(() => "bar")), typeof(Func<object>)); // covariant yield return factory(Expression.Constant((Func<int, string>)(x => "bar")), typeof(Func<int, object>)); // covariant yield return factory(Expression.Constant((Func<object, string>)(o => "bar")), typeof(Func<string, object>)); // contravariant and covariant yield return factory(Expression.Constant((Func<object, int, string>)((o, x) => "bar")), typeof(Func<string, int, object>)); // contravariant and covariant yield return factory(Expression.Constant((Func<int, object, string>)((x, o) => "bar")), typeof(Func<int, string, object>)); // contravariant and covariant } } private static IEnumerable<Expression> ConvertUnboxingInvalidCast() { var objs = new object[] { 1, 1L, 1.0f, 1.0, true, TimeSpan.FromSeconds(1), "bar" }; Type[] types = objs.Select(o => o.GetType()).ToArray(); foreach (var o in objs) { ConstantExpression c = Expression.Constant(o, typeof(object)); foreach (var t in types) { if (t != o.GetType()) { yield return Expression.Convert(c, t); if (t.IsValueType) { Type n = typeof(Nullable<>).MakeGenericType(t); yield return Expression.Convert(c, n); } } } } } #endregion #region Test verifiers private static void VerifyUnaryConvert(Expression e, object o, bool useInterpreter) { Expression<Func<object>> f = Expression.Lambda<Func<object>>( Expression.Convert(e, typeof(object))); Func<object> c = f.Compile(useInterpreter); Assert.Equal(o, c()); } private static void VerifyUnaryConvertThrows<T>(Expression e, bool useInterpreter) where T : Exception { Expression<Func<object>> f = Expression.Lambda<Func<object>>( Expression.Convert(e, typeof(object))); Func<object> c = f.Compile(useInterpreter); Assert.Throws<T>(() => c()); } private static void VerifyUnaryConvert(Expression e, bool useInterpreter) { Expression<Func<object>> f = Expression.Lambda<Func<object>>( Expression.Convert(e, typeof(object))); Func<object> c = f.Compile(useInterpreter); c(); // should not throw } #endregion } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Private.CoreLib/src/System/IMultiplicativeIdentity.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.Versioning; #if !FEATURE_GENERIC_MATH #error FEATURE_GENERIC_MATH is not defined #endif namespace System { /// <summary>Defines a mechanism for getting the multiplicative identity of a given type.</summary> /// <typeparam name="TSelf">The type that implements this interface.</typeparam> /// <typeparam name="TResult">The type that contains the multiplicative identify of <typeparamref name="TSelf" />.</typeparam> [RequiresPreviewFeatures(Number.PreviewFeatureMessage, Url = Number.PreviewFeatureUrl)] public interface IMultiplicativeIdentity<TSelf, TResult> where TSelf : IMultiplicativeIdentity<TSelf, TResult> { /// <summary>Gets the multiplicative identity of the current type.</summary> static abstract TResult MultiplicativeIdentity { 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.Runtime.Versioning; #if !FEATURE_GENERIC_MATH #error FEATURE_GENERIC_MATH is not defined #endif namespace System { /// <summary>Defines a mechanism for getting the multiplicative identity of a given type.</summary> /// <typeparam name="TSelf">The type that implements this interface.</typeparam> /// <typeparam name="TResult">The type that contains the multiplicative identify of <typeparamref name="TSelf" />.</typeparam> [RequiresPreviewFeatures(Number.PreviewFeatureMessage, Url = Number.PreviewFeatureUrl)] public interface IMultiplicativeIdentity<TSelf, TResult> where TSelf : IMultiplicativeIdentity<TSelf, TResult> { /// <summary>Gets the multiplicative identity of the current type.</summary> static abstract TResult MultiplicativeIdentity { get; } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // This program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in. // It is available from http://www.codeplex.com/hyperAddin #if ES_BUILD_STANDALONE #define FEATURE_MANAGED_ETW_CHANNELS // #define FEATURE_ADVANCED_MANAGED_ETW_CHANNELS #endif /* DESIGN NOTES DESIGN NOTES DESIGN NOTES DESIGN NOTES */ // DESIGN NOTES // Over the years EventSource has become more complex and so it is important to understand // the basic structure of the code to insure that it does not grow more complex. // // Basic Model // // PRINCIPLE: EventSource - ETW decoupling // // Conceptually an EventSouce is something that takes event logging data from the source methods // to the EventListener that can subscribe to them. Note that CONCEPTUALLY EVENTSOURCES DON'T // KNOW ABOUT ETW!. The MODEL of the system is that there is a special EventListener which // we will call the EtwEventListener, that forwards commands from ETW to EventSources and // listens to EventSources and forwards on those events to ETW. Thus the model should // be that you DON'T NEED ETW. // // Now in actual practice, EventSouce have rather intimate knowledge of ETW and send events // to it directly, but this can be VIEWED AS AN OPTIMIZATION. // // Basic Event Data Flow: // // There are two ways for event Data to enter the system // 1) WriteEvent* and friends. This is called the 'contract' based approach because // you write a method per event which forms a contract that is know at compile time. // In this scheme each event is given an EVENTID (small integer), which is its identity // 2) Write<T> methods. This is called the 'dynamic' approach because new events // can be created on the fly. Event identity is determined by the event NAME, and these // are not quite as efficient at runtime since you have at least a hash table lookup // on every event write. // // EventSource-EventListener transfer fully supports both ways of writing events (either contract // based (WriteEvent*) or dynamic (Write<T>)). Both ways fully support the same set of data // types. It is recommended, however, that you use the contract based approach when the event scheme // is known at compile time (that is whenever possible). It is more efficient, but more importantly // it makes the contract very explicit, and centralizes all policy about logging. These are good // things. The Write<T> API is really meant for more ad-hoc cases. // // Allowed Data: // // Note that EventSource-EventListeners have a conceptual serialization-deserialization that happens // during the transfer. In particular object identity is not preserved, some objects are morphed, // and not all data types are supported. In particular you can pass // // A Valid type to log to an EventSource include // * Primitive data types // * IEnumerable<T> of valid types T (this include arrays) (* New for V4.6) // * Explicitly Opted in class or struct with public property Getters over Valid types. (* New for V4.6) // // This set of types is roughly a generalization of JSON support (basically primitives, bags, and arrays). // // Explicitly allowed structs include (* New for V4.6) // * Marked with the EventData attribute // * implicitly defined (e.g the C# new {x = 3, y = 5} syntax) // * KeyValuePair<K,V> (thus dictionaries can be passed since they are an IEnumerable of KeyValuePair) // // When classes are returned in an EventListener, what is returned is something that implements // IDictionary<string, T>. Thus when objects are passed to an EventSource they are transformed // into a key-value bag (the IDictionary<string, T>) for consumption in the listener. These // are obviously NOT the original objects. // // ETW serialization formats: // // As mentioned, conceptually EventSources send data to EventListeners and there is a conceptual // copy/morph of that data as described above. In addition the .NET framework supports a conceptual // ETWListener that will send the data to the ETW stream. If you use this feature, the data needs // to be serialized in a way that ETW supports. ETW supports the following serialization formats // // 1) Manifest Based serialization. // 2) SelfDescribing serialization (TraceLogging style in the TraceLogging directory) // // A key factor is that the Write<T> method, which supports on the fly definition of events, can't // support the manifest based serialization because the manifest needs the schema of all events // to be known before any events are emitted. This implies the following: // // If you use Write<T> and the output goes to ETW it will use the SelfDescribing format. // If you use the EventSource(string) constructor for an eventSource (in which you don't // create a subclass), the default is also to use Self-Describing serialization. In addition // you can use the EventSoruce(EventSourceSettings) constructor to also explicitly specify // Self-Describing serialization format. These affect the WriteEvent* APIs going to ETW. // // Note that none of this ETW serialization logic affects EventListeners. Only the ETW listener. // // ************************************************************************************* // *** INTERNALS: Event Propagation // // Data enters the system either though // // 1) A user defined method in the user defined subclass of EventSource which calls // A) A typesafe type specific overload of WriteEvent(ID, ...) e.g. WriteEvent(ID, string, string) // * which calls into the unsafe WriteEventCore(ID COUNT EventData*) WriteEventWithRelatedActivityIdCore() // B) The typesafe overload WriteEvent(ID, object[]) which calls the private helper WriteEventVarargs(ID, Guid* object[]) // C) Directly into the unsafe WriteEventCore(ID, COUNT EventData*) or WriteEventWithRelatedActivityIdCore() // // All event data eventually flows to one of // * WriteEventWithRelatedActivityIdCore(ID, Guid*, COUNT, EventData*) // * WriteEventVarargs(ID, Guid*, object[]) // // 2) A call to one of the overloads of Write<T>. All these overloads end up in // * WriteImpl<T>(EventName, Options, Data, Guid*, Guid*) // // On output there are the following routines // Writing to all listeners that are NOT ETW, we have the following routines // * WriteToAllListeners(ID, Guid*, Guid*, COUNT, EventData*) // * WriteToAllListeners(ID, Guid*, Guid*, object[]) // * WriteToAllListeners(NAME, Guid*, Guid*, EventPayload) // // EventPayload is the internal type that implements the IDictionary<string, object> interface // The EventListeners will pass back for serialized classes for nested object, but // WriteToAllListeners(NAME, Guid*, Guid*, EventPayload) unpacks this and uses the fields as if they // were parameters to a method. // // The first two are used for the WriteEvent* case, and the later is used for the Write<T> case. // // Writing to ETW, Manifest Based // EventProvider.WriteEvent(EventDescriptor, Guid*, COUNT, EventData*) // EventProvider.WriteEvent(EventDescriptor, Guid*, object[]) // Writing to ETW, Self-Describing format // WriteMultiMerge(NAME, Options, Types, EventData*) // WriteMultiMerge(NAME, Options, Types, object[]) // WriteImpl<T> has logic that knows how to serialize (like WriteMultiMerge) but also knows // where it will write it to // // All ETW writes eventually call // EventWriteTransfer // EventProvider.WriteEventRaw - sets last error // EventSource.WriteEventRaw - Does EventSource exception handling logic // WriteMultiMerge // WriteImpl<T> // EventProvider.WriteEvent(EventDescriptor, Guid*, COUNT, EventData*) // EventProvider.WriteEvent(EventDescriptor, Guid*, object[]) // // Serialization: We have a bit of a hodge-podge of serializers right now. Only the one for ETW knows // how to deal with nested classes or arrays. I will call this serializer the 'TypeInfo' serializer // since it is the TraceLoggingTypeInfo structure that knows how to do this. Effectively for a type you // can call one of these // WriteMetadata - transforms the type T into serialization meta data blob for that type // WriteObjectData - transforms an object of T into serialization data blob for that instance // GetData - transforms an object of T into its deserialized form suitable for passing to EventListener. // The first two are used to serialize something for ETW. The second one is used to transform the object // for use by the EventListener. We also have a 'DecodeObject' method that will take a EventData* and // deserialize to pass to an EventListener, but it only works on primitive types (types supported in version V4.5). // // It is an important observation that while EventSource does support users directly calling with EventData* // blobs, we ONLY support that for the primitive types (V4.5 level support). Thus while there is a EventData* // path through the system it is only for some types. The object[] path is the more general (but less efficient) path. // // TODO There is cleanup needed There should be no divergence until WriteEventRaw. // // TODO: We should have a single choke point (right now we always have this parallel EventData* and object[] path. This // was historical (at one point we tried to pass object directly from EventSoruce to EventListener. That was always // fragile and a compatibility headache, but we have finally been forced into the idea that there is always a transformation. // This allows us to use the EventData* form to be the canonical data format in the low level APIs. This also gives us the // opportunity to expose this format to EventListeners in the future. // using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Numerics; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; #if ES_BUILD_STANDALONE using System.Security.Permissions; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing { #else namespace System.Diagnostics.Tracing { [Conditional("NEEDED_FOR_SOURCE_GENERATOR_ONLY")] [AttributeUsage(AttributeTargets.Class)] internal sealed class EventSourceAutoGenerateAttribute : Attribute { } #endif /// <summary> /// This class is meant to be inherited by a user-defined event source in order to define a managed /// ETW provider. Please See DESIGN NOTES above for the internal architecture. /// The minimal definition of an EventSource simply specifies a number of ETW event methods that /// call one of the EventSource.WriteEvent overloads, <see cref="EventSource.WriteEventCore"/>, /// or <see cref="EventSource.WriteEventWithRelatedActivityIdCore"/> to log them. This functionality /// is sufficient for many users. /// <para> /// To achieve more control over the ETW provider manifest exposed by the event source type, the /// [<see cref="EventAttribute"/>] attributes can be specified for the ETW event methods. /// </para><para> /// For very advanced EventSources, it is possible to intercept the commands being given to the /// eventSource and change what filtering is done (see EventListener.EnableEvents and /// <see cref="EventListener.DisableEvents"/>) or cause actions to be performed by the eventSource, /// e.g. dumping a data structure (see EventSource.SendCommand and /// <see cref="EventSource.OnEventCommand"/>). /// </para><para> /// The eventSources can be turned on with Windows ETW controllers (e.g. logman), immediately. /// It is also possible to control and intercept the data dispatcher programmatically. See /// <see cref="EventListener"/> for more. /// </para> /// </summary> /// <remarks> /// This is a minimal definition for a custom event source: /// <code> /// [EventSource(Name="Samples.Demos.Minimal")] /// sealed class MinimalEventSource : EventSource /// { /// public static MinimalEventSource Log = new MinimalEventSource(); /// public void Load(long ImageBase, string Name) { WriteEvent(1, ImageBase, Name); } /// public void Unload(long ImageBase) { WriteEvent(2, ImageBase); } /// private MinimalEventSource() {} /// } /// </code> /// </remarks> #if !ES_BUILD_STANDALONE // The EnsureDescriptorsInitialized() method might need to access EventSource and its derived type // members and the trimmer ensures that these members are preserved. [DynamicallyAccessedMembers(ManifestMemberTypes)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2113:ReflectionToRequiresUnreferencedCode", Justification = "EnsureDescriptorsInitialized's use of GetType preserves methods on Delegate and MulticastDelegate " + "because the nested type OverrideEventProvider's base type EventProvider defines a delegate. " + "This includes Delegate and MulticastDelegate methods which require unreferenced code, but " + "EnsureDescriptorsInitialized does not access these members and is safe to call.")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2115:ReflectionToDynamicallyAccessedMembers", Justification = "EnsureDescriptorsInitialized's use of GetType preserves methods on Delegate and MulticastDelegate " + "because the nested type OverrideEventProvider's base type EventProvider defines a delegate. " + "This includes Delegate and MulticastDelegate methods which have dynamically accessed members requirements, but " + "EnsureDescriptorsInitialized does not access these members and is safe to call.")] #endif public partial class EventSource : IDisposable { internal static bool IsSupported { get; } = InitializeIsSupported(); private static bool InitializeIsSupported() => AppContext.TryGetSwitch("System.Diagnostics.Tracing.EventSource.IsSupported", out bool isSupported) ? isSupported : true; #if FEATURE_EVENTSOURCE_XPLAT #pragma warning disable CA1823 // field is used to keep listener alive private static readonly EventListener? persistent_Xplat_Listener = IsSupported ? XplatEventLogger.InitializePersistentListener() : null; #pragma warning restore CA1823 #endif //FEATURE_EVENTSOURCE_XPLAT /// <summary> /// The human-friendly name of the eventSource. It defaults to the simple name of the class /// </summary> public string Name => m_name; /// <summary> /// Every eventSource is assigned a GUID to uniquely identify it to the system. /// </summary> public Guid Guid => m_guid; /// <summary> /// Returns true if the eventSource has been enabled at all. This is the preferred test /// to be performed before a relatively expensive EventSource operation. /// </summary> public bool IsEnabled() { return m_eventSourceEnabled; } /// <summary> /// Returns true if events with greater than or equal 'level' and have one of 'keywords' set are enabled. /// /// Note that the result of this function is only an approximation on whether a particular /// event is active or not. It is only meant to be used as way of avoiding expensive /// computation for logging when logging is not on, therefore it sometimes returns false /// positives (but is always accurate when returning false). EventSources are free to /// have additional filtering. /// </summary> public bool IsEnabled(EventLevel level, EventKeywords keywords) { return IsEnabled(level, keywords, EventChannel.None); } /// <summary> /// Returns true if events with greater than or equal 'level' and have one of 'keywords' set are enabled, or /// if 'keywords' specifies a channel bit for a channel that is enabled. /// /// Note that the result of this function only an approximation on whether a particular /// event is active or not. It is only meant to be used as way of avoiding expensive /// computation for logging when logging is not on, therefore it sometimes returns false /// positives (but is always accurate when returning false). EventSources are free to /// have additional filtering. /// </summary> public bool IsEnabled(EventLevel level, EventKeywords keywords, EventChannel channel) { if (!IsEnabled()) return false; if (!IsEnabledCommon(m_eventSourceEnabled, m_level, m_matchAnyKeyword, level, keywords, channel)) return false; return true; } /// <summary> /// Returns the settings for the event source instance /// </summary> public EventSourceSettings Settings => m_config; // Manifest support /// <summary> /// Returns the GUID that uniquely identifies the eventSource defined by 'eventSourceType'. /// This API allows you to compute this without actually creating an instance of the EventSource. /// It only needs to reflect over the type. /// </summary> public static Guid GetGuid(Type eventSourceType) { if (eventSourceType == null) throw new ArgumentNullException(nameof(eventSourceType)); EventSourceAttribute? attrib = (EventSourceAttribute?)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute)); string name = eventSourceType.Name; if (attrib != null) { if (attrib.Guid != null) { if (Guid.TryParse(attrib.Guid, out Guid g)) return g; } if (attrib.Name != null) name = attrib.Name; } if (name == null) { throw new ArgumentException(SR.Argument_InvalidTypeName, nameof(eventSourceType)); } return GenerateGuidFromName(name.ToUpperInvariant()); // Make it case insensitive. } /// <summary> /// Returns the official ETW Provider name for the eventSource defined by 'eventSourceType'. /// This API allows you to compute this without actually creating an instance of the EventSource. /// It only needs to reflect over the type. /// </summary> public static string GetName(Type eventSourceType) { return GetName(eventSourceType, EventManifestOptions.None); } #if !ES_BUILD_STANDALONE private const DynamicallyAccessedMemberTypes ManifestMemberTypes = DynamicallyAccessedMemberTypes.All; #endif /// <summary> /// Returns a string of the XML manifest associated with the eventSourceType. The scheme for this XML is /// documented at in EventManifest Schema https://docs.microsoft.com/en-us/windows/desktop/WES/eventmanifestschema-schema. /// This is the preferred way of generating a manifest to be embedded in the ETW stream as it is fast and /// the fact that it only includes localized entries for the current UI culture is an acceptable tradeoff. /// </summary> /// <param name="eventSourceType">The type of the event source class for which the manifest is generated</param> /// <param name="assemblyPathToIncludeInManifest">The manifest XML fragment contains the string name of the DLL name in /// which it is embedded. This parameter specifies what name will be used</param> /// <returns>The XML data string</returns> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2114:ReflectionToDynamicallyAccessedMembers", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "has dynamically accessed members requirements, but EnsureDescriptorsInitialized does not "+ "access this member and is safe to call.")] #endif public static string? GenerateManifest( #if !ES_BUILD_STANDALONE [DynamicallyAccessedMembers(ManifestMemberTypes)] #endif Type eventSourceType, string? assemblyPathToIncludeInManifest) { return GenerateManifest(eventSourceType, assemblyPathToIncludeInManifest, EventManifestOptions.None); } /// <summary> /// Returns a string of the XML manifest associated with the eventSourceType. The scheme for this XML is /// documented at in EventManifest Schema https://docs.microsoft.com/en-us/windows/desktop/WES/eventmanifestschema-schema. /// Pass EventManifestOptions.AllCultures when generating a manifest to be registered on the machine. This /// ensures that the entries in the event log will be "optimally" localized. /// </summary> /// <param name="eventSourceType">The type of the event source class for which the manifest is generated</param> /// <param name="assemblyPathToIncludeInManifest">The manifest XML fragment contains the string name of the DLL name in /// which it is embedded. This parameter specifies what name will be used</param> /// <param name="flags">The flags to customize manifest generation. If flags has bit OnlyIfNeededForRegistration specified /// this returns null when the eventSourceType does not require explicit registration</param> /// <returns>The XML data string or null</returns> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2114:ReflectionToDynamicallyAccessedMembers", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "has dynamically accessed members requirements, but EnsureDescriptorsInitialized does not "+ "access this member and is safe to call.")] #endif public static string? GenerateManifest( #if !ES_BUILD_STANDALONE [DynamicallyAccessedMembers(ManifestMemberTypes)] #endif Type eventSourceType, string? assemblyPathToIncludeInManifest, EventManifestOptions flags) { if (!IsSupported) { return null; } if (eventSourceType == null) throw new ArgumentNullException(nameof(eventSourceType)); byte[]? manifestBytes = EventSource.CreateManifestAndDescriptors(eventSourceType, assemblyPathToIncludeInManifest, null, flags); return (manifestBytes == null) ? null : Encoding.UTF8.GetString(manifestBytes, 0, manifestBytes.Length); } // EventListener support /// <summary> /// returns a list (IEnumerable) of all sources in the appdomain). EventListeners typically need this. /// </summary> /// <returns></returns> public static IEnumerable<EventSource> GetSources() { if (!IsSupported) { return Array.Empty<EventSource>(); } var ret = new List<EventSource>(); lock (EventListener.EventListenersLock) { Debug.Assert(EventListener.s_EventSources != null); foreach (WeakReference<EventSource> eventSourceRef in EventListener.s_EventSources) { if (eventSourceRef.TryGetTarget(out EventSource? eventSource) && !eventSource.IsDisposed) ret.Add(eventSource); } } return ret; } /// <summary> /// Send a command to a particular EventSource identified by 'eventSource'. /// Calling this routine simply forwards the command to the EventSource.OnEventCommand /// callback. What the EventSource does with the command and its arguments are from /// that point EventSource-specific. /// </summary> /// <param name="eventSource">The instance of EventSource to send the command to</param> /// <param name="command">A positive user-defined EventCommand, or EventCommand.SendManifest</param> /// <param name="commandArguments">A set of (name-argument, value-argument) pairs associated with the command</param> public static void SendCommand(EventSource eventSource, EventCommand command, IDictionary<string, string?>? commandArguments) { if (!IsSupported) { return; } if (eventSource is null) { throw new ArgumentNullException(nameof(eventSource)); } // User-defined EventCommands should not conflict with the reserved commands. if ((int)command <= (int)EventCommand.Update && (int)command != (int)EventCommand.SendManifest) { throw new ArgumentException(SR.EventSource_InvalidCommand, nameof(command)); } eventSource.SendCommand(null, EventProviderType.ETW, 0, 0, command, true, EventLevel.LogAlways, EventKeywords.None, commandArguments); } // Error APIs. (We don't throw by default, but you can probe for status) /// <summary> /// Because /// /// 1) Logging is often optional and thus should not generate fatal errors (exceptions) /// 2) EventSources are often initialized in class constructors (which propagate exceptions poorly) /// /// The event source constructor does not throw exceptions. Instead we remember any exception that /// was generated (it is also logged to Trace.WriteLine). /// </summary> public Exception? ConstructionException => m_constructionException; /// <summary> /// EventSources can have arbitrary string key-value pairs associated with them called Traits. /// These traits are not interpreted by the EventSource but may be interpreted by EventListeners /// (e.g. like the built in ETW listener). These traits are specified at EventSource /// construction time and can be retrieved by using this GetTrait API. /// </summary> /// <param name="key">The key to look up in the set of key-value pairs passed to the EventSource constructor</param> /// <returns>The value string associated with key. Will return null if there is no such key.</returns> public string? GetTrait(string key) { if (m_traits != null) { for (int i = 0; i < m_traits.Length - 1; i += 2) { if (m_traits[i] == key) return m_traits[i + 1]; } } return null; } /// <summary> /// Displays the name and GUID for the eventSource for debugging purposes. /// </summary> public override string ToString() { if (!IsSupported) return base.ToString()!; return SR.Format(SR.EventSource_ToString, Name, Guid); } /// <summary> /// Fires when a Command (e.g. Enable) comes from a an EventListener. /// </summary> public event EventHandler<EventCommandEventArgs>? EventCommandExecuted { add { if (value == null) return; m_eventCommandExecuted += value; // If we have an EventHandler<EventCommandEventArgs> attached to the EventSource before the first command arrives // It should get a chance to handle the deferred commands. EventCommandEventArgs? deferredCommands = m_deferredCommands; while (deferredCommands != null) { value(this, deferredCommands); deferredCommands = deferredCommands.nextCommand; } } remove { m_eventCommandExecuted -= value; } } #region ActivityID /// <summary> /// When a thread starts work that is on behalf of 'something else' (typically another /// thread or network request) it should mark the thread as working on that other work. /// This API marks the current thread as working on activity 'activityID'. This API /// should be used when the caller knows the thread's current activity (the one being /// overwritten) has completed. Otherwise, callers should prefer the overload that /// return the oldActivityThatWillContinue (below). /// /// All events created with the EventSource on this thread are also tagged with the /// activity ID of the thread. /// /// It is common, and good practice after setting the thread to an activity to log an event /// with a 'start' opcode to indicate that precise time/thread where the new activity /// started. /// </summary> /// <param name="activityId">A Guid that represents the new activity with which to mark /// the current thread</param> public static void SetCurrentThreadActivityId(Guid activityId) { if (!IsSupported) { return; } if (TplEventSource.Log != null) TplEventSource.Log.SetActivityId(activityId); // We ignore errors to keep with the convention that EventSources do not throw errors. // Note we can't access m_throwOnWrites because this is a static method. #if FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING // Set the activity id via EventPipe. EventPipeEventProvider.EventActivityIdControl( Interop.Advapi32.ActivityControl.EVENT_ACTIVITY_CTRL_SET_ID, ref activityId); #endif // FEATURE_PERFTRACING #if TARGET_WINDOWS // Set the activity id via ETW. Interop.Advapi32.EventActivityIdControl( Interop.Advapi32.ActivityControl.EVENT_ACTIVITY_CTRL_SET_ID, ref activityId); #endif // TARGET_WINDOWS #endif // FEATURE_MANAGED_ETW } /// <summary> /// Retrieves the ETW activity ID associated with the current thread. /// </summary> public static Guid CurrentThreadActivityId { get { if (!IsSupported) { return default; } // We ignore errors to keep with the convention that EventSources do not throw // errors. Note we can't access m_throwOnWrites because this is a static method. Guid retVal = default; #if FEATURE_MANAGED_ETW #if TARGET_WINDOWS Interop.Advapi32.EventActivityIdControl( Interop.Advapi32.ActivityControl.EVENT_ACTIVITY_CTRL_GET_ID, ref retVal); #elif FEATURE_PERFTRACING EventPipeEventProvider.EventActivityIdControl( Interop.Advapi32.ActivityControl.EVENT_ACTIVITY_CTRL_GET_ID, ref retVal); #endif // TARGET_WINDOWS #endif // FEATURE_MANAGED_ETW return retVal; } } /// <summary> /// When a thread starts work that is on behalf of 'something else' (typically another /// thread or network request) it should mark the thread as working on that other work. /// This API marks the current thread as working on activity 'activityID'. It returns /// whatever activity the thread was previously marked with. There is a convention that /// callers can assume that callees restore this activity mark before the callee returns. /// To encourage this, this API returns the old activity, so that it can be restored later. /// /// All events created with the EventSource on this thread are also tagged with the /// activity ID of the thread. /// /// It is common, and good practice after setting the thread to an activity to log an event /// with a 'start' opcode to indicate that precise time/thread where the new activity /// started. /// </summary> /// <param name="activityId">A Guid that represents the new activity with which to mark /// the current thread</param> /// <param name="oldActivityThatWillContinue">The Guid that represents the current activity /// which will continue at some point in the future, on the current thread</param> public static void SetCurrentThreadActivityId(Guid activityId, out Guid oldActivityThatWillContinue) { if (!IsSupported) { oldActivityThatWillContinue = default; return; } oldActivityThatWillContinue = activityId; #if FEATURE_MANAGED_ETW // We ignore errors to keep with the convention that EventSources do not throw errors. // Note we can't access m_throwOnWrites because this is a static method. #if FEATURE_PERFTRACING && TARGET_WINDOWS EventPipeEventProvider.EventActivityIdControl( Interop.Advapi32.ActivityControl.EVENT_ACTIVITY_CTRL_SET_ID, ref oldActivityThatWillContinue); #elif FEATURE_PERFTRACING EventPipeEventProvider.EventActivityIdControl( Interop.Advapi32.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID, ref oldActivityThatWillContinue); #endif // FEATURE_PERFTRACING && TARGET_WINDOWS #if TARGET_WINDOWS Interop.Advapi32.EventActivityIdControl( Interop.Advapi32.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID, ref oldActivityThatWillContinue); #endif // TARGET_WINDOWS #endif // FEATURE_MANAGED_ETW // We don't call the activityDying callback here because the caller has declared that // it is not dying. if (TplEventSource.Log != null) TplEventSource.Log.SetActivityId(activityId); } #endregion #region protected /// <summary> /// This is the constructor that most users will use to create their eventSource. It takes /// no parameters. The ETW provider name and GUID of the EventSource are determined by the EventSource /// custom attribute (so you can determine these things declaratively). If the GUID for the eventSource /// is not specified in the EventSourceAttribute (recommended), it is Generated by hashing the name. /// If the ETW provider name of the EventSource is not given, the name of the EventSource class is used as /// the ETW provider name. /// </summary> protected EventSource() : this(EventSourceSettings.EtwManifestEventFormat) { } /// <summary> /// By default calling the 'WriteEvent' methods do NOT throw on errors (they silently discard the event). /// This is because in most cases users assume logging is not 'precious' and do NOT wish to have logging failures /// crash the program. However for those applications where logging is 'precious' and if it fails the caller /// wishes to react, setting 'throwOnEventWriteErrors' will cause an exception to be thrown if WriteEvent /// fails. Note the fact that EventWrite succeeds does not necessarily mean that the event reached its destination /// only that operation of writing it did not fail. These EventSources will not generate self-describing ETW events. /// /// For compatibility only use the EventSourceSettings.ThrowOnEventWriteErrors flag instead. /// </summary> // [Obsolete("Use the EventSource(EventSourceSettings) overload")] protected EventSource(bool throwOnEventWriteErrors) : this(EventSourceSettings.EtwManifestEventFormat | (throwOnEventWriteErrors ? EventSourceSettings.ThrowOnEventWriteErrors : 0)) { } /// <summary> /// Construct an EventSource with additional non-default settings (see EventSourceSettings for more) /// </summary> protected EventSource(EventSourceSettings settings) : this(settings, null) { } /// <summary> /// Construct an EventSource with additional non-default settings. /// /// Also specify a list of key-value pairs called traits (you must pass an even number of strings). /// The first string is the key and the second is the value. These are not interpreted by EventSource /// itself but may be interpreted the listeners. Can be fetched with GetTrait(string). /// </summary> /// <param name="settings">See EventSourceSettings for more.</param> /// <param name="traits">A collection of key-value strings (must be an even number).</param> protected EventSource(EventSourceSettings settings, params string[]? traits) { if (IsSupported) { #if FEATURE_PERFTRACING m_eventHandleTable = new TraceLoggingEventHandleTable(); #endif m_config = ValidateSettings(settings); Type myType = this.GetType(); Guid eventSourceGuid = GetGuid(myType); string eventSourceName = GetName(myType); Initialize(eventSourceGuid, eventSourceName, traits); } } #if FEATURE_PERFTRACING // Generate the serialized blobs that describe events for all strongly typed events (that is events that define strongly // typed event methods. Dynamically defined events (that use Write) hare defined on the fly and are handled elsewhere. private unsafe void DefineEventPipeEvents() { // If the EventSource is set to emit all events as TraceLogging events, skip this initialization. // Events will be defined when they are emitted for the first time. if (SelfDescribingEvents) { return; } Debug.Assert(m_eventData != null); Debug.Assert(m_eventPipeProvider != null); int cnt = m_eventData.Length; for (int i = 0; i < cnt; i++) { uint eventID = (uint)m_eventData[i].Descriptor.EventId; if (eventID == 0) continue; byte[]? metadata = EventPipeMetadataGenerator.Instance.GenerateEventMetadata(m_eventData[i]); uint metadataLength = (metadata != null) ? (uint)metadata.Length : 0; string eventName = m_eventData[i].Name; long keywords = m_eventData[i].Descriptor.Keywords; uint eventVersion = m_eventData[i].Descriptor.Version; uint level = m_eventData[i].Descriptor.Level; fixed (byte *pMetadata = metadata) { IntPtr eventHandle = m_eventPipeProvider.m_eventProvider.DefineEventHandle( eventID, eventName, keywords, eventVersion, level, pMetadata, metadataLength); Debug.Assert(eventHandle != IntPtr.Zero); m_eventData[i].EventHandle = eventHandle; } } } #endif /// <summary> /// This method is called when the eventSource is updated by the controller. /// </summary> protected virtual void OnEventCommand(EventCommandEventArgs command) { } #pragma warning disable 1591 // optimized for common signatures (no args) #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId) { WriteEventCore(eventId, 0, null); } // optimized for common signatures (ints) #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, int arg1) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[1]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 4; descrs[0].Reserved = 0; WriteEventCore(eventId, 1, descrs); } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, int arg1, int arg2) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 4; descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 4; descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, int arg1, int arg2, int arg3) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 4; descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 4; descrs[1].Reserved = 0; descrs[2].DataPointer = (IntPtr)(&arg3); descrs[2].Size = 4; descrs[2].Reserved = 0; WriteEventCore(eventId, 3, descrs); } } // optimized for common signatures (longs) #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, long arg1) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[1]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[0].Reserved = 0; WriteEventCore(eventId, 1, descrs); } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, long arg1, long arg2) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 8; descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, long arg1, long arg2, long arg3) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 8; descrs[1].Reserved = 0; descrs[2].DataPointer = (IntPtr)(&arg3); descrs[2].Size = 8; descrs[2].Reserved = 0; WriteEventCore(eventId, 3, descrs); } } // optimized for common signatures (strings) #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, string? arg1) { if (IsEnabled()) { arg1 ??= ""; fixed (char* string1Bytes = arg1) { EventSource.EventData* descrs = stackalloc EventSource.EventData[1]; descrs[0].DataPointer = (IntPtr)string1Bytes; descrs[0].Size = ((arg1.Length + 1) * 2); descrs[0].Reserved = 0; WriteEventCore(eventId, 1, descrs); } } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, string? arg1, string? arg2) { if (IsEnabled()) { arg1 ??= ""; arg2 ??= ""; fixed (char* string1Bytes = arg1) fixed (char* string2Bytes = arg2) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; descrs[0].DataPointer = (IntPtr)string1Bytes; descrs[0].Size = ((arg1.Length + 1) * 2); descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)string2Bytes; descrs[1].Size = ((arg2.Length + 1) * 2); descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, string? arg1, string? arg2, string? arg3) { if (IsEnabled()) { arg1 ??= ""; arg2 ??= ""; arg3 ??= ""; fixed (char* string1Bytes = arg1) fixed (char* string2Bytes = arg2) fixed (char* string3Bytes = arg3) { EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; descrs[0].DataPointer = (IntPtr)string1Bytes; descrs[0].Size = ((arg1.Length + 1) * 2); descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)string2Bytes; descrs[1].Size = ((arg2.Length + 1) * 2); descrs[1].Reserved = 0; descrs[2].DataPointer = (IntPtr)string3Bytes; descrs[2].Size = ((arg3.Length + 1) * 2); descrs[2].Reserved = 0; WriteEventCore(eventId, 3, descrs); } } } // optimized for common signatures (string and ints) #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, string? arg1, int arg2) { if (IsEnabled()) { arg1 ??= ""; fixed (char* string1Bytes = arg1) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; descrs[0].DataPointer = (IntPtr)string1Bytes; descrs[0].Size = ((arg1.Length + 1) * 2); descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 4; descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, string? arg1, int arg2, int arg3) { if (IsEnabled()) { arg1 ??= ""; fixed (char* string1Bytes = arg1) { EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; descrs[0].DataPointer = (IntPtr)string1Bytes; descrs[0].Size = ((arg1.Length + 1) * 2); descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 4; descrs[1].Reserved = 0; descrs[2].DataPointer = (IntPtr)(&arg3); descrs[2].Size = 4; descrs[2].Reserved = 0; WriteEventCore(eventId, 3, descrs); } } } // optimized for common signatures (string and longs) #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, string? arg1, long arg2) { if (IsEnabled()) { arg1 ??= ""; fixed (char* string1Bytes = arg1) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; descrs[0].DataPointer = (IntPtr)string1Bytes; descrs[0].Size = ((arg1.Length + 1) * 2); descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 8; descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } } } // optimized for common signatures (long and string) #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, long arg1, string? arg2) { if (IsEnabled()) { arg2 ??= ""; fixed (char* string2Bytes = arg2) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)string2Bytes; descrs[1].Size = ((arg2.Length + 1) * 2); descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } } } // optimized for common signatures (int and string) #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, int arg1, string? arg2) { if (IsEnabled()) { arg2 ??= ""; fixed (char* string2Bytes = arg2) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 4; descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)string2Bytes; descrs[1].Size = ((arg2.Length + 1) * 2); descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, byte[]? arg1) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; if (arg1 == null || arg1.Length == 0) { int blobSize = 0; descrs[0].DataPointer = (IntPtr)(&blobSize); descrs[0].Size = 4; descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)(&blobSize); // valid address instead of empty content descrs[1].Size = 0; descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } else { int blobSize = arg1.Length; fixed (byte* blob = &arg1[0]) { descrs[0].DataPointer = (IntPtr)(&blobSize); descrs[0].Size = 4; descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)blob; descrs[1].Size = blobSize; descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } } } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, long arg1, byte[]? arg2) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[0].Reserved = 0; if (arg2 == null || arg2.Length == 0) { int blobSize = 0; descrs[1].DataPointer = (IntPtr)(&blobSize); descrs[1].Size = 4; descrs[1].Reserved = 0; descrs[2].DataPointer = (IntPtr)(&blobSize); // valid address instead of empty contents descrs[2].Size = 0; descrs[2].Reserved = 0; WriteEventCore(eventId, 3, descrs); } else { int blobSize = arg2.Length; fixed (byte* blob = &arg2[0]) { descrs[1].DataPointer = (IntPtr)(&blobSize); descrs[1].Size = 4; descrs[1].Reserved = 0; descrs[2].DataPointer = (IntPtr)blob; descrs[2].Size = blobSize; descrs[2].Reserved = 0; WriteEventCore(eventId, 3, descrs); } } } } #pragma warning restore 1591 /// <summary> /// Used to construct the data structure to be passed to the native ETW APIs - EventWrite and EventWriteTransfer. /// </summary> protected internal struct EventData { /// <summary> /// Address where the one argument lives (if this points to managed memory you must ensure the /// managed object is pinned. /// </summary> public unsafe IntPtr DataPointer { get => (IntPtr)(void*)m_Ptr; set => m_Ptr = unchecked((ulong)(void*)value); } /// <summary> /// Size of the argument referenced by DataPointer /// </summary> public int Size { get => m_Size; set => m_Size = value; } /// <summary> /// Reserved by ETW. This property is present to ensure that we can zero it /// since System.Private.CoreLib uses are not zero'd. /// </summary> internal int Reserved { get => m_Reserved; set => m_Reserved = value; } #region private /// <summary> /// Initializes the members of this EventData object to point at a previously-pinned /// tracelogging-compatible metadata blob. /// </summary> /// <param name="pointer">Pinned tracelogging-compatible metadata blob.</param> /// <param name="size">The size of the metadata blob.</param> /// <param name="reserved">Value for reserved: 2 for per-provider metadata, 1 for per-event metadata</param> internal unsafe void SetMetadata(byte* pointer, int size, int reserved) { this.m_Ptr = (ulong)pointer; this.m_Size = size; this.m_Reserved = reserved; // Mark this descriptor as containing tracelogging-compatible metadata. } // Important, we pass this structure directly to the Win32 EventWrite API, so this structure must // be layed out exactly the way EventWrite wants it. internal ulong m_Ptr; internal int m_Size; #pragma warning disable 0649 internal int m_Reserved; // Used to pad the size to match the Win32 API #pragma warning restore 0649 #endregion } /// <summary> /// This routine allows you to create efficient WriteEvent helpers, however the code that you use to /// do this, while straightforward, is unsafe. /// </summary> /// <remarks> /// <code> /// protected unsafe void WriteEvent(int eventId, string arg1, long arg2) /// { /// if (IsEnabled()) /// { /// arg2 ??= ""; /// fixed (char* string2Bytes = arg2) /// { /// EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; /// descrs[0].DataPointer = (IntPtr)(&amp;arg1); /// descrs[0].Size = 8; /// descrs[0].Reserved = 0; /// descrs[1].DataPointer = (IntPtr)string2Bytes; /// descrs[1].Size = ((arg2.Length + 1) * 2); /// descrs[1].Reserved = 0; /// WriteEventCore(eventId, 2, descrs); /// } /// } /// } /// </code> /// </remarks> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "requires unreferenced code, but EnsureDescriptorsInitialized does not access this member and is safe to call.")] [RequiresUnreferencedCode(EventSourceRequiresUnreferenceMessage)] #endif [CLSCompliant(false)] protected unsafe void WriteEventCore(int eventId, int eventDataCount, EventSource.EventData* data) { WriteEventWithRelatedActivityIdCore(eventId, null, eventDataCount, data); } /// <summary> /// This routine allows you to create efficient WriteEventWithRelatedActivityId helpers, however the code /// that you use to do this, while straightforward, is unsafe. The only difference from /// <see cref="WriteEventCore"/> is that you pass the relatedActivityId from caller through to this API /// </summary> /// <remarks> /// <code> /// protected unsafe void WriteEventWithRelatedActivityId(int eventId, Guid relatedActivityId, string arg1, long arg2) /// { /// if (IsEnabled()) /// { /// arg2 ??= ""; /// fixed (char* string2Bytes = arg2) /// { /// EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; /// descrs[0].DataPointer = (IntPtr)(&amp;arg1); /// descrs[0].Size = 8; /// descrs[1].DataPointer = (IntPtr)string2Bytes; /// descrs[1].Size = ((arg2.Length + 1) * 2); /// WriteEventWithRelatedActivityIdCore(eventId, relatedActivityId, 2, descrs); /// } /// } /// } /// </code> /// </remarks> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "requires unreferenced code, but EnsureDescriptorsInitialized does not access this member and is safe to call.")] [RequiresUnreferencedCode(EventSourceRequiresUnreferenceMessage)] #endif [CLSCompliant(false)] protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, Guid* relatedActivityId, int eventDataCount, EventSource.EventData* data) { if (IsEnabled()) { Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source. try { ref EventMetadata metadata = ref m_eventData[eventId]; EventOpcode opcode = (EventOpcode)metadata.Descriptor.Opcode; Guid* pActivityId = null; Guid activityId = Guid.Empty; Guid relActivityId = Guid.Empty; if (opcode != EventOpcode.Info && relatedActivityId == null && ((metadata.ActivityOptions & EventActivityOptions.Disable) == 0)) { if (opcode == EventOpcode.Start) { m_activityTracker.OnStart(m_name, metadata.Name, metadata.Descriptor.Task, ref activityId, ref relActivityId, metadata.ActivityOptions); } else if (opcode == EventOpcode.Stop) { m_activityTracker.OnStop(m_name, metadata.Name, metadata.Descriptor.Task, ref activityId); } if (activityId != Guid.Empty) pActivityId = &activityId; if (relActivityId != Guid.Empty) relatedActivityId = &relActivityId; } #if FEATURE_MANAGED_ETW if (!SelfDescribingEvents) { if (metadata.EnabledForETW && !m_etwProvider.WriteEvent(ref metadata.Descriptor, metadata.EventHandle, pActivityId, relatedActivityId, eventDataCount, (IntPtr)data)) ThrowEventSourceException(metadata.Name); #if FEATURE_PERFTRACING if (metadata.EnabledForEventPipe && !m_eventPipeProvider.WriteEvent(ref metadata.Descriptor, metadata.EventHandle, pActivityId, relatedActivityId, eventDataCount, (IntPtr)data)) ThrowEventSourceException(metadata.Name); #endif // FEATURE_PERFTRACING } else if (metadata.EnabledForETW #if FEATURE_PERFTRACING || metadata.EnabledForEventPipe #endif // FEATURE_PERFTRACING ) { EventSourceOptions opt = new EventSourceOptions { Keywords = (EventKeywords)metadata.Descriptor.Keywords, Level = (EventLevel)metadata.Descriptor.Level, Opcode = (EventOpcode)metadata.Descriptor.Opcode }; WriteMultiMerge(metadata.Name, ref opt, metadata.TraceLoggingEventTypes, pActivityId, relatedActivityId, data); } #endif // FEATURE_MANAGED_ETW if (m_Dispatchers != null && metadata.EnabledForAnyListener) { #if MONO && !TARGET_BROWSER // On Mono, managed events from NativeRuntimeEventSource are written using WriteEventCore which can be // written doubly because EventPipe tries to pump it back up to EventListener via NativeRuntimeEventSource.ProcessEvents. // So we need to prevent this from getting written directly to the Listeners. if (this.GetType() != typeof(NativeRuntimeEventSource)) #endif // MONO && !TARGET_BROWSER { var eventCallbackArgs = new EventWrittenEventArgs(this, eventId, pActivityId, relatedActivityId); WriteToAllListeners(eventCallbackArgs, eventDataCount, data); } } } catch (Exception ex) { if (ex is EventSourceException) throw; else ThrowEventSourceException(m_eventData[eventId].Name, ex); } } } // fallback varags helpers. /// <summary> /// This is the varargs helper for writing an event. It does create an array and box all the arguments so it is /// relatively inefficient and should only be used for relatively rare events (e.g. less than 100 / sec). If your /// rates are faster than that you should use <see cref="WriteEventCore"/> to create fast helpers for your particular /// method signature. Even if you use this for rare events, this call should be guarded by an <see cref="IsEnabled()"/> /// check so that the varargs call is not made when the EventSource is not active. /// </summary> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "requires unreferenced code, but EnsureDescriptorsInitialized does not access this member and is safe to call.")] [RequiresUnreferencedCode(EventSourceRequiresUnreferenceMessage)] #endif protected unsafe void WriteEvent(int eventId, params object?[] args) { WriteEventVarargs(eventId, null, args); } /// <summary> /// This is the varargs helper for writing an event which also specifies a related activity. It is completely analogous /// to corresponding WriteEvent (they share implementation). It does create an array and box all the arguments so it is /// relatively inefficient and should only be used for relatively rare events (e.g. less than 100 / sec). If your /// rates are faster than that you should use <see cref="WriteEventWithRelatedActivityIdCore"/> to create fast helpers for your /// particular method signature. Even if you use this for rare events, this call should be guarded by an <see cref="IsEnabled()"/> /// check so that the varargs call is not made when the EventSource is not active. /// </summary> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "requires unreferenced code, but EnsureDescriptorsInitialized does not access this member and is safe to call.")] [RequiresUnreferencedCode(EventSourceRequiresUnreferenceMessage)] #endif protected unsafe void WriteEventWithRelatedActivityId(int eventId, Guid relatedActivityId, params object?[] args) { WriteEventVarargs(eventId, &relatedActivityId, args); } #endregion #region IDisposable Members /// <summary> /// Disposes of an EventSource. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Disposes of an EventSource. /// </summary> /// <remarks> /// Called from Dispose() with disposing=true, and from the finalizer (~EventSource) with disposing=false. /// Guidelines: /// 1. We may be called more than once: do nothing after the first call. /// 2. Avoid throwing exceptions if disposing is false, i.e. if we're being finalized. /// </remarks> /// <param name="disposing">True if called from Dispose(), false if called from the finalizer.</param> protected virtual void Dispose(bool disposing) { if (!IsSupported) { return; } // Do not invoke Dispose under the lock as this can lead to a deadlock. // See https://github.com/dotnet/runtime/issues/48342 for details. Debug.Assert(!Monitor.IsEntered(EventListener.EventListenersLock)); if (disposing) { #if FEATURE_MANAGED_ETW // Send the manifest one more time to ensure circular buffers have a chance to get to this information // even in scenarios with a high volume of ETW events. if (m_eventSourceEnabled) { try { SendManifest(m_rawManifest); } catch { } // If it fails, simply give up. m_eventSourceEnabled = false; } if (m_etwProvider != null) { m_etwProvider.Dispose(); m_etwProvider = null!; } #endif #if FEATURE_PERFTRACING if (m_eventPipeProvider != null) { m_eventPipeProvider.Dispose(); m_eventPipeProvider = null!; } #endif } m_eventSourceEnabled = false; m_eventSourceDisposed = true; } /// <summary> /// Finalizer for EventSource /// </summary> ~EventSource() { this.Dispose(false); } #endregion #region private private unsafe void WriteEventRaw( string? eventName, ref EventDescriptor eventDescriptor, IntPtr eventHandle, Guid* activityID, Guid* relatedActivityID, int dataCount, IntPtr data) { #if FEATURE_MANAGED_ETW || FEATURE_PERFTRACING bool allAreNull = true; #if FEATURE_MANAGED_ETW allAreNull &= (m_etwProvider == null); if (m_etwProvider != null && !m_etwProvider.WriteEventRaw(ref eventDescriptor, eventHandle, activityID, relatedActivityID, dataCount, data)) { ThrowEventSourceException(eventName); } #endif // FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING allAreNull &= (m_eventPipeProvider == null); if (m_eventPipeProvider != null && !m_eventPipeProvider.WriteEventRaw(ref eventDescriptor, eventHandle, activityID, relatedActivityID, dataCount, data)) { ThrowEventSourceException(eventName); } #endif // FEATURE_PERFTRACING if (allAreNull) { ThrowEventSourceException(eventName); } #endif // FEATURE_MANAGED_ETW || FEATURE_PERFTRACING } // FrameworkEventSource is on the startup path for the framework, so we have this internal overload that it can use // to prevent the working set hit from looking at the custom attributes on the type to get the Guid. internal EventSource(Guid eventSourceGuid, string eventSourceName) : this(eventSourceGuid, eventSourceName, EventSourceSettings.EtwManifestEventFormat) { } // Used by the internal FrameworkEventSource constructor and the TraceLogging-style event source constructor internal EventSource(Guid eventSourceGuid, string eventSourceName, EventSourceSettings settings, string[]? traits = null) { if (IsSupported) { #if FEATURE_PERFTRACING m_eventHandleTable = new TraceLoggingEventHandleTable(); #endif m_config = ValidateSettings(settings); Initialize(eventSourceGuid, eventSourceName, traits); } } /// <summary> /// This method is responsible for the common initialization path from our constructors. It must /// not leak any exceptions (otherwise, since most EventSource classes define a static member, /// "Log", such an exception would become a cached exception for the initialization of the static /// member, and any future access to the "Log" would throw the cached exception). /// </summary> private unsafe void Initialize(Guid eventSourceGuid, string eventSourceName, string[]? traits) { try { m_traits = traits; if (m_traits != null && m_traits.Length % 2 != 0) { throw new ArgumentException(SR.EventSource_TraitEven, nameof(traits)); } if (eventSourceGuid == Guid.Empty) { throw new ArgumentException(SR.EventSource_NeedGuid); } if (eventSourceName == null) { throw new ArgumentException(SR.EventSource_NeedName); } m_name = eventSourceName; m_guid = eventSourceGuid; // Enable Implicit Activity tracker m_activityTracker = ActivityTracker.Instance; #if FEATURE_MANAGED_ETW || FEATURE_PERFTRACING #if !DEBUG if (ProviderMetadata.Length == 0) #endif { // Create and register our provider traits. We do this early because it is needed to log errors // In the self-describing event case. InitializeProviderMetadata(); } #endif #if FEATURE_MANAGED_ETW // Register the provider with ETW var etwProvider = new OverrideEventProvider(this, EventProviderType.ETW); etwProvider.Register(this); #endif #if FEATURE_PERFTRACING // Register the provider with EventPipe var eventPipeProvider = new OverrideEventProvider(this, EventProviderType.EventPipe); lock (EventListener.EventListenersLock) { eventPipeProvider.Register(this); } #endif // Add the eventSource to the global (weak) list. // This also sets m_id, which is the index in the list. EventListener.AddEventSource(this); #if FEATURE_MANAGED_ETW // OK if we get this far without an exception, then we can at least write out error messages. // Set m_provider, which allows this. m_etwProvider = etwProvider; #if TARGET_WINDOWS #if (!ES_BUILD_STANDALONE) // API available on OS >= Win 8 and patched Win 7. // Disable only for FrameworkEventSource to avoid recursion inside exception handling. if (this.Name != "System.Diagnostics.Eventing.FrameworkEventSource" || Environment.IsWindows8OrAbove) #endif { var providerMetadata = ProviderMetadata; fixed (byte* pMetadata = providerMetadata) { m_etwProvider.SetInformation( Interop.Advapi32.EVENT_INFO_CLASS.SetTraits, pMetadata, (uint)providerMetadata.Length); } } #endif // TARGET_WINDOWS #endif // FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING m_eventPipeProvider = eventPipeProvider; #endif Debug.Assert(!m_eventSourceEnabled); // We can't be enabled until we are completely initted. // We are logically completely initialized at this point. m_completelyInited = true; } catch (Exception e) { m_constructionException ??= e; ReportOutOfBandMessage("ERROR: Exception during construction of EventSource " + Name + ": " + e.Message); } // Once m_completelyInited is set, you can have concurrency, so all work is under the lock. lock (EventListener.EventListenersLock) { // If there are any deferred commands, we can do them now. // This is the most likely place for exceptions to happen. // Note that we are NOT resetting m_deferredCommands to NULL here, // We are giving for EventHandler<EventCommandEventArgs> that will be attached later EventCommandEventArgs? deferredCommands = m_deferredCommands; while (deferredCommands != null) { DoCommand(deferredCommands); // This can never throw, it catches them and reports the errors. deferredCommands = deferredCommands.nextCommand; } } } private static string GetName(Type eventSourceType, EventManifestOptions flags) { if (eventSourceType == null) throw new ArgumentNullException(nameof(eventSourceType)); EventSourceAttribute? attrib = (EventSourceAttribute?)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute), flags); if (attrib != null && attrib.Name != null) return attrib.Name; return eventSourceType.Name; } private static Guid GenerateGuidFromName(string name) { #if ES_BUILD_STANDALONE if (namespaceBytes == null) { namespaceBytes = new byte[] { 0x48, 0x2C, 0x2D, 0xB2, 0xC3, 0x90, 0x47, 0xC8, 0x87, 0xF8, 0x1A, 0x15, 0xBF, 0xC1, 0x30, 0xFB, }; } #else ReadOnlySpan<byte> namespaceBytes = new byte[] // rely on C# compiler optimization to remove byte[] allocation { 0x48, 0x2C, 0x2D, 0xB2, 0xC3, 0x90, 0x47, 0xC8, 0x87, 0xF8, 0x1A, 0x15, 0xBF, 0xC1, 0x30, 0xFB, }; #endif byte[] bytes = Encoding.BigEndianUnicode.GetBytes(name); Sha1ForNonSecretPurposes hash = default; hash.Start(); hash.Append(namespaceBytes); hash.Append(bytes); Array.Resize(ref bytes, 16); hash.Finish(bytes); bytes[7] = unchecked((byte)((bytes[7] & 0x0F) | 0x50)); // Set high 4 bits of octet 7 to 5, as per RFC 4122 return new Guid(bytes); } private static unsafe void DecodeObjects(object?[] decodedObjects, Type[] parameterTypes, EventData* data) { for (int i = 0; i < decodedObjects.Length; i++, data++) { IntPtr dataPointer = data->DataPointer; Type dataType = parameterTypes[i]; object? decoded; if (dataType == typeof(string)) { goto String; } else if (dataType == typeof(int)) { Debug.Assert(data->Size == 4); decoded = *(int*)dataPointer; } else { TypeCode typeCode = Type.GetTypeCode(dataType); int size = data->Size; if (size == 4) { if ((uint)(typeCode - TypeCode.SByte) <= TypeCode.Int32 - TypeCode.SByte) { Debug.Assert(dataType.IsEnum); // Enums less than 4 bytes in size should be treated as int. decoded = *(int*)dataPointer; } else if (typeCode == TypeCode.UInt32) { decoded = *(uint*)dataPointer; } else if (typeCode == TypeCode.Single) { decoded = *(float*)dataPointer; } else if (typeCode == TypeCode.Boolean) { // The manifest defines a bool as a 32bit type (WIN32 BOOL), not 1 bit as CLR Does. decoded = *(int*)dataPointer == 1; } else if (dataType == typeof(byte[])) { // byte[] are written to EventData* as an int followed by a blob Debug.Assert(*(int*)dataPointer == (data + 1)->Size); data++; goto BytePtr; } else if (IntPtr.Size == 4 && dataType == typeof(IntPtr)) { decoded = *(IntPtr*)dataPointer; } else { goto Unknown; } } else if (size <= 2) { Debug.Assert(!dataType.IsEnum); if (typeCode == TypeCode.Byte) { Debug.Assert(size == 1); decoded = *(byte*)dataPointer; } else if (typeCode == TypeCode.SByte) { Debug.Assert(size == 1); decoded = *(sbyte*)dataPointer; } else if (typeCode == TypeCode.Int16) { Debug.Assert(size == 2); decoded = *(short*)dataPointer; } else if (typeCode == TypeCode.UInt16) { Debug.Assert(size == 2); decoded = *(ushort*)dataPointer; } else if (typeCode == TypeCode.Char) { Debug.Assert(size == 2); decoded = *(char*)dataPointer; } else { goto Unknown; } } else if (size == 8) { if (typeCode == TypeCode.Int64) { decoded = *(long*)dataPointer; } else if (typeCode == TypeCode.UInt64) { decoded = *(ulong*)dataPointer; } else if (typeCode == TypeCode.Double) { decoded = *(double*)dataPointer; } else if (typeCode == TypeCode.DateTime) { decoded = *(DateTime*)dataPointer; } else if (IntPtr.Size == 8 && dataType == typeof(IntPtr)) { decoded = *(IntPtr*)dataPointer; } else { goto Unknown; } } else if (typeCode == TypeCode.Decimal) { Debug.Assert(size == 16); decoded = *(decimal*)dataPointer; } else if (dataType == typeof(Guid)) { Debug.Assert(size == 16); decoded = *(Guid*)dataPointer; } else { goto Unknown; } } goto Store; Unknown: if (dataType != typeof(byte*)) { // Everything else is marshaled as a string. goto String; } BytePtr: if (data->Size == 0) { decoded = Array.Empty<byte>(); } else { var blob = new byte[data->Size]; Marshal.Copy(data->DataPointer, blob, 0, blob.Length); decoded = blob; } goto Store; String: // ETW strings are NULL-terminated, so marshal everything up to the first null in the string. AssertValidString(data); decoded = dataPointer == IntPtr.Zero ? null : new string((char*)dataPointer, 0, (data->Size >> 1) - 1); Store: decodedObjects[i] = decoded; } } [Conditional("DEBUG")] private static unsafe void AssertValidString(EventData* data) { Debug.Assert(data->Size >= 0 && data->Size % 2 == 0, "String size should be even"); char* charPointer = (char*)data->DataPointer; int charLength = data->Size / 2 - 1; for (int i = 0; i < charLength; i++) { Debug.Assert(*(charPointer + i) != 0, "String may not contain null chars"); } Debug.Assert(*(charPointer + charLength) == 0, "String must be null terminated"); } // Finds the Dispatcher (which holds the filtering state), for a given dispatcher for the current // eventSource). private EventDispatcher? GetDispatcher(EventListener? listener) { EventDispatcher? dispatcher = m_Dispatchers; while (dispatcher != null) { if (dispatcher.m_Listener == listener) return dispatcher; dispatcher = dispatcher.m_Next; } return dispatcher; } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "requires unreferenced code, but EnsureDescriptorsInitialized does not access this member and is safe to call.")] [RequiresUnreferencedCode(EventSourceRequiresUnreferenceMessage)] #endif private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object?[] args) { if (IsEnabled()) { Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source. try { ref EventMetadata metadata = ref m_eventData[eventId]; if (childActivityID != null) { // If you use WriteEventWithRelatedActivityID you MUST declare the first argument to be a GUID // with the name 'relatedActivityID, and NOT pass this argument to the WriteEvent method. // During manifest creation we modify the ParameterInfo[] that we store to strip out any // first parameter that is of type Guid and named "relatedActivityId." Thus, if you call // WriteEventWithRelatedActivityID from a method that doesn't name its first parameter correctly // we can end up in a state where the ParameterInfo[] doesn't have its first parameter stripped, // and this leads to a mismatch between the number of arguments and the number of ParameterInfos, // which would cause a cryptic IndexOutOfRangeException later if we don't catch it here. if (!metadata.HasRelatedActivityID) { throw new ArgumentException(SR.EventSource_NoRelatedActivityId); } } LogEventArgsMismatches(eventId, args); Guid* pActivityId = null; Guid activityId = Guid.Empty; Guid relatedActivityId = Guid.Empty; EventOpcode opcode = (EventOpcode)metadata.Descriptor.Opcode; EventActivityOptions activityOptions = metadata.ActivityOptions; if (childActivityID == null && ((activityOptions & EventActivityOptions.Disable) == 0)) { if (opcode == EventOpcode.Start) { m_activityTracker.OnStart(m_name, metadata.Name, metadata.Descriptor.Task, ref activityId, ref relatedActivityId, metadata.ActivityOptions); } else if (opcode == EventOpcode.Stop) { m_activityTracker.OnStop(m_name, metadata.Name, metadata.Descriptor.Task, ref activityId); } if (activityId != Guid.Empty) pActivityId = &activityId; if (relatedActivityId != Guid.Empty) childActivityID = &relatedActivityId; } #if FEATURE_MANAGED_ETW if (metadata.EnabledForETW #if FEATURE_PERFTRACING || metadata.EnabledForEventPipe #endif // FEATURE_PERFTRACING ) { if (!SelfDescribingEvents) { if (!m_etwProvider.WriteEvent(ref metadata.Descriptor, metadata.EventHandle, pActivityId, childActivityID, args)) ThrowEventSourceException(metadata.Name); #if FEATURE_PERFTRACING if (!m_eventPipeProvider.WriteEvent(ref metadata.Descriptor, metadata.EventHandle, pActivityId, childActivityID, args)) ThrowEventSourceException(metadata.Name); #endif // FEATURE_PERFTRACING } else { // TODO: activity ID support EventSourceOptions opt = new EventSourceOptions { Keywords = (EventKeywords)metadata.Descriptor.Keywords, Level = (EventLevel)metadata.Descriptor.Level, Opcode = (EventOpcode)metadata.Descriptor.Opcode }; WriteMultiMerge(metadata.Name, ref opt, metadata.TraceLoggingEventTypes, pActivityId, childActivityID, args); } } #endif // FEATURE_MANAGED_ETW if (m_Dispatchers != null && metadata.EnabledForAnyListener) { #if !ES_BUILD_STANDALONE // Maintain old behavior - object identity is preserved if (!LocalAppContextSwitches.PreserveEventListnerObjectIdentity) #endif // !ES_BUILD_STANDALONE { args = SerializeEventArgs(eventId, args); } var eventCallbackArgs = new EventWrittenEventArgs(this, eventId, pActivityId, childActivityID) { Payload = new ReadOnlyCollection<object?>(args) }; DispatchToAllListeners(eventCallbackArgs); } } catch (Exception ex) { if (ex is EventSourceException) throw; else ThrowEventSourceException(m_eventData[eventId].Name, ex); } } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "requires unreferenced code, but EnsureDescriptorsInitialized does not access this member and is safe to call.")] [RequiresUnreferencedCode(EventSourceRequiresUnreferenceMessage)] #endif private unsafe object?[] SerializeEventArgs(int eventId, object?[] args) { Debug.Assert(m_eventData != null); TraceLoggingEventTypes eventTypes = m_eventData[eventId].TraceLoggingEventTypes; int paramCount = Math.Min(eventTypes.typeInfos.Length, args.Length); // parameter count mismatch get logged in LogEventArgsMismatches var eventData = new object?[eventTypes.typeInfos.Length]; for (int i = 0; i < paramCount; i++) { eventData[i] = eventTypes.typeInfos[i].GetData(args[i]); } return eventData; } /// <summary> /// We expect that the arguments to the Event method and the arguments to WriteEvent match. This function /// checks that they in fact match and logs a warning to the debugger if they don't. /// </summary> /// <param name="eventId"></param> /// <param name="args"></param> private void LogEventArgsMismatches(int eventId, object?[] args) { Debug.Assert(m_eventData != null); ParameterInfo[] infos = m_eventData[eventId].Parameters; if (args.Length != infos.Length) { ReportOutOfBandMessage(SR.Format(SR.EventSource_EventParametersMismatch, eventId, args.Length, infos.Length)); return; } for (int i = 0; i < args.Length; i++) { Type pType = infos[i].ParameterType; object? arg = args[i]; // Checking to see if the Parameter types (from the Event method) match the supplied argument types. // Fail if one of two things hold : either the argument type is not equal or assignable to the parameter type, or the // argument is null and the parameter type is a non-Nullable<T> value type. if ((arg != null && !pType.IsAssignableFrom(arg.GetType())) || (arg == null && (pType.IsValueType && !(pType.IsGenericType && pType.GetGenericTypeDefinition() == typeof(Nullable<>)))) ) { ReportOutOfBandMessage(SR.Format(SR.EventSource_VarArgsParameterMismatch, eventId, infos[i].Name)); return; } } } private unsafe void WriteToAllListeners(EventWrittenEventArgs eventCallbackArgs, int eventDataCount, EventData* data) { Debug.Assert(m_eventData != null); ref EventMetadata metadata = ref m_eventData[eventCallbackArgs.EventId]; if (eventDataCount != metadata.EventListenerParameterCount) { ReportOutOfBandMessage(SR.Format(SR.EventSource_EventParametersMismatch, eventCallbackArgs.EventId, eventDataCount, metadata.Parameters.Length)); } object?[] args; if (eventDataCount == 0) { eventCallbackArgs.Payload = EventWrittenEventArgs.EmptyPayload; } else { args = new object?[Math.Min(eventDataCount, metadata.Parameters.Length)]; if (metadata.AllParametersAreString) { for (int i = 0; i < args.Length; i++, data++) { AssertValidString(data); IntPtr dataPointer = data->DataPointer; args[i] = dataPointer == IntPtr.Zero ? null : new string((char*)dataPointer, 0, (data->Size >> 1) - 1); } } else if (metadata.AllParametersAreInt32) { for (int i = 0; i < args.Length; i++, data++) { Debug.Assert(data->Size == 4); args[i] = *(int*)data->DataPointer; } } else { DecodeObjects(args, metadata.ParameterTypes, data); } eventCallbackArgs.Payload = new ReadOnlyCollection<object?>(args); } DispatchToAllListeners(eventCallbackArgs); } internal unsafe void DispatchToAllListeners(EventWrittenEventArgs eventCallbackArgs) { int eventId = eventCallbackArgs.EventId; Exception? lastThrownException = null; for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) { Debug.Assert(dispatcher.m_EventEnabled != null); if (eventId == -1 || dispatcher.m_EventEnabled[eventId]) { { try { dispatcher.m_Listener.OnEventWritten(eventCallbackArgs); } catch (Exception e) { ReportOutOfBandMessage("ERROR: Exception during EventSource.OnEventWritten: " + e.Message); lastThrownException = e; } } } } if (lastThrownException != null && ThrowOnEventWriteErrors) { throw new EventSourceException(lastThrownException); } } // WriteEventString is used for logging an error message (or similar) to // ETW and EventPipe providers. It is not a general purpose API, it will // log the message with Level=LogAlways and Keywords=All to make sure whoever // is listening gets the message. private unsafe void WriteEventString(string msgString) { #if FEATURE_MANAGED_ETW || FEATURE_PERFTRACING bool allAreNull = true; #if FEATURE_MANAGED_ETW allAreNull &= (m_etwProvider == null); #endif // FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING allAreNull &= (m_eventPipeProvider == null); #endif // FEATURE_PERFTRACING if (allAreNull) { return; } EventLevel level = EventLevel.LogAlways; long keywords = -1; const string EventName = "EventSourceMessage"; if (SelfDescribingEvents) { EventSourceOptions opt = new EventSourceOptions { Keywords = (EventKeywords)unchecked(keywords), Level = level }; #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The call to TraceLoggingEventTypes with the below parameter values are trim safe")] #endif static TraceLoggingEventTypes GetTrimSafeTraceLoggingEventTypes() => new TraceLoggingEventTypes(EventName, EventTags.None, new Type[] { typeof(string) }); var tlet = GetTrimSafeTraceLoggingEventTypes(); WriteMultiMergeInner(EventName, ref opt, tlet, null, null, msgString); } else { // We want the name of the provider to show up so if we don't have a manifest we create // on that at least has the provider name (I don't define any events). if (m_rawManifest == null && m_outOfBandMessageCount == 1) { ManifestBuilder manifestBuilder = new ManifestBuilder(Name, Guid, Name, null, EventManifestOptions.None); manifestBuilder.StartEvent(EventName, new EventAttribute(0) { Level = level, Task = (EventTask)0xFFFE }); manifestBuilder.AddEventParameter(typeof(string), "message"); manifestBuilder.EndEvent(); SendManifest(manifestBuilder.CreateManifest()); } // We use this low level routine to bypass the enabled checking, since the eventSource itself is only partially inited. fixed (char* msgStringPtr = msgString) { EventDescriptor descr = new EventDescriptor(0, 0, 0, (byte)level, 0, 0, keywords); EventProvider.EventData data = default; data.Ptr = (ulong)msgStringPtr; data.Size = (uint)(2 * (msgString.Length + 1)); data.Reserved = 0; #if FEATURE_MANAGED_ETW if (m_etwProvider != null) { m_etwProvider.WriteEvent(ref descr, IntPtr.Zero, null, null, 1, (IntPtr)((void*)&data)); } #endif // FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING if (m_eventPipeProvider != null) { if (m_writeEventStringEventHandle == IntPtr.Zero) { if (m_createEventLock is null) { Interlocked.CompareExchange(ref m_createEventLock, new object(), null); } lock (m_createEventLock) { if (m_writeEventStringEventHandle == IntPtr.Zero) { string eventName = "EventSourceMessage"; EventParameterInfo paramInfo = default(EventParameterInfo); paramInfo.SetInfo("message", typeof(string)); byte[]? metadata = EventPipeMetadataGenerator.Instance.GenerateMetadata(0, eventName, keywords, (uint)level, 0, EventOpcode.Info, new EventParameterInfo[] { paramInfo }); uint metadataLength = (metadata != null) ? (uint)metadata.Length : 0; fixed (byte* pMetadata = metadata) { m_writeEventStringEventHandle = m_eventPipeProvider.m_eventProvider.DefineEventHandle(0, eventName, keywords, 0, (uint)level, pMetadata, metadataLength); } } } } m_eventPipeProvider.WriteEvent(ref descr, m_writeEventStringEventHandle, null, null, 1, (IntPtr)((void*)&data)); } #endif // FEATURE_PERFTRACING } } #endif // FEATURE_MANAGED_ETW || FEATURE_PERFTRACING } /// <summary> /// Since this is a means of reporting errors (see ReportoutOfBandMessage) any failure encountered /// while writing the message to any one of the listeners will be silently ignored. /// </summary> private void WriteStringToAllListeners(string eventName, string msg) { var eventCallbackArgs = new EventWrittenEventArgs(this, 0) { EventName = eventName, Message = msg, Payload = new ReadOnlyCollection<object?>(new object[] { msg }), PayloadNames = new ReadOnlyCollection<string>(new string[] { "message" }) }; for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) { bool dispatcherEnabled = false; if (dispatcher.m_EventEnabled == null) { // if the listeners that weren't correctly initialized, we will send to it // since this is an error message and we want to see it go out. dispatcherEnabled = true; } else { // if there's *any* enabled event on the dispatcher we'll write out the string // otherwise we'll treat the listener as disabled and skip it for (int evtId = 0; evtId < dispatcher.m_EventEnabled.Length; ++evtId) { if (dispatcher.m_EventEnabled[evtId]) { dispatcherEnabled = true; break; } } } try { if (dispatcherEnabled) dispatcher.m_Listener.OnEventWritten(eventCallbackArgs); } catch { // ignore any exceptions thrown by listeners' OnEventWritten } } } /// <summary> /// Returns true if 'eventNum' is enabled if you only consider the level and matchAnyKeyword filters. /// It is possible that eventSources turn off the event based on additional filtering criteria. /// </summary> private bool IsEnabledByDefault(int eventNum, bool enable, EventLevel currentLevel, EventKeywords currentMatchAnyKeyword) { if (!enable) return false; Debug.Assert(m_eventData != null); EventLevel eventLevel = (EventLevel)m_eventData[eventNum].Descriptor.Level; EventKeywords eventKeywords = unchecked((EventKeywords)((ulong)m_eventData[eventNum].Descriptor.Keywords & (~(SessionMask.All.ToEventKeywords())))); #if FEATURE_MANAGED_ETW_CHANNELS EventChannel channel = unchecked((EventChannel)m_eventData[eventNum].Descriptor.Channel); #else EventChannel channel = EventChannel.None; #endif return IsEnabledCommon(enable, currentLevel, currentMatchAnyKeyword, eventLevel, eventKeywords, channel); } private bool IsEnabledCommon(bool enabled, EventLevel currentLevel, EventKeywords currentMatchAnyKeyword, EventLevel eventLevel, EventKeywords eventKeywords, EventChannel eventChannel) { if (!enabled) return false; // does is pass the level test? if ((currentLevel != 0) && (currentLevel < eventLevel)) return false; // if yes, does it pass the keywords test? if (currentMatchAnyKeyword != 0 && eventKeywords != 0) { #if FEATURE_MANAGED_ETW_CHANNELS // is there a channel with keywords that match currentMatchAnyKeyword? if (eventChannel != EventChannel.None && this.m_channelData != null && this.m_channelData.Length > (int)eventChannel) { EventKeywords channel_keywords = unchecked((EventKeywords)(m_channelData[(int)eventChannel] | (ulong)eventKeywords)); if (channel_keywords != 0 && (channel_keywords & currentMatchAnyKeyword) == 0) return false; } else #endif { if ((unchecked((ulong)eventKeywords & (ulong)currentMatchAnyKeyword)) == 0) return false; } } return true; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private void ThrowEventSourceException(string? eventName, Exception? innerEx = null) { // If we fail during out of band logging we may end up trying // to throw another EventSourceException, thus hitting a StackOverflowException. // Avoid StackOverflow by making sure we do not recursively call this method. if (m_EventSourceExceptionRecurenceCount > 0) return; try { m_EventSourceExceptionRecurenceCount++; string errorPrefix = "EventSourceException"; if (eventName != null) { errorPrefix += " while processing event \"" + eventName + "\""; } // TODO Create variations of EventSourceException that indicate more information using the error code. switch (EventProvider.GetLastWriteEventError()) { case EventProvider.WriteEventErrorCode.EventTooBig: ReportOutOfBandMessage(errorPrefix + ": " + SR.EventSource_EventTooBig); if (ThrowOnEventWriteErrors) throw new EventSourceException(SR.EventSource_EventTooBig, innerEx); break; case EventProvider.WriteEventErrorCode.NoFreeBuffers: ReportOutOfBandMessage(errorPrefix + ": " + SR.EventSource_NoFreeBuffers); if (ThrowOnEventWriteErrors) throw new EventSourceException(SR.EventSource_NoFreeBuffers, innerEx); break; case EventProvider.WriteEventErrorCode.NullInput: ReportOutOfBandMessage(errorPrefix + ": " + SR.EventSource_NullInput); if (ThrowOnEventWriteErrors) throw new EventSourceException(SR.EventSource_NullInput, innerEx); break; case EventProvider.WriteEventErrorCode.TooManyArgs: ReportOutOfBandMessage(errorPrefix + ": " + SR.EventSource_TooManyArgs); if (ThrowOnEventWriteErrors) throw new EventSourceException(SR.EventSource_TooManyArgs, innerEx); break; default: if (innerEx != null) { innerEx = innerEx.GetBaseException(); ReportOutOfBandMessage(errorPrefix + ": " + innerEx.GetType() + ":" + innerEx.Message); } else ReportOutOfBandMessage(errorPrefix); if (ThrowOnEventWriteErrors) throw new EventSourceException(innerEx); break; } } finally { m_EventSourceExceptionRecurenceCount--; } } internal static EventOpcode GetOpcodeWithDefault(EventOpcode opcode, string? eventName) { if (opcode == EventOpcode.Info && eventName != null) { if (eventName.EndsWith(s_ActivityStartSuffix, StringComparison.Ordinal)) { return EventOpcode.Start; } else if (eventName.EndsWith(s_ActivityStopSuffix, StringComparison.Ordinal)) { return EventOpcode.Stop; } } return opcode; } #if FEATURE_MANAGED_ETW /// <summary> /// This class lets us hook the 'OnEventCommand' from the eventSource. /// </summary> private sealed class OverrideEventProvider : EventProvider { public OverrideEventProvider(EventSource eventSource, EventProviderType providerType) : base(providerType) { this.m_eventSource = eventSource; this.m_eventProviderType = providerType; } protected override void OnControllerCommand(ControllerCommand command, IDictionary<string, string?>? arguments, int perEventSourceSessionId, int etwSessionId) { // We use null to represent the ETW EventListener. EventListener? listener = null; m_eventSource.SendCommand(listener, m_eventProviderType, perEventSourceSessionId, etwSessionId, (EventCommand)command, IsEnabled(), Level, MatchAnyKeyword, arguments); } private readonly EventSource m_eventSource; private readonly EventProviderType m_eventProviderType; } #endif /// <summary> /// Used to hold all the static information about an event. This includes everything in the event /// descriptor as well as some stuff we added specifically for EventSource. see the /// code:m_eventData for where we use this. /// </summary> internal partial struct EventMetadata { public EventDescriptor Descriptor; public IntPtr EventHandle; // EventPipeEvent handle. public EventTags Tags; public bool EnabledForAnyListener; // true if any dispatcher has this event turned on public bool EnabledForETW; // is this event on for ETW? #if FEATURE_PERFTRACING public bool EnabledForEventPipe; // is this event on for EventPipe? #endif public bool HasRelatedActivityID; // Set if the event method's first parameter is a Guid named 'relatedActivityId' public string Name; // the name of the event public string? Message; // If the event has a message associated with it, this is it. public ParameterInfo[] Parameters; // TODO can we remove? public int EventListenerParameterCount; public bool AllParametersAreString; public bool AllParametersAreInt32; public EventActivityOptions ActivityOptions; private TraceLoggingEventTypes _traceLoggingEventTypes; public TraceLoggingEventTypes TraceLoggingEventTypes { #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "requires unreferenced code, but EnsureDescriptorsInitialized does not access this member and is safe to call.")] [RequiresUnreferencedCode(EventSourceRequiresUnreferenceMessage)] #endif get { if (_traceLoggingEventTypes is null) { var tlet = new TraceLoggingEventTypes(Name, Tags, Parameters); Interlocked.CompareExchange(ref _traceLoggingEventTypes, tlet, null); } return _traceLoggingEventTypes; } } private ReadOnlyCollection<string>? _parameterNames; public ReadOnlyCollection<string> ParameterNames { get { if (_parameterNames is null) { ParameterInfo[] parameters = Parameters; var names = new string[parameters.Length]; for (int i = 0; i < names.Length; i++) { names[i] = parameters[i].Name!; } _parameterNames = new ReadOnlyCollection<string>(names); } return _parameterNames; } } private Type[]? _parameterTypes; public Type[] ParameterTypes { get { return _parameterTypes ??= GetParameterTypes(Parameters); static Type[] GetParameterTypes(ParameterInfo[] parameters) { var types = new Type[parameters.Length]; for (int i = 0; i < types.Length; i++) { types[i] = parameters[i].ParameterType; } return types; } } } } // This is the internal entry point that code:EventListeners call when wanting to send a command to a // eventSource. The logic is as follows // // * if Command == Update // * perEventSourceSessionId specifies the per-provider ETW session ID that the command applies // to (if listener != null) // perEventSourceSessionId = 0 - reserved for EventListeners // perEventSourceSessionId = 1..SessionMask.MAX - reserved for activity tracing aware ETW sessions // perEventSourceSessionId-1 represents the bit in the reserved field (bits 44..47) in // Keywords that identifies the session // perEventSourceSessionId = SessionMask.MAX+1 - reserved for legacy ETW sessions; these are // discriminated by etwSessionId // * etwSessionId specifies a machine-wide ETW session ID; this allows correlation of // activity tracing across different providers (which might have different sessionIds // for the same ETW session) // * enable, level, matchAnyKeywords are used to set a default for all events for the // eventSource. In particular, if 'enabled' is false, 'level' and // 'matchAnyKeywords' are not used. // * OnEventCommand is invoked, which may cause calls to // code:EventSource.EnableEventForDispatcher which may cause changes in the filtering // depending on the logic in that routine. // * else (command != Update) // * Simply call OnEventCommand. The expectation is that filtering is NOT changed. // * The 'enabled' 'level', matchAnyKeyword' arguments are ignored (must be true, 0, 0). // // dispatcher == null has special meaning. It is the 'ETW' dispatcher. internal void SendCommand(EventListener? listener, EventProviderType eventProviderType, int perEventSourceSessionId, int etwSessionId, EventCommand command, bool enable, EventLevel level, EventKeywords matchAnyKeyword, IDictionary<string, string?>? commandArguments) { if (!IsSupported) { return; } var commandArgs = new EventCommandEventArgs(command, commandArguments, this, listener, eventProviderType, perEventSourceSessionId, etwSessionId, enable, level, matchAnyKeyword); lock (EventListener.EventListenersLock) { if (m_completelyInited) { // After the first command arrive after construction, we are ready to get rid of the deferred commands this.m_deferredCommands = null; // We are fully initialized, do the command DoCommand(commandArgs); } else { // We can't do the command, simply remember it and we do it when we are fully constructed. if (m_deferredCommands == null) { m_deferredCommands = commandArgs; // create the first entry } else { // We have one or more entries, find the last one and add it to that. EventCommandEventArgs lastCommand = m_deferredCommands; while (lastCommand.nextCommand != null) lastCommand = lastCommand.nextCommand; lastCommand.nextCommand = commandArgs; } } } } /// <summary> /// We want the eventSource to be fully initialized when we do commands because that way we can send /// error messages and other logging directly to the event stream. Unfortunately we can get callbacks /// when we are not fully initialized. In that case we store them in 'commandArgs' and do them later. /// This helper actually does all actual command logic. /// </summary> internal void DoCommand(EventCommandEventArgs commandArgs) { if (!IsSupported) { return; } // PRECONDITION: We should be holding the EventListener.EventListenersLock // We defer commands until we are completely inited. This allows error messages to be sent. Debug.Assert(m_completelyInited); #if FEATURE_MANAGED_ETW if (m_etwProvider == null) // If we failed to construct return; #endif // FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING if (m_eventPipeProvider == null) return; #endif m_outOfBandMessageCount = 0; try { EnsureDescriptorsInitialized(); Debug.Assert(m_eventData != null); // Find the per-EventSource dispatcher corresponding to registered dispatcher commandArgs.dispatcher = GetDispatcher(commandArgs.listener); if (commandArgs.dispatcher == null && commandArgs.listener != null) // dispatcher == null means ETW dispatcher { throw new ArgumentException(SR.EventSource_ListenerNotFound); } commandArgs.Arguments ??= new Dictionary<string, string?>(); if (commandArgs.Command == EventCommand.Update) { // Set it up using the 'standard' filtering bitfields (use the "global" enable, not session specific one) for (int i = 0; i < m_eventData.Length; i++) EnableEventForDispatcher(commandArgs.dispatcher, commandArgs.eventProviderType, i, IsEnabledByDefault(i, commandArgs.enable, commandArgs.level, commandArgs.matchAnyKeyword)); if (commandArgs.enable) { if (!m_eventSourceEnabled) { // EventSource turned on for the first time, simply copy the bits. m_level = commandArgs.level; m_matchAnyKeyword = commandArgs.matchAnyKeyword; } else { // Already enabled, make it the most verbose of the existing and new filter if (commandArgs.level > m_level) m_level = commandArgs.level; if (commandArgs.matchAnyKeyword == 0) m_matchAnyKeyword = 0; else if (m_matchAnyKeyword != 0) m_matchAnyKeyword = unchecked(m_matchAnyKeyword | commandArgs.matchAnyKeyword); } } // interpret perEventSourceSessionId's sign, and adjust perEventSourceSessionId to // represent 0-based positive values bool bSessionEnable = (commandArgs.perEventSourceSessionId >= 0); if (commandArgs.perEventSourceSessionId == 0 && !commandArgs.enable) bSessionEnable = false; if (commandArgs.listener == null) { if (!bSessionEnable) commandArgs.perEventSourceSessionId = -commandArgs.perEventSourceSessionId; // for "global" enable/disable (passed in with listener == null and // perEventSourceSessionId == 0) perEventSourceSessionId becomes -1 --commandArgs.perEventSourceSessionId; } commandArgs.Command = bSessionEnable ? EventCommand.Enable : EventCommand.Disable; // perEventSourceSessionId = -1 when ETW sent a notification, but the set of active sessions // hasn't changed. // sesisonId = SessionMask.MAX when one of the legacy ETW sessions changed // 0 <= perEventSourceSessionId < SessionMask.MAX for activity-tracing aware sessions Debug.Assert(commandArgs.perEventSourceSessionId >= -1 && commandArgs.perEventSourceSessionId <= SessionMask.MAX); // Send the manifest if we are enabling an ETW session if (bSessionEnable && commandArgs.dispatcher == null) { // eventSourceDispatcher == null means this is the ETW manifest // Note that we unconditionally send the manifest whenever we are enabled, even if // we were already enabled. This is because there may be multiple sessions active // and we can't know that all the sessions have seen the manifest. if (!SelfDescribingEvents) SendManifest(m_rawManifest); } // Turn on the enable bit before making the OnEventCommand callback This allows you to do useful // things like log messages, or test if keywords are enabled in the callback. if (commandArgs.enable) { Debug.Assert(m_eventData != null); m_eventSourceEnabled = true; } this.OnEventCommand(commandArgs); this.m_eventCommandExecuted?.Invoke(this, commandArgs); if (!commandArgs.enable) { // If we are disabling, maybe we can turn on 'quick checks' to filter // quickly. These are all just optimizations (since later checks will still filter) // There is a good chance EnabledForAnyListener are not as accurate as // they could be, go ahead and get a better estimate. for (int i = 0; i < m_eventData.Length; i++) { bool isEnabledForAnyListener = false; for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) { Debug.Assert(dispatcher.m_EventEnabled != null); if (dispatcher.m_EventEnabled[i]) { isEnabledForAnyListener = true; break; } } m_eventData[i].EnabledForAnyListener = isEnabledForAnyListener; } // If no events are enabled, disable the global enabled bit. if (!AnyEventEnabled()) { m_level = 0; m_matchAnyKeyword = 0; m_eventSourceEnabled = false; } } } else { if (commandArgs.Command == EventCommand.SendManifest) { // TODO: should we generate the manifest here if we hadn't already? if (m_rawManifest != null) SendManifest(m_rawManifest); } // These are not used for non-update commands and thus should always be 'default' values // Debug.Assert(enable == true); // Debug.Assert(level == EventLevel.LogAlways); // Debug.Assert(matchAnyKeyword == EventKeywords.None); this.OnEventCommand(commandArgs); m_eventCommandExecuted?.Invoke(this, commandArgs); } } catch (Exception e) { // When the ETW session is created after the EventSource has registered with the ETW system // we can send any error messages here. ReportOutOfBandMessage("ERROR: Exception in Command Processing for EventSource " + Name + ": " + e.Message); // We never throw when doing a command. } } /// <summary> /// If 'value is 'true' then set the eventSource so that 'dispatcher' will receive event with the eventId /// of 'eventId. If value is 'false' disable the event for that dispatcher. If 'eventId' is out of /// range return false, otherwise true. /// </summary> internal bool EnableEventForDispatcher(EventDispatcher? dispatcher, EventProviderType eventProviderType, int eventId, bool value) { if (!IsSupported) return false; Debug.Assert(m_eventData != null); if (dispatcher == null) { if (eventId >= m_eventData.Length) return false; #if FEATURE_MANAGED_ETW if (m_etwProvider != null && eventProviderType == EventProviderType.ETW) m_eventData[eventId].EnabledForETW = value; #endif #if FEATURE_PERFTRACING if (m_eventPipeProvider != null && eventProviderType == EventProviderType.EventPipe) m_eventData[eventId].EnabledForEventPipe = value; #endif } else { Debug.Assert(dispatcher.m_EventEnabled != null); if (eventId >= dispatcher.m_EventEnabled.Length) return false; dispatcher.m_EventEnabled[eventId] = value; if (value) m_eventData[eventId].EnabledForAnyListener = true; } return true; } /// <summary> /// Returns true if any event at all is on. /// </summary> private bool AnyEventEnabled() { Debug.Assert(m_eventData != null); for (int i = 0; i < m_eventData.Length; i++) if (m_eventData[i].EnabledForETW || m_eventData[i].EnabledForAnyListener #if FEATURE_PERFTRACING || m_eventData[i].EnabledForEventPipe #endif // FEATURE_PERFTRACING ) return true; return false; } private bool IsDisposed => m_eventSourceDisposed; private void EnsureDescriptorsInitialized() { #if !ES_BUILD_STANDALONE Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif if (m_eventData == null) { // get the metadata via reflection. Debug.Assert(m_rawManifest == null); m_rawManifest = CreateManifestAndDescriptors(this.GetType(), Name, this); Debug.Assert(m_eventData != null); // TODO Enforce singleton pattern if (!AllowDuplicateSourceNames) { Debug.Assert(EventListener.s_EventSources != null, "should be called within lock on EventListener.EventListenersLock which ensures s_EventSources to be initialized"); foreach (WeakReference<EventSource> eventSourceRef in EventListener.s_EventSources) { if (eventSourceRef.TryGetTarget(out EventSource? eventSource) && eventSource.Guid == m_guid && !eventSource.IsDisposed) { if (eventSource != this) { throw new ArgumentException(SR.Format(SR.EventSource_EventSourceGuidInUse, m_guid)); } } } } // Make certain all dispatchers also have their arrays initialized EventDispatcher? dispatcher = m_Dispatchers; while (dispatcher != null) { dispatcher.m_EventEnabled ??= new bool[m_eventData.Length]; dispatcher = dispatcher.m_Next; } #if FEATURE_PERFTRACING // Initialize the EventPipe event handles. DefineEventPipeEvents(); #endif } } // Send out the ETW manifest XML out to ETW // Today, we only send the manifest to ETW, custom listeners don't get it. private unsafe void SendManifest(byte[]? rawManifest) { if (rawManifest == null) return; Debug.Assert(!SelfDescribingEvents); #if FEATURE_MANAGED_ETW fixed (byte* dataPtr = rawManifest) { // we don't want the manifest to show up in the event log channels so we specify as keywords // everything but the first 8 bits (reserved for the 8 channels) var manifestDescr = new EventDescriptor(0xFFFE, 1, 0, 0, 0xFE, 0xFFFE, 0x00ffFFFFffffFFFF); ManifestEnvelope envelope = default; envelope.Format = ManifestEnvelope.ManifestFormats.SimpleXmlFormat; envelope.MajorVersion = 1; envelope.MinorVersion = 0; envelope.Magic = 0x5B; // An unusual number that can be checked for consistency. int dataLeft = rawManifest.Length; envelope.ChunkNumber = 0; EventProvider.EventData* dataDescrs = stackalloc EventProvider.EventData[2]; dataDescrs[0].Ptr = (ulong)&envelope; dataDescrs[0].Size = (uint)sizeof(ManifestEnvelope); dataDescrs[0].Reserved = 0; dataDescrs[1].Ptr = (ulong)dataPtr; dataDescrs[1].Reserved = 0; int chunkSize = ManifestEnvelope.MaxChunkSize; TRY_AGAIN_WITH_SMALLER_CHUNK_SIZE: envelope.TotalChunks = (ushort)((dataLeft + (chunkSize - 1)) / chunkSize); while (dataLeft > 0) { dataDescrs[1].Size = (uint)Math.Min(dataLeft, chunkSize); if (m_etwProvider != null) { if (!m_etwProvider.WriteEvent(ref manifestDescr, IntPtr.Zero, null, null, 2, (IntPtr)dataDescrs)) { // Turns out that if users set the BufferSize to something less than 64K then WriteEvent // can fail. If we get this failure on the first chunk try again with something smaller // The smallest BufferSize is 1K so if we get to 256 (to account for envelope overhead), we can give up making it smaller. if (EventProvider.GetLastWriteEventError() == EventProvider.WriteEventErrorCode.EventTooBig) { if (envelope.ChunkNumber == 0 && chunkSize > 256) { chunkSize /= 2; goto TRY_AGAIN_WITH_SMALLER_CHUNK_SIZE; } } if (ThrowOnEventWriteErrors) ThrowEventSourceException("SendManifest"); break; } } dataLeft -= chunkSize; dataDescrs[1].Ptr += (uint)chunkSize; envelope.ChunkNumber++; // For large manifests we want to not overflow any receiver's buffer. Most manifests will fit within // 5 chunks, so only the largest manifests will hit the pause. if ((envelope.ChunkNumber % 5) == 0) { Thread.Sleep(15); } } } #endif // FEATURE_MANAGED_ETW } // Helper to deal with the fact that the type we are reflecting over might be loaded in the ReflectionOnly context. // When that is the case, we have to build the custom assemblies on a member by hand. internal static bool IsCustomAttributeDefinedHelper( MemberInfo member, Type attributeType, EventManifestOptions flags = EventManifestOptions.None) { // AllowEventSourceOverride is an option that allows either Microsoft.Diagnostics.Tracing or // System.Diagnostics.Tracing EventSource to be considered valid. This should not mattter anywhere but in Microsoft.Diagnostics.Tracing (nuget package). if (!member.Module.Assembly.ReflectionOnly && (flags & EventManifestOptions.AllowEventSourceOverride) == 0) { // Let the runtime do the work for us, since we can execute code in this context. return member.IsDefined(attributeType, inherit: false); } foreach (CustomAttributeData data in CustomAttributeData.GetCustomAttributes(member)) { if (AttributeTypeNamesMatch(attributeType, data.Constructor.ReflectedType!)) { return true; } } return false; } // Helper to deal with the fact that the type we are reflecting over might be loaded in the ReflectionOnly context. // When that is the case, we have the build the custom assemblies on a member by hand. #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2114:ReflectionToDynamicallyAccessedMembers", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "has dynamically accessed members requirements, but EnsureDescriptorsInitialized does not "+ "access this member and is safe to call.")] #endif internal static Attribute? GetCustomAttributeHelper( MemberInfo member, #if !ES_BUILD_STANDALONE [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicProperties)] #endif Type attributeType, EventManifestOptions flags = EventManifestOptions.None) { Debug.Assert(attributeType == typeof(EventAttribute) || attributeType == typeof(EventSourceAttribute)); // AllowEventSourceOverride is an option that allows either Microsoft.Diagnostics.Tracing or // System.Diagnostics.Tracing EventSource to be considered valid. This should not mattter anywhere but in Microsoft.Diagnostics.Tracing (nuget package). if (!member.Module.Assembly.ReflectionOnly && (flags & EventManifestOptions.AllowEventSourceOverride) == 0) { // Let the runtime do the work for us, since we can execute code in this context. return member.GetCustomAttribute(attributeType, inherit: false); } foreach (CustomAttributeData data in CustomAttributeData.GetCustomAttributes(member)) { if (AttributeTypeNamesMatch(attributeType, data.Constructor.ReflectedType!)) { Attribute? attr = null; Debug.Assert(data.ConstructorArguments.Count <= 1); if (data.ConstructorArguments.Count == 1) { attr = (Attribute?)Activator.CreateInstance(attributeType, new object?[] { data.ConstructorArguments[0].Value }); } else if (data.ConstructorArguments.Count == 0) { attr = (Attribute?)Activator.CreateInstance(attributeType); } if (attr != null) { foreach (CustomAttributeNamedArgument namedArgument in data.NamedArguments) { PropertyInfo p = attributeType.GetProperty(namedArgument.MemberInfo.Name, BindingFlags.Public | BindingFlags.Instance)!; object value = namedArgument.TypedValue.Value!; if (p.PropertyType.IsEnum) { string val = value.ToString()!; value = Enum.Parse(p.PropertyType, val); } p.SetValue(attr, value, null); } return attr; } } } return null; } /// <summary> /// Evaluates if two related "EventSource"-domain types should be considered the same /// </summary> /// <param name="attributeType">The attribute type in the load context - it's associated with the running /// EventSource type. This type may be different fromt he base type of the user-defined EventSource.</param> /// <param name="reflectedAttributeType">The attribute type in the reflection context - it's associated with /// the user-defined EventSource, and is in the same assembly as the eventSourceType passed to /// </param> /// <returns>True - if the types should be considered equivalent, False - otherwise</returns> private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAttributeType) { return // are these the same type? attributeType == reflectedAttributeType || // are the full typenames equal? string.Equals(attributeType.FullName, reflectedAttributeType.FullName, StringComparison.Ordinal) || // are the typenames equal and the namespaces under "Diagnostics.Tracing" (typically // either Microsoft.Diagnostics.Tracing or System.Diagnostics.Tracing)? string.Equals(attributeType.Name, reflectedAttributeType.Name, StringComparison.Ordinal) && attributeType.Namespace!.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal) && (reflectedAttributeType.Namespace!.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal) #if EVENT_SOURCE_LEGACY_NAMESPACE_SUPPORT || reflectedAttributeType.Namespace.EndsWith("Diagnostics.Eventing", StringComparison.Ordinal) #endif ); } private static Type? GetEventSourceBaseType(Type eventSourceType, bool allowEventSourceOverride, bool reflectionOnly) { Type? ret = eventSourceType; // return false for "object" and interfaces if (ret.BaseType == null) return null; // now go up the inheritance chain until hitting a concrete type ("object" at worse) do { ret = ret.BaseType; } while (ret != null && ret.IsAbstract); if (ret != null) { if (!allowEventSourceOverride) { if (reflectionOnly && ret.FullName != typeof(EventSource).FullName || !reflectionOnly && ret != typeof(EventSource)) return null; } else { if (ret.Name != "EventSource") return null; } } return ret; } // Use reflection to look at the attributes of a class, and generate a manifest for it (as UTF8) and // return the UTF8 bytes. It also sets up the code:EventData structures needed to dispatch events // at run time. 'source' is the event source to place the descriptors. If it is null, // then the descriptors are not created, and just the manifest is generated. #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2114:ReflectionToDynamicallyAccessedMembers", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "has dynamically accessed members requirements, but its use of this method satisfies " + "these requirements because it passes in the result of GetType with the same annotations.")] #endif private static byte[]? CreateManifestAndDescriptors( #if !ES_BUILD_STANDALONE [DynamicallyAccessedMembers(ManifestMemberTypes)] #endif Type eventSourceType, string? eventSourceDllName, EventSource? source, EventManifestOptions flags = EventManifestOptions.None) { ManifestBuilder? manifest = null; bool bNeedsManifest = source != null ? !source.SelfDescribingEvents : true; Exception? exception = null; // exception that might get raised during validation b/c we couldn't/didn't recover from a previous error byte[]? res = null; if (eventSourceType.IsAbstract && (flags & EventManifestOptions.Strict) == 0) return null; try { MethodInfo[] methods = eventSourceType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); EventAttribute defaultEventAttribute; int eventId = 1; // The number given to an event that does not have a explicitly given ID. EventMetadata[]? eventData = null; Dictionary<string, string>? eventsByName = null; if (source != null || (flags & EventManifestOptions.Strict) != 0) { eventData = new EventMetadata[methods.Length + 1]; eventData[0].Name = ""; // Event 0 is the 'write messages string' event, and has an empty name. } // See if we have localization information. ResourceManager? resources = null; EventSourceAttribute? eventSourceAttrib = (EventSourceAttribute?)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute), flags); if (eventSourceAttrib != null && eventSourceAttrib.LocalizationResources != null) resources = new ResourceManager(eventSourceAttrib.LocalizationResources, eventSourceType.Assembly); if (source is not null) { // We have the source so don't need to use reflection to get the Name and Guid manifest = new ManifestBuilder(source.Name, source.Guid, eventSourceDllName, resources, flags); } else { manifest = new ManifestBuilder(GetName(eventSourceType, flags), GetGuid(eventSourceType), eventSourceDllName, resources, flags); } // Add an entry unconditionally for event ID 0 which will be for a string message. manifest.StartEvent("EventSourceMessage", new EventAttribute(0) { Level = EventLevel.LogAlways, Task = (EventTask)0xFFFE }); manifest.AddEventParameter(typeof(string), "message"); manifest.EndEvent(); // eventSourceType must be sealed and must derive from this EventSource if ((flags & EventManifestOptions.Strict) != 0) { bool typeMatch = GetEventSourceBaseType(eventSourceType, (flags & EventManifestOptions.AllowEventSourceOverride) != 0, eventSourceType.Assembly.ReflectionOnly) != null; if (!typeMatch) { manifest.ManifestError(SR.EventSource_TypeMustDeriveFromEventSource); } if (!eventSourceType.IsAbstract && !eventSourceType.IsSealed) { manifest.ManifestError(SR.EventSource_TypeMustBeSealedOrAbstract); } } // Collect task, opcode, keyword and channel information #if FEATURE_MANAGED_ETW_CHANNELS && FEATURE_ADVANCED_MANAGED_ETW_CHANNELS foreach (var providerEnumKind in new string[] { "Keywords", "Tasks", "Opcodes", "Channels" }) #else foreach (string providerEnumKind in new string[] { "Keywords", "Tasks", "Opcodes" }) #endif { Type? nestedType = eventSourceType.GetNestedType(providerEnumKind); if (nestedType != null) { if (eventSourceType.IsAbstract) { manifest.ManifestError(SR.Format(SR.EventSource_AbstractMustNotDeclareKTOC, nestedType.Name)); } else { foreach (FieldInfo staticField in nestedType.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)) { AddProviderEnumKind(manifest, staticField, providerEnumKind); } } } } // ensure we have keywords for the session-filtering reserved bits { manifest.AddKeyword("Session3", (long)0x1000 << 32); manifest.AddKeyword("Session2", (long)0x2000 << 32); manifest.AddKeyword("Session1", (long)0x4000 << 32); manifest.AddKeyword("Session0", (long)0x8000 << 32); } if (eventSourceType != typeof(EventSource)) { for (int i = 0; i < methods.Length; i++) { MethodInfo method = methods[i]; ParameterInfo[] args = method.GetParameters(); // Get the EventDescriptor (from the Custom attributes) EventAttribute? eventAttribute = (EventAttribute?)GetCustomAttributeHelper(method, typeof(EventAttribute), flags); // Compat: until v4.5.1 we ignored any non-void returning methods as well as virtual methods for // the only reason of limiting the number of methods considered to be events. This broke a common // design of having event sources implement specific interfaces. To fix this in a compatible way // we will now allow both non-void returning and virtual methods to be Event methods, as long // as they are marked with the [Event] attribute if (/* method.IsVirtual || */ method.IsStatic) { continue; } if (eventSourceType.IsAbstract) { if (eventAttribute != null) { manifest.ManifestError(SR.Format(SR.EventSource_AbstractMustNotDeclareEventMethods, method.Name, eventAttribute.EventId)); } continue; } else if (eventAttribute == null) { // Methods that don't return void can't be events, if they're NOT marked with [Event]. // (see Compat comment above) if (method.ReturnType != typeof(void)) { continue; } // Continue to ignore virtual methods if they do NOT have the [Event] attribute // (see Compat comment above) if (method.IsVirtual) { continue; } // If we explicitly mark the method as not being an event, then honor that. if (IsCustomAttributeDefinedHelper(method, typeof(NonEventAttribute), flags)) continue; defaultEventAttribute = new EventAttribute(eventId); eventAttribute = defaultEventAttribute; } else if (eventAttribute.EventId <= 0) { manifest.ManifestError(SR.EventSource_NeedPositiveId, true); continue; // don't validate anything else for this event } if (method.Name.LastIndexOf('.') >= 0) { manifest.ManifestError(SR.Format(SR.EventSource_EventMustNotBeExplicitImplementation, method.Name, eventAttribute.EventId)); } eventId++; string eventName = method.Name; if (eventAttribute.Opcode == EventOpcode.Info) // We are still using the default opcode. { // By default pick a task ID derived from the EventID, starting with the highest task number and working back bool noTask = (eventAttribute.Task == EventTask.None); if (noTask) eventAttribute.Task = (EventTask)(0xFFFE - eventAttribute.EventId); // Unless we explicitly set the opcode to Info (to override the auto-generate of Start or Stop opcodes, // pick a default opcode based on the event name (either Info or start or stop if the name ends with that suffix). if (!eventAttribute.IsOpcodeSet) eventAttribute.Opcode = GetOpcodeWithDefault(EventOpcode.Info, eventName); // Make the stop opcode have the same task as the start opcode. if (noTask) { if (eventAttribute.Opcode == EventOpcode.Start) { string taskName = eventName.Substring(0, eventName.Length - s_ActivityStartSuffix.Length); // Remove the Stop suffix to get the task name if (string.Compare(eventName, 0, taskName, 0, taskName.Length) == 0 && string.Compare(eventName, taskName.Length, s_ActivityStartSuffix, 0, Math.Max(eventName.Length - taskName.Length, s_ActivityStartSuffix.Length)) == 0) { // Add a task that is just the task name for the start event. This suppress the auto-task generation // That would otherwise happen (and create 'TaskName'Start as task name rather than just 'TaskName' manifest.AddTask(taskName, (int)eventAttribute.Task); } } else if (eventAttribute.Opcode == EventOpcode.Stop) { // Find the start associated with this stop event. We require start to be immediately before the stop int startEventId = eventAttribute.EventId - 1; if (eventData != null && startEventId < eventData.Length) { Debug.Assert(0 <= startEventId); // Since we reserve id 0, we know that id-1 is <= 0 EventMetadata startEventMetadata = eventData[startEventId]; // If you remove the Stop and add a Start does that name match the Start Event's Name? // Ideally we would throw an error string taskName = eventName.Substring(0, eventName.Length - s_ActivityStopSuffix.Length); // Remove the Stop suffix to get the task name if (startEventMetadata.Descriptor.Opcode == (byte)EventOpcode.Start && string.Compare(startEventMetadata.Name, 0, taskName, 0, taskName.Length) == 0 && string.Compare(startEventMetadata.Name, taskName.Length, s_ActivityStartSuffix, 0, Math.Max(startEventMetadata.Name.Length - taskName.Length, s_ActivityStartSuffix.Length)) == 0) { // Make the stop event match the start event eventAttribute.Task = (EventTask)startEventMetadata.Descriptor.Task; noTask = false; } } if (noTask && (flags & EventManifestOptions.Strict) != 0) // Throw an error if we can compatibly. { throw new ArgumentException(SR.EventSource_StopsFollowStarts); } } } } bool hasRelatedActivityID = RemoveFirstArgIfRelatedActivityId(ref args); if (!(source != null && source.SelfDescribingEvents)) { manifest.StartEvent(eventName, eventAttribute); for (int fieldIdx = 0; fieldIdx < args.Length; fieldIdx++) { manifest.AddEventParameter(args[fieldIdx].ParameterType, args[fieldIdx].Name!); } manifest.EndEvent(); } if (source != null || (flags & EventManifestOptions.Strict) != 0) { Debug.Assert(eventData != null); // Do checking for user errors (optional, but not a big deal so we do it). DebugCheckEvent(ref eventsByName, eventData, method, eventAttribute, manifest, flags); #if FEATURE_MANAGED_ETW_CHANNELS // add the channel keyword for Event Viewer channel based filters. This is added for creating the EventDescriptors only // and is not required for the manifest if (eventAttribute.Channel != EventChannel.None) { unchecked { eventAttribute.Keywords |= (EventKeywords)manifest.GetChannelKeyword(eventAttribute.Channel, (ulong)eventAttribute.Keywords); } } #endif if (manifest.HasResources) { string eventKey = "event_" + eventName; if (manifest.GetLocalizedMessage(eventKey, CultureInfo.CurrentUICulture, etwFormat: false) is string msg) { // overwrite inline message with the localized message eventAttribute.Message = msg; } } AddEventDescriptor(ref eventData, eventName, eventAttribute, args, hasRelatedActivityID); } } } // Tell the TraceLogging stuff where to start allocating its own IDs. NameInfo.ReserveEventIDsBelow(eventId); if (source != null) { Debug.Assert(eventData != null); TrimEventDescriptors(ref eventData); source.m_eventData = eventData; // officially initialize it. We do this at most once (it is racy otherwise). #if FEATURE_MANAGED_ETW_CHANNELS source.m_channelData = manifest.GetChannelData(); #endif } // if this is an abstract event source we've already performed all the validation we can if (!eventSourceType.IsAbstract && (source == null || !source.SelfDescribingEvents)) { bNeedsManifest = (flags & EventManifestOptions.OnlyIfNeededForRegistration) == 0 #if FEATURE_MANAGED_ETW_CHANNELS || manifest.GetChannelData().Length > 0 #endif ; // if the manifest is not needed and we're not requested to validate the event source return early if (!bNeedsManifest && (flags & EventManifestOptions.Strict) == 0) return null; res = manifest.CreateManifest(); } } catch (Exception e) { // if this is a runtime manifest generation let the exception propagate if ((flags & EventManifestOptions.Strict) == 0) throw; // else store it to include it in the Argument exception we raise below exception = e; } if ((flags & EventManifestOptions.Strict) != 0 && (manifest?.Errors.Count > 0 || exception != null)) { string msg = string.Empty; if (manifest?.Errors.Count > 0) { bool firstError = true; foreach (string error in manifest.Errors) { if (!firstError) msg += System.Environment.NewLine; firstError = false; msg += error; } } else msg = "Unexpected error: " + exception!.Message; throw new ArgumentException(msg, exception); } return bNeedsManifest ? res : null; } private static bool RemoveFirstArgIfRelatedActivityId(ref ParameterInfo[] args) { // If the first parameter is (case insensitive) 'relatedActivityId' then skip it. if (args.Length > 0 && args[0].ParameterType == typeof(Guid) && string.Equals(args[0].Name, "relatedActivityId", StringComparison.OrdinalIgnoreCase)) { var newargs = new ParameterInfo[args.Length - 1]; Array.Copy(args, 1, newargs, 0, args.Length - 1); args = newargs; return true; } return false; } // adds a enumeration (keyword, opcode, task or channel) represented by 'staticField' // to the manifest. private static void AddProviderEnumKind(ManifestBuilder manifest, FieldInfo staticField, string providerEnumKind) { bool reflectionOnly = staticField.Module.Assembly.ReflectionOnly; Type staticFieldType = staticField.FieldType; if (!reflectionOnly && (staticFieldType == typeof(EventOpcode)) || AttributeTypeNamesMatch(staticFieldType, typeof(EventOpcode))) { if (providerEnumKind != "Opcodes") goto Error; int value = (int)staticField.GetRawConstantValue()!; manifest.AddOpcode(staticField.Name, value); } else if (!reflectionOnly && (staticFieldType == typeof(EventTask)) || AttributeTypeNamesMatch(staticFieldType, typeof(EventTask))) { if (providerEnumKind != "Tasks") goto Error; int value = (int)staticField.GetRawConstantValue()!; manifest.AddTask(staticField.Name, value); } else if (!reflectionOnly && (staticFieldType == typeof(EventKeywords)) || AttributeTypeNamesMatch(staticFieldType, typeof(EventKeywords))) { if (providerEnumKind != "Keywords") goto Error; ulong value = unchecked((ulong)(long)staticField.GetRawConstantValue()!); manifest.AddKeyword(staticField.Name, value); } #if FEATURE_MANAGED_ETW_CHANNELS && FEATURE_ADVANCED_MANAGED_ETW_CHANNELS else if (!reflectionOnly && (staticFieldType == typeof(EventChannel)) || AttributeTypeNamesMatch(staticFieldType, typeof(EventChannel))) { if (providerEnumKind != "Channels") goto Error; var channelAttribute = (EventChannelAttribute)GetCustomAttributeHelper(staticField, typeof(EventChannelAttribute)); manifest.AddChannel(staticField.Name, (byte)staticField.GetRawConstantValue(), channelAttribute); } #endif return; Error: manifest.ManifestError(SR.Format(SR.EventSource_EnumKindMismatch, staticField.FieldType.Name, providerEnumKind)); } // Helper used by code:CreateManifestAndDescriptors to add a code:EventData descriptor for a method // with the code:EventAttribute 'eventAttribute'. resourceManger may be null in which case we populate it // it is populated if we need to look up message resources private static void AddEventDescriptor( [NotNull] ref EventMetadata[] eventData, string eventName, EventAttribute eventAttribute, ParameterInfo[] eventParameters, bool hasRelatedActivityID) { if (eventData.Length <= eventAttribute.EventId) { EventMetadata[] newValues = new EventMetadata[Math.Max(eventData.Length + 16, eventAttribute.EventId + 1)]; Array.Copy(eventData, newValues, eventData.Length); eventData = newValues; } ref EventMetadata metadata = ref eventData[eventAttribute.EventId]; metadata.Descriptor = new EventDescriptor( eventAttribute.EventId, eventAttribute.Version, #if FEATURE_MANAGED_ETW_CHANNELS (byte)eventAttribute.Channel, #else (byte)0, #endif (byte)eventAttribute.Level, (byte)eventAttribute.Opcode, (int)eventAttribute.Task, unchecked((long)((ulong)eventAttribute.Keywords | SessionMask.All.ToEventKeywords()))); metadata.Tags = eventAttribute.Tags; metadata.Name = eventName; metadata.Parameters = eventParameters; metadata.Message = eventAttribute.Message; metadata.ActivityOptions = eventAttribute.ActivityOptions; metadata.HasRelatedActivityID = hasRelatedActivityID; metadata.EventHandle = IntPtr.Zero; // We represent a byte[] with 2 EventData entries: an integer denoting the length and a blob of bytes in the data pointer. // This causes a spurious warning because eventDataCount is off by one for the byte[] case. // When writing to EventListeners, we want to check that the number of parameters is correct against the byte[] case. int eventListenerParameterCount = eventParameters.Length; bool allParametersAreInt32 = true; bool allParametersAreString = true; foreach (ParameterInfo parameter in eventParameters) { Type dataType = parameter.ParameterType; if (dataType == typeof(string)) { allParametersAreInt32 = false; } else if (dataType == typeof(int) || (dataType.IsEnum && Type.GetTypeCode(dataType.GetEnumUnderlyingType()) <= TypeCode.UInt32)) { // Int32 or an enum with a 1/2/4 byte backing type allParametersAreString = false; } else { if (dataType == typeof(byte[])) { eventListenerParameterCount++; } allParametersAreInt32 = false; allParametersAreString = false; } } metadata.AllParametersAreInt32 = allParametersAreInt32; metadata.AllParametersAreString = allParametersAreString; metadata.EventListenerParameterCount = eventListenerParameterCount; } // Helper used by code:CreateManifestAndDescriptors that trims the m_eventData array to the correct // size after all event descriptors have been added. private static void TrimEventDescriptors(ref EventMetadata[] eventData) { int idx = eventData.Length; while (0 < idx) { --idx; if (eventData[idx].Descriptor.EventId != 0) break; } if (eventData.Length - idx > 2) // allow one wasted slot. { EventMetadata[] newValues = new EventMetadata[idx + 1]; Array.Copy(eventData, newValues, newValues.Length); eventData = newValues; } } // Helper used by code:EventListener.AddEventSource and code:EventListener.EventListener // when a listener gets attached to a eventSource internal void AddListener(EventListener listener) { lock (EventListener.EventListenersLock) { bool[]? enabledArray = null; if (m_eventData != null) enabledArray = new bool[m_eventData.Length]; m_Dispatchers = new EventDispatcher(m_Dispatchers, enabledArray, listener); listener.OnEventSourceCreated(this); } } // Helper used by code:CreateManifestAndDescriptors to find user mistakes like reusing an event // index for two distinct events etc. Throws exceptions when it finds something wrong. private static void DebugCheckEvent(ref Dictionary<string, string>? eventsByName, EventMetadata[] eventData, MethodInfo method, EventAttribute eventAttribute, ManifestBuilder manifest, EventManifestOptions options) { int evtId = eventAttribute.EventId; string evtName = method.Name; int eventArg = GetHelperCallFirstArg(method); if (eventArg >= 0 && evtId != eventArg) { manifest.ManifestError(SR.Format(SR.EventSource_MismatchIdToWriteEvent, evtName, evtId, eventArg), true); } if (evtId < eventData.Length && eventData[evtId].Descriptor.EventId != 0) { manifest.ManifestError(SR.Format(SR.EventSource_EventIdReused, evtName, evtId), true); } // We give a task to things if they don't have one. // TODO this is moderately expensive (N*N). We probably should not even bother.... Debug.Assert(eventAttribute.Task != EventTask.None || eventAttribute.Opcode != EventOpcode.Info); for (int idx = 0; idx < eventData.Length; ++idx) { // skip unused Event IDs. if (eventData[idx].Name == null) continue; if (eventData[idx].Descriptor.Task == (int)eventAttribute.Task && eventData[idx].Descriptor.Opcode == (int)eventAttribute.Opcode) { manifest.ManifestError(SR.Format(SR.EventSource_TaskOpcodePairReused, evtName, evtId, eventData[idx].Name, idx)); // If we are not strict stop on first error. We have had problems with really large providers taking forever. because of many errors. if ((options & EventManifestOptions.Strict) == 0) break; } } // for non-default event opcodes the user must define a task! if (eventAttribute.Opcode != EventOpcode.Info) { bool failure = false; if (eventAttribute.Task == EventTask.None) failure = true; else { // If you have the auto-assigned Task, then you did not explicitly set one. // This is OK for Start events because we have special logic to assign the task to a prefix derived from the event name // But all other cases we want to catch the omission. var autoAssignedTask = (EventTask)(0xFFFE - evtId); if (eventAttribute.Opcode != EventOpcode.Start && eventAttribute.Opcode != EventOpcode.Stop && eventAttribute.Task == autoAssignedTask) failure = true; } if (failure) { manifest.ManifestError(SR.Format(SR.EventSource_EventMustHaveTaskIfNonDefaultOpcode, evtName, evtId)); } } // If we ever want to enforce the rule: MethodName = TaskName + OpcodeName here's how: // (the reason we don't is backwards compat and the need for handling this as a non-fatal error // by eventRegister.exe) // taskName & opcodeName could be passed in by the caller which has opTab & taskTab handy // if (!(((int)eventAttribute.Opcode == 0 && evtName == taskName) || (evtName == taskName+opcodeName))) // { // throw new WarningException(SR.EventSource_EventNameDoesNotEqualTaskPlusOpcode); // } eventsByName ??= new Dictionary<string, string>(); if (eventsByName.ContainsKey(evtName)) { manifest.ManifestError(SR.Format(SR.EventSource_EventNameReused, evtName), true); } eventsByName[evtName] = evtName; } /// <summary> /// This method looks at the IL and tries to pattern match against the standard /// 'boilerplate' event body /// <code> /// { if (Enabled()) WriteEvent(#, ...) } /// </code> /// If the pattern matches, it returns the literal number passed as the first parameter to /// the WriteEvent. This is used to find common user errors (mismatching this /// number with the EventAttribute ID). It is only used for validation. /// </summary> /// <param name="method">The method to probe.</param> /// <returns>The literal value or -1 if the value could not be determined. </returns> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The method calls MethodBase.GetMethodBody. Trimming application can change IL of various methods" + "which can lead to change of behavior. This method only uses this to validate usage of event source APIs." + "In the worst case it will not be able to determine the value it's looking for and will not perform" + "any validation.")] #endif private static int GetHelperCallFirstArg(MethodInfo method) { #if !CORERT // Currently searches for the following pattern // // ... // CAN ONLY BE THE INSTRUCTIONS BELOW // LDARG0 // LDC.I4 XXX // ... // CAN ONLY BE THE INSTRUCTIONS BELOW CAN'T BE A BRANCH OR A CALL // CALL // NOP // 0 or more times // RET // // If we find this pattern we return the XXX. Otherwise we return -1. #if ES_BUILD_STANDALONE (new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)).Assert(); #endif byte[] instrs = method.GetMethodBody()!.GetILAsByteArray()!; int retVal = -1; for (int idx = 0; idx < instrs.Length;) { switch (instrs[idx]) { case 0: // NOP case 1: // BREAK case 2: // LDARG_0 case 3: // LDARG_1 case 4: // LDARG_2 case 5: // LDARG_3 case 6: // LDLOC_0 case 7: // LDLOC_1 case 8: // LDLOC_2 case 9: // LDLOC_3 case 10: // STLOC_0 case 11: // STLOC_1 case 12: // STLOC_2 case 13: // STLOC_3 break; case 14: // LDARG_S case 16: // STARG_S idx++; break; case 20: // LDNULL break; case 21: // LDC_I4_M1 case 22: // LDC_I4_0 case 23: // LDC_I4_1 case 24: // LDC_I4_2 case 25: // LDC_I4_3 case 26: // LDC_I4_4 case 27: // LDC_I4_5 case 28: // LDC_I4_6 case 29: // LDC_I4_7 case 30: // LDC_I4_8 if (idx > 0 && instrs[idx - 1] == 2) // preceeded by LDARG0 retVal = instrs[idx] - 22; break; case 31: // LDC_I4_S if (idx > 0 && instrs[idx - 1] == 2) // preceeded by LDARG0 retVal = instrs[idx + 1]; idx++; break; case 32: // LDC_I4 idx += 4; break; case 37: // DUP break; case 40: // CALL idx += 4; if (retVal >= 0) { // Is this call just before return? for (int search = idx + 1; search < instrs.Length; search++) { if (instrs[search] == 42) // RET return retVal; if (instrs[search] != 0) // NOP break; } } retVal = -1; break; case 44: // BRFALSE_S case 45: // BRTRUE_S retVal = -1; idx++; break; case 57: // BRFALSE case 58: // BRTRUE retVal = -1; idx += 4; break; case 103: // CONV_I1 case 104: // CONV_I2 case 105: // CONV_I4 case 106: // CONV_I8 case 109: // CONV_U4 case 110: // CONV_U8 break; case 140: // BOX case 141: // NEWARR idx += 4; break; case 162: // STELEM_REF break; case 254: // PREFIX idx++; // Covers the CEQ instructions used in debug code for some reason. if (idx >= instrs.Length || instrs[idx] >= 6) goto default; break; default: /* Debug.Fail("Warning: User validation code sub-optimial: Unsuported opcode " + instrs[idx] + " at " + idx + " in method " + method.Name); */ return -1; } idx++; } #endif return -1; } /// <summary> /// Sends an error message to the debugger (outputDebugString), as well as the EventListeners /// It will do this even if the EventSource is not enabled. /// </summary> internal void ReportOutOfBandMessage(string msg) { try { if (m_outOfBandMessageCount < 16 - 1) // Note this is only if size byte { m_outOfBandMessageCount++; } else { if (m_outOfBandMessageCount == 16) return; m_outOfBandMessageCount = 16; // Mark that we hit the limit. Notify them that this is the case. msg = "Reached message limit. End of EventSource error messages."; } // send message to debugger Debugger.Log(0, null, $"EventSource Error: {msg}{System.Environment.NewLine}"); // Send it to all listeners. WriteEventString(msg); WriteStringToAllListeners("EventSourceMessage", msg); } catch { } // If we fail during last chance logging, well, we have to give up.... } private static EventSourceSettings ValidateSettings(EventSourceSettings settings) { const EventSourceSettings evtFormatMask = EventSourceSettings.EtwManifestEventFormat | EventSourceSettings.EtwSelfDescribingEventFormat; if ((settings & evtFormatMask) == evtFormatMask) { throw new ArgumentException(SR.EventSource_InvalidEventFormat, nameof(settings)); } // If you did not explicitly ask for manifest, you get self-describing. if ((settings & evtFormatMask) == 0) settings |= EventSourceSettings.EtwSelfDescribingEventFormat; return settings; } private bool ThrowOnEventWriteErrors => (m_config & EventSourceSettings.ThrowOnEventWriteErrors) != 0; private bool SelfDescribingEvents { get { Debug.Assert(((m_config & EventSourceSettings.EtwManifestEventFormat) != 0) != ((m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != 0)); return (m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != 0; } } // private instance state private string m_name = null!; // My friendly name (privided in ctor) internal int m_id; // A small integer that is unique to this instance. private Guid m_guid; // GUID representing the ETW eventSource to the OS. internal volatile EventMetadata[]? m_eventData; // None per-event data private volatile byte[]? m_rawManifest; // Bytes to send out representing the event schema private EventHandler<EventCommandEventArgs>? m_eventCommandExecuted; private readonly EventSourceSettings m_config; // configuration information private bool m_eventSourceDisposed; // has Dispose been called. // Enabling bits private bool m_eventSourceEnabled; // am I enabled (any of my events are enabled for any dispatcher) internal EventLevel m_level; // highest level enabled by any output dispatcher internal EventKeywords m_matchAnyKeyword; // the logical OR of all levels enabled by any output dispatcher (zero is a special case) meaning 'all keywords' // Dispatching state internal volatile EventDispatcher? m_Dispatchers; // Linked list of code:EventDispatchers we write the data to (we also do ETW specially) #if FEATURE_MANAGED_ETW private volatile OverrideEventProvider m_etwProvider = null!; // This hooks up ETW commands to our 'OnEventCommand' callback #endif #if FEATURE_PERFTRACING private object? m_createEventLock; private IntPtr m_writeEventStringEventHandle = IntPtr.Zero; private volatile OverrideEventProvider m_eventPipeProvider = null!; #endif private bool m_completelyInited; // The EventSource constructor has returned without exception. private Exception? m_constructionException; // If there was an exception construction, this is it private byte m_outOfBandMessageCount; // The number of out of band messages sent (we throttle them private EventCommandEventArgs? m_deferredCommands; // If we get commands before we are fully we store them here and run the when we are fully inited. private string[]? m_traits; // Used to implement GetTraits [ThreadStatic] private static byte m_EventSourceExceptionRecurenceCount; // current recursion count inside ThrowEventSourceException #if FEATURE_MANAGED_ETW_CHANNELS internal volatile ulong[]? m_channelData; #endif // We use a single instance of ActivityTracker for all EventSources instances to allow correlation between multiple event providers. // We have m_activityTracker field simply because instance field is more efficient than static field fetch. private ActivityTracker m_activityTracker = null!; internal const string s_ActivityStartSuffix = "Start"; internal const string s_ActivityStopSuffix = "Stop"; // This switch controls an opt-in, off-by-default mechanism for allowing multiple EventSources to have the same // name and by extension GUID. This is not considered a mainline scenario and is explicitly intended as a release // valve for users that make heavy use of AssemblyLoadContext and experience exceptions from EventSource. // This does not solve any issues that might arise from this configuration. For instance: // // * If multiple manifest-mode EventSources have the same name/GUID, it is ambiguous which manifest should be used by an ETW parser. // This can result in events being incorrectly parse. The data will still be there, but EventTrace (or other libraries) won't // know how to parse it. // * Potential issues in parsing self-describing EventSources that use the same name/GUID, event name, and payload type from the same AssemblyLoadContext // but have different event IDs set. // // Most users should not turn this on. internal const string DuplicateSourceNamesSwitch = "System.Diagnostics.Tracing.EventSource.AllowDuplicateSourceNames"; private static readonly bool AllowDuplicateSourceNames = AppContext.TryGetSwitch(DuplicateSourceNamesSwitch, out bool isEnabled) ? isEnabled : false; // WARNING: Do not depend upon initialized statics during creation of EventSources, as it is possible for creation of an EventSource to trigger // creation of yet another EventSource. When this happens, these statics may not yet be initialized. // Rather than depending on initialized statics, use lazy initialization to ensure that the statics are initialized exactly when they are needed. #if ES_BUILD_STANDALONE // used for generating GUID from eventsource name private static byte[]? namespaceBytes; #endif #endregion } /// <summary> /// Enables specifying event source configuration options to be used in the EventSource constructor. /// </summary> [Flags] public enum EventSourceSettings { /// <summary> /// This specifies none of the special configuration options should be enabled. /// </summary> Default = 0, /// <summary> /// Normally an EventSource NEVER throws; setting this option will tell it to throw when it encounters errors. /// </summary> ThrowOnEventWriteErrors = 1, /// <summary> /// Setting this option is a directive to the ETW listener should use manifest-based format when /// firing events. This is the default option when defining a type derived from EventSource /// (using the protected EventSource constructors). /// Only one of EtwManifestEventFormat or EtwSelfDescribingEventFormat should be specified /// </summary> EtwManifestEventFormat = 4, /// <summary> /// Setting this option is a directive to the ETW listener should use self-describing event format /// when firing events. This is the default option when creating a new instance of the EventSource /// type (using the public EventSource constructors). /// Only one of EtwManifestEventFormat or EtwSelfDescribingEventFormat should be specified /// </summary> EtwSelfDescribingEventFormat = 8, } /// <summary> /// An EventListener represents a target for the events generated by EventSources (that is subclasses /// of <see cref="EventSource"/>), in the current appdomain. When a new EventListener is created /// it is logically attached to all eventSources in that appdomain. When the EventListener is Disposed, then /// it is disconnected from the event eventSources. Note that there is a internal list of STRONG references /// to EventListeners, which means that relying on the lack of references to EventListeners to clean up /// EventListeners will NOT work. You must call EventListener.Dispose explicitly when a dispatcher is no /// longer needed. /// <para> /// Once created, EventListeners can enable or disable on a per-eventSource basis using verbosity levels /// (<see cref="EventLevel"/>) and bitfields (<see cref="EventKeywords"/>) to further restrict the set of /// events to be sent to the dispatcher. The dispatcher can also send arbitrary commands to a particular /// eventSource using the 'SendCommand' method. The meaning of the commands are eventSource specific. /// </para><para> /// The Null Guid (that is (new Guid()) has special meaning as a wildcard for 'all current eventSources in /// the appdomain'. Thus it is relatively easy to turn on all events in the appdomain if desired. /// </para><para> /// It is possible for there to be many EventListener's defined in a single appdomain. Each dispatcher is /// logically independent of the other listeners. Thus when one dispatcher enables or disables events, it /// affects only that dispatcher (other listeners get the events they asked for). It is possible that /// commands sent with 'SendCommand' would do a semantic operation that would affect the other listeners /// (like doing a GC, or flushing data ...), but this is the exception rather than the rule. /// </para><para> /// Thus the model is that each EventSource keeps a list of EventListeners that it is sending events /// to. Associated with each EventSource-dispatcher pair is a set of filtering criteria that determine for /// that eventSource what events that dispatcher will receive. /// </para><para> /// Listeners receive the events on their 'OnEventWritten' method. Thus subclasses of EventListener must /// override this method to do something useful with the data. /// </para><para> /// In addition, when new eventSources are created, the 'OnEventSourceCreate' method is called. The /// invariant associated with this callback is that every eventSource gets exactly one /// 'OnEventSourceCreate' call for ever eventSource that can potentially send it log messages. In /// particular when a EventListener is created, typically a series of OnEventSourceCreate' calls are /// made to notify the new dispatcher of all the eventSources that existed before the EventListener was /// created. /// </para> /// </summary> public class EventListener : IDisposable { private event EventHandler<EventSourceCreatedEventArgs>? _EventSourceCreated; /// <summary> /// This event is raised whenever a new eventSource is 'attached' to the dispatcher. /// This can happen for all existing EventSources when the EventListener is created /// as well as for any EventSources that come into existence after the EventListener /// has been created. /// /// These 'catch up' events are called during the construction of the EventListener. /// Subclasses need to be prepared for that. /// /// In a multi-threaded environment, it is possible that 'EventSourceEventWrittenCallback' /// events for a particular eventSource to occur BEFORE the EventSourceCreatedCallback is issued. /// </summary> public event EventHandler<EventSourceCreatedEventArgs>? EventSourceCreated { add { CallBackForExistingEventSources(false, value); this._EventSourceCreated = (EventHandler<EventSourceCreatedEventArgs>?)Delegate.Combine(_EventSourceCreated, value); } remove { this._EventSourceCreated = (EventHandler<EventSourceCreatedEventArgs>?)Delegate.Remove(_EventSourceCreated, value); } } /// <summary> /// This event is raised whenever an event has been written by a EventSource for which /// the EventListener has enabled events. /// </summary> public event EventHandler<EventWrittenEventArgs>? EventWritten; static EventListener() { #if FEATURE_PERFTRACING // This allows NativeRuntimeEventSource to get initialized so that EventListeners can subscribe to the runtime events emitted from // native side. GC.KeepAlive(NativeRuntimeEventSource.Log); #endif } /// <summary> /// Create a new EventListener in which all events start off turned off (use EnableEvents to turn /// them on). /// </summary> public EventListener() { // This will cause the OnEventSourceCreated callback to fire. CallBackForExistingEventSources(true, (obj, args) => args.EventSource!.AddListener((EventListener)obj!)); } /// <summary> /// Dispose should be called when the EventListener no longer desires 'OnEvent*' callbacks. Because /// there is an internal list of strong references to all EventListeners, calling 'Dispose' directly /// is the only way to actually make the listen die. Thus it is important that users of EventListener /// call Dispose when they are done with their logging. /// </summary> public virtual void Dispose() { lock (EventListenersLock) { if (s_Listeners != null) { if (this == s_Listeners) { EventListener cur = s_Listeners; s_Listeners = this.m_Next; RemoveReferencesToListenerInEventSources(cur); } else { // Find 'this' from the s_Listeners linked list. EventListener prev = s_Listeners; while (true) { EventListener? cur = prev.m_Next; if (cur == null) break; if (cur == this) { // Found our Listener, remove references to it in the eventSources prev.m_Next = cur.m_Next; // Remove entry. RemoveReferencesToListenerInEventSources(cur); break; } prev = cur; } } } Validate(); } } // We don't expose a Dispose(bool), because the contract is that you don't have any non-syncronous // 'cleanup' associated with this object /// <summary> /// Enable all events from the eventSource identified by 'eventSource' to the current /// dispatcher that have a verbosity level of 'level' or lower. /// /// This call can have the effect of REDUCING the number of events sent to the /// dispatcher if 'level' indicates a less verbose level than was previously enabled. /// /// This call never has an effect on other EventListeners. /// /// </summary> public void EnableEvents(EventSource eventSource, EventLevel level) { EnableEvents(eventSource, level, EventKeywords.None); } /// <summary> /// Enable all events from the eventSource identified by 'eventSource' to the current /// dispatcher that have a verbosity level of 'level' or lower and have a event keyword /// matching any of the bits in 'matchAnyKeyword'. /// /// This call can have the effect of REDUCING the number of events sent to the /// dispatcher if 'level' indicates a less verbose level than was previously enabled or /// if 'matchAnyKeyword' has fewer keywords set than where previously set. /// /// This call never has an effect on other EventListeners. /// </summary> public void EnableEvents(EventSource eventSource, EventLevel level, EventKeywords matchAnyKeyword) { EnableEvents(eventSource, level, matchAnyKeyword, null); } /// <summary> /// Enable all events from the eventSource identified by 'eventSource' to the current /// dispatcher that have a verbosity level of 'level' or lower and have a event keyword /// matching any of the bits in 'matchAnyKeyword' as well as any (eventSource specific) /// effect passing additional 'key-value' arguments 'arguments' might have. /// /// This call can have the effect of REDUCING the number of events sent to the /// dispatcher if 'level' indicates a less verbose level than was previously enabled or /// if 'matchAnyKeyword' has fewer keywords set than where previously set. /// /// This call never has an effect on other EventListeners. /// </summary> public void EnableEvents(EventSource eventSource!!, EventLevel level, EventKeywords matchAnyKeyword, IDictionary<string, string?>? arguments) { eventSource.SendCommand(this, EventProviderType.None, 0, 0, EventCommand.Update, true, level, matchAnyKeyword, arguments); #if FEATURE_PERFTRACING if (eventSource.GetType() == typeof(NativeRuntimeEventSource)) { EventPipeEventDispatcher.Instance.SendCommand(this, EventCommand.Update, true, level, matchAnyKeyword); } #endif // FEATURE_PERFTRACING } /// <summary> /// Disables all events coming from eventSource identified by 'eventSource'. /// /// This call never has an effect on other EventListeners. /// </summary> public void DisableEvents(EventSource eventSource!!) { eventSource.SendCommand(this, EventProviderType.None, 0, 0, EventCommand.Update, false, EventLevel.LogAlways, EventKeywords.None, null); #if FEATURE_PERFTRACING if (eventSource.GetType() == typeof(NativeRuntimeEventSource)) { EventPipeEventDispatcher.Instance.SendCommand(this, EventCommand.Update, false, EventLevel.LogAlways, EventKeywords.None); } #endif // FEATURE_PERFTRACING } /// <summary> /// EventSourceIndex is small non-negative integer (suitable for indexing in an array) /// identifying EventSource. It is unique per-appdomain. Some EventListeners might find /// it useful to store additional information about each eventSource connected to it, /// and EventSourceIndex allows this extra information to be efficiently stored in a /// (growable) array (eg List(T)). /// </summary> public static int EventSourceIndex(EventSource eventSource) { return eventSource.m_id; } /// <summary> /// This method is called whenever a new eventSource is 'attached' to the dispatcher. /// This can happen for all existing EventSources when the EventListener is created /// as well as for any EventSources that come into existence after the EventListener /// has been created. /// /// These 'catch up' events are called during the construction of the EventListener. /// Subclasses need to be prepared for that. /// /// In a multi-threaded environment, it is possible that 'OnEventWritten' callbacks /// for a particular eventSource to occur BEFORE the OnEventSourceCreated is issued. /// </summary> /// <param name="eventSource"></param> protected internal virtual void OnEventSourceCreated(EventSource eventSource) { EventHandler<EventSourceCreatedEventArgs>? callBack = this._EventSourceCreated; if (callBack != null) { EventSourceCreatedEventArgs args = new EventSourceCreatedEventArgs(); args.EventSource = eventSource; callBack(this, args); } } /// <summary> /// This method is called whenever an event has been written by a EventSource for which /// the EventListener has enabled events. /// </summary> /// <param name="eventData"></param> protected internal virtual void OnEventWritten(EventWrittenEventArgs eventData) { this.EventWritten?.Invoke(this, eventData); } #region private /// <summary> /// This routine adds newEventSource to the global list of eventSources, it also assigns the /// ID to the eventSource (which is simply the ordinal in the global list). /// /// EventSources currently do not pro-actively remove themselves from this list. Instead /// when eventSources's are GCed, the weak handle in this list naturally gets nulled, and /// we will reuse the slot. Today this list never shrinks (but we do reuse entries /// that are in the list). This seems OK since the expectation is that EventSources /// tend to live for the lifetime of the appdomain anyway (they tend to be used in /// global variables). /// </summary> /// <param name="newEventSource"></param> internal static void AddEventSource(EventSource newEventSource) { lock (EventListenersLock) { Debug.Assert(s_EventSources != null); #if ES_BUILD_STANDALONE // netcoreapp build calls DisposeOnShutdown directly from AppContext.OnProcessExit if (!s_EventSourceShutdownRegistered) { s_EventSourceShutdownRegistered = true; AppDomain.CurrentDomain.ProcessExit += DisposeOnShutdown; AppDomain.CurrentDomain.DomainUnload += DisposeOnShutdown; } #endif // Periodically search the list for existing entries to reuse, this avoids // unbounded memory use if we keep recycling eventSources (an unlikely thing). int newIndex = -1; if (s_EventSources.Count % 64 == 63) // on every block of 64, fill up the block before continuing { int i = s_EventSources.Count; // Work from the top down. while (0 < i) { --i; WeakReference<EventSource> weakRef = s_EventSources[i]; if (!weakRef.TryGetTarget(out _)) { newIndex = i; weakRef.SetTarget(newEventSource); break; } } } if (newIndex < 0) { newIndex = s_EventSources.Count; s_EventSources.Add(new WeakReference<EventSource>(newEventSource)); } newEventSource.m_id = newIndex; #if DEBUG // Disable validation of EventSource/EventListener connections in case a call to EventSource.AddListener // causes a recursive call into this method. bool previousValue = s_ConnectingEventSourcesAndListener; s_ConnectingEventSourcesAndListener = true; try { #endif // Add every existing dispatcher to the new EventSource for (EventListener? listener = s_Listeners; listener != null; listener = listener.m_Next) newEventSource.AddListener(listener); #if DEBUG } finally { s_ConnectingEventSourcesAndListener = previousValue; } #endif Validate(); } } // Whenver we have async callbacks from native code, there is an ugly issue where // during .NET shutdown native code could be calling the callback, but the CLR // has already prohibited callbacks to managed code in the appdomain, causing the CLR // to throw a COMPLUS_BOOT_EXCEPTION. The guideline we give is that you must unregister // such callbacks on process shutdown or appdomain so that unmanaged code will never // do this. This is what this callback is for. // See bug 724140 for more #if ES_BUILD_STANDALONE private static void DisposeOnShutdown(object? sender, EventArgs e) #else internal static void DisposeOnShutdown() #endif { Debug.Assert(EventSource.IsSupported); List<EventSource> sourcesToDispose = new List<EventSource>(); lock (EventListenersLock) { Debug.Assert(s_EventSources != null); foreach (WeakReference<EventSource> esRef in s_EventSources) { if (esRef.TryGetTarget(out EventSource? es)) { sourcesToDispose.Add(es); } } } // Do not invoke Dispose under the lock as this can lead to a deadlock. // See https://github.com/dotnet/runtime/issues/48342 for details. Debug.Assert(!Monitor.IsEntered(EventListenersLock)); foreach (EventSource es in sourcesToDispose) { es.Dispose(); } } /// <summary> /// Helper used in code:Dispose that removes any references to 'listenerToRemove' in any of the /// eventSources in the appdomain. /// /// The EventListenersLock must be held before calling this routine. /// </summary> private static void RemoveReferencesToListenerInEventSources(EventListener listenerToRemove) { #if !ES_BUILD_STANDALONE Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif // Foreach existing EventSource in the appdomain Debug.Assert(s_EventSources != null); foreach (WeakReference<EventSource> eventSourceRef in s_EventSources) { if (eventSourceRef.TryGetTarget(out EventSource? eventSource)) { Debug.Assert(eventSource.m_Dispatchers != null); // Is the first output dispatcher the dispatcher we are removing? if (eventSource.m_Dispatchers.m_Listener == listenerToRemove) eventSource.m_Dispatchers = eventSource.m_Dispatchers.m_Next; else { // Remove 'listenerToRemove' from the eventSource.m_Dispatchers linked list. EventDispatcher? prev = eventSource.m_Dispatchers; while (true) { EventDispatcher? cur = prev.m_Next; if (cur == null) { Debug.Fail("EventSource did not have a registered EventListener!"); break; } if (cur.m_Listener == listenerToRemove) { prev.m_Next = cur.m_Next; // Remove entry. break; } prev = cur; } } } } #if FEATURE_PERFTRACING // Remove the listener from the EventPipe dispatcher. EventPipeEventDispatcher.Instance.RemoveEventListener(listenerToRemove); #endif // FEATURE_PERFTRACING } /// <summary> /// Checks internal consistency of EventSources/Listeners. /// </summary> [Conditional("DEBUG")] internal static void Validate() { #if DEBUG // Don't run validation code if we're in the middle of modifying the connections between EventSources and EventListeners. if (s_ConnectingEventSourcesAndListener) { return; } #endif lock (EventListenersLock) { Debug.Assert(s_EventSources != null); // Get all listeners Dictionary<EventListener, bool> allListeners = new Dictionary<EventListener, bool>(); EventListener? cur = s_Listeners; while (cur != null) { allListeners.Add(cur, true); cur = cur.m_Next; } // For all eventSources int id = -1; foreach (WeakReference<EventSource> eventSourceRef in s_EventSources) { id++; if (!eventSourceRef.TryGetTarget(out EventSource? eventSource)) continue; Debug.Assert(eventSource.m_id == id, "Unexpected event source ID."); // None listeners on eventSources exist in the dispatcher list. EventDispatcher? dispatcher = eventSource.m_Dispatchers; while (dispatcher != null) { Debug.Assert(allListeners.ContainsKey(dispatcher.m_Listener), "EventSource has a listener not on the global list."); dispatcher = dispatcher.m_Next; } // Every dispatcher is on Dispatcher List of every eventSource. foreach (EventListener listener in allListeners.Keys) { dispatcher = eventSource.m_Dispatchers; while (true) { Debug.Assert(dispatcher != null, "Listener is not on all eventSources."); if (dispatcher.m_Listener == listener) break; dispatcher = dispatcher.m_Next; } } } } } /// <summary> /// Gets a global lock that is intended to protect the code:s_Listeners linked list and the /// code:s_EventSources list. (We happen to use the s_EventSources list as the lock object) /// </summary> internal static object EventListenersLock { get { if (s_EventSources == null) Interlocked.CompareExchange(ref s_EventSources, new List<WeakReference<EventSource>>(2), null); return s_EventSources; } } private void CallBackForExistingEventSources(bool addToListenersList, EventHandler<EventSourceCreatedEventArgs>? callback) { lock (EventListenersLock) { Debug.Assert(s_EventSources != null); // Disallow creating EventListener reentrancy. if (s_CreatingListener) { throw new InvalidOperationException(SR.EventSource_ListenerCreatedInsideCallback); } try { s_CreatingListener = true; if (addToListenersList) { // Add to list of listeners in the system, do this BEFORE firing the 'OnEventSourceCreated' so that // Those added sources see this listener. this.m_Next = s_Listeners; s_Listeners = this; } if (callback != null) { // Find all existing eventSources call OnEventSourceCreated to 'catchup' // Note that we DO have reentrancy here because 'AddListener' calls out to user code (via OnEventSourceCreated callback) // We tolerate this by iterating over a copy of the list here. New event sources will take care of adding listeners themselves // EventSources are not guaranteed to be added at the end of the s_EventSource list -- We re-use slots when a new source // is created. WeakReference<EventSource>[] eventSourcesSnapshot = s_EventSources.ToArray(); #if DEBUG bool previousValue = s_ConnectingEventSourcesAndListener; s_ConnectingEventSourcesAndListener = true; try { #endif for (int i = 0; i < eventSourcesSnapshot.Length; i++) { WeakReference<EventSource> eventSourceRef = eventSourcesSnapshot[i]; if (eventSourceRef.TryGetTarget(out EventSource? eventSource)) { EventSourceCreatedEventArgs args = new EventSourceCreatedEventArgs(); args.EventSource = eventSource; callback(this, args); } } #if DEBUG } finally { s_ConnectingEventSourcesAndListener = previousValue; } #endif } Validate(); } finally { s_CreatingListener = false; } } } // Instance fields internal volatile EventListener? m_Next; // These form a linked list in s_Listeners // static fields /// <summary> /// The list of all listeners in the appdomain. Listeners must be explicitly disposed to remove themselves /// from this list. Note that EventSources point to their listener but NOT the reverse. /// </summary> internal static EventListener? s_Listeners; /// <summary> /// The list of all active eventSources in the appdomain. Note that eventSources do NOT /// remove themselves from this list this is a weak list and the GC that removes them may /// not have happened yet. Thus it can contain event sources that are dead (thus you have /// to filter those out. /// </summary> internal static List<WeakReference<EventSource>>? s_EventSources; /// <summary> /// Used to disallow reentrancy. /// </summary> private static bool s_CreatingListener; #if DEBUG /// <summary> /// Used to disable validation of EventSource and EventListener connectivity. /// This is needed when an EventListener is in the middle of being published to all EventSources /// and another EventSource is created as part of the process. /// </summary> [ThreadStatic] private static bool s_ConnectingEventSourcesAndListener; #endif #if ES_BUILD_STANDALONE /// <summary> /// Used to register AD/Process shutdown callbacks. /// </summary> private static bool s_EventSourceShutdownRegistered; #endif #endregion } /// <summary> /// Passed to the code:EventSource.OnEventCommand callback /// </summary> public class EventCommandEventArgs : EventArgs { /// <summary> /// Gets the command for the callback. /// </summary> public EventCommand Command { get; internal set; } /// <summary> /// Gets the arguments for the callback. /// </summary> public IDictionary<string, string?>? Arguments { get; internal set; } /// <summary> /// Enables the event that has the specified identifier. /// </summary> /// <param name="eventId">Event ID of event to be enabled</param> /// <returns>true if eventId is in range</returns> public bool EnableEvent(int eventId) { if (Command != EventCommand.Enable && Command != EventCommand.Disable) throw new InvalidOperationException(); return eventSource.EnableEventForDispatcher(dispatcher, eventProviderType, eventId, true); } /// <summary> /// Disables the event that have the specified identifier. /// </summary> /// <param name="eventId">Event ID of event to be disabled</param> /// <returns>true if eventId is in range</returns> public bool DisableEvent(int eventId) { if (Command != EventCommand.Enable && Command != EventCommand.Disable) throw new InvalidOperationException(); return eventSource.EnableEventForDispatcher(dispatcher, eventProviderType, eventId, false); } #region private internal EventCommandEventArgs(EventCommand command, IDictionary<string, string?>? arguments, EventSource eventSource, EventListener? listener, EventProviderType eventProviderType, int perEventSourceSessionId, int etwSessionId, bool enable, EventLevel level, EventKeywords matchAnyKeyword) { this.Command = command; this.Arguments = arguments; this.eventSource = eventSource; this.listener = listener; this.eventProviderType = eventProviderType; this.perEventSourceSessionId = perEventSourceSessionId; this.etwSessionId = etwSessionId; this.enable = enable; this.level = level; this.matchAnyKeyword = matchAnyKeyword; } internal EventSource eventSource; internal EventDispatcher? dispatcher; internal EventProviderType eventProviderType; // These are the arguments of sendCommand and are only used for deferring commands until after we are fully initialized. internal EventListener? listener; internal int perEventSourceSessionId; internal int etwSessionId; internal bool enable; internal EventLevel level; internal EventKeywords matchAnyKeyword; internal EventCommandEventArgs? nextCommand; // We form a linked list of these deferred commands. #endregion } /// <summary> /// EventSourceCreatedEventArgs is passed to <see cref="EventListener.EventSourceCreated"/> /// </summary> public class EventSourceCreatedEventArgs : EventArgs { /// <summary> /// The EventSource that is attaching to the listener. /// </summary> public EventSource? EventSource { get; internal set; } } /// <summary> /// EventWrittenEventArgs is passed to the user-provided override for /// <see cref="EventListener.OnEventWritten"/> when an event is fired. /// </summary> public class EventWrittenEventArgs : EventArgs { internal static readonly ReadOnlyCollection<object?> EmptyPayload = new(Array.Empty<object>()); private ref EventSource.EventMetadata Metadata => ref EventSource.m_eventData![EventId]; /// <summary> /// The name of the event. /// </summary> public string? EventName { get => _moreInfo?.EventName ?? (EventId <= 0 ? null : Metadata.Name); internal set => MoreInfo.EventName = value; } /// <summary> /// Gets the event ID for the event that was written. /// </summary> public int EventId { get; } private Guid _activityId; /// <summary> /// Gets the activity ID for the thread on which the event was written. /// </summary> public Guid ActivityId { get { if (_activityId == Guid.Empty) { _activityId = EventSource.CurrentThreadActivityId; } return _activityId; } } /// <summary> /// Gets the related activity ID if one was specified when the event was written. /// </summary> public Guid RelatedActivityId => _moreInfo?.RelatedActivityId ?? default; /// <summary> /// Gets the payload for the event. /// </summary> public ReadOnlyCollection<object?>? Payload { get; internal set; } /// <summary> /// Gets the payload argument names. /// </summary> public ReadOnlyCollection<string>? PayloadNames { get => _moreInfo?.PayloadNames ?? (EventId <= 0 ? null : Metadata.ParameterNames); internal set => MoreInfo.PayloadNames = value; } /// <summary> /// Gets the event source object. /// </summary> public EventSource EventSource { get; } /// <summary> /// Gets the keywords for the event. /// </summary> public EventKeywords Keywords { get => EventId <= 0 ? (_moreInfo?.Keywords ?? default) : (EventKeywords)Metadata.Descriptor.Keywords; internal set => MoreInfo.Keywords = value; } /// <summary> /// Gets the operation code for the event. /// </summary> public EventOpcode Opcode { get => EventId <= 0 ? (_moreInfo?.Opcode ?? default) : (EventOpcode)Metadata.Descriptor.Opcode; internal set => MoreInfo.Opcode = value; } /// <summary> /// Gets the task for the event. /// </summary> public EventTask Task => EventId <= 0 ? EventTask.None : (EventTask)Metadata.Descriptor.Task; /// <summary> /// Any provider/user defined options associated with the event. /// </summary> public EventTags Tags { get => EventId <= 0 ? (_moreInfo?.Tags ?? default) : Metadata.Tags; internal set => MoreInfo.Tags = value; } /// <summary> /// Gets the message for the event. If the message has {N} parameters they are NOT substituted. /// </summary> public string? Message { get => _moreInfo?.Message ?? (EventId <= 0 ? null : Metadata.Message); internal set => MoreInfo.Message = value; } #if FEATURE_MANAGED_ETW_CHANNELS /// <summary> /// Gets the channel for the event. /// </summary> public EventChannel Channel => EventId <= 0 ? EventChannel.None : (EventChannel)Metadata.Descriptor.Channel; #endif /// <summary> /// Gets the version of the event. /// </summary> public byte Version => EventId <= 0 ? (byte)0 : Metadata.Descriptor.Version; /// <summary> /// Gets the level for the event. /// </summary> public EventLevel Level { get => EventId <= 0 ? (_moreInfo?.Level ?? default) : (EventLevel)Metadata.Descriptor.Level; internal set => MoreInfo.Level = value; } /// <summary> /// Gets the identifier for the OS thread that wrote the event. /// </summary> public long OSThreadId { get { ref long? osThreadId = ref MoreInfo.OsThreadId; if (!osThreadId.HasValue) { #if ES_BUILD_STANDALONE osThreadId = (long)Interop.Kernel32.GetCurrentThreadId(); #else osThreadId = (long)Thread.CurrentOSThreadId; #endif } return osThreadId.Value; } internal set => MoreInfo.OsThreadId = value; } /// <summary> /// Gets a UTC DateTime that specifies when the event was written. /// </summary> public DateTime TimeStamp { get; internal set; } internal EventWrittenEventArgs(EventSource eventSource, int eventId) { EventSource = eventSource; EventId = eventId; TimeStamp = DateTime.UtcNow; } internal unsafe EventWrittenEventArgs(EventSource eventSource, int eventId, Guid* pActivityID, Guid* pChildActivityID) : this(eventSource, eventId) { if (pActivityID != null) { _activityId = *pActivityID; } if (pChildActivityID != null) { MoreInfo.RelatedActivityId = *pChildActivityID; } } private MoreEventInfo? _moreInfo; private MoreEventInfo MoreInfo => _moreInfo ??= new MoreEventInfo(); private sealed class MoreEventInfo { public string? Message; public string? EventName; public ReadOnlyCollection<string>? PayloadNames; public Guid RelatedActivityId; public long? OsThreadId; public EventTags Tags; public EventOpcode Opcode; public EventLevel Level; public EventKeywords Keywords; } } /// <summary> /// Allows customizing defaults and specifying localization support for the event source class to which it is applied. /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class EventSourceAttribute : Attribute { /// <summary> /// Overrides the ETW name of the event source (which defaults to the class name) /// </summary> public string? Name { get; set; } /// <summary> /// Overrides the default (calculated) Guid of an EventSource type. Explicitly defining a GUID is discouraged, /// except when upgrading existing ETW providers to using event sources. /// </summary> public string? Guid { get; set; } /// <summary> /// <para> /// EventSources support localization of events. The names used for events, opcodes, tasks, keywords and maps /// can be localized to several languages if desired. This works by creating a ResX style string table /// (by simply adding a 'Resource File' to your project). This resource file is given a name e.g. /// 'DefaultNameSpace.ResourceFileName' which can be passed to the ResourceManager constructor to read the /// resources. This name is the value of the LocalizationResources property. /// </para><para> /// If LocalizationResources property is non-null, then EventSource will look up the localized strings for events by /// using the following resource naming scheme /// </para> /// <para>* event_EVENTNAME</para> /// <para>* task_TASKNAME</para> /// <para>* keyword_KEYWORDNAME</para> /// <para>* map_MAPNAME</para> /// <para> /// where the capitalized name is the name of the event, task, keyword, or map value that should be localized. /// Note that the localized string for an event corresponds to the Message string, and can have {0} values /// which represent the payload values. /// </para> /// </summary> public string? LocalizationResources { get; set; } } /// <summary> /// Any instance methods in a class that subclasses <see cref="EventSource"/> and that return void are /// assumed by default to be methods that generate an ETW event. Enough information can be deduced from the /// name of the method and its signature to generate basic schema information for the event. The /// <see cref="EventAttribute"/> class allows you to specify additional event schema information for an event if /// desired. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class EventAttribute : Attribute { /// <summary>Construct an EventAttribute with specified eventId</summary> /// <param name="eventId">ID of the ETW event (an integer between 1 and 65535)</param> public EventAttribute(int eventId) { this.EventId = eventId; Level = EventLevel.Informational; } /// <summary>Event's ID</summary> public int EventId { get; private set; } /// <summary>Event's severity level: indicates the severity or verbosity of the event</summary> public EventLevel Level { get; set; } /// <summary>Event's keywords: allows classification of events by "categories"</summary> public EventKeywords Keywords { get; set; } /// <summary>Event's operation code: allows defining operations, generally used with Tasks</summary> public EventOpcode Opcode { get => m_opcode; set { this.m_opcode = value; this.m_opcodeSet = true; } } internal bool IsOpcodeSet => m_opcodeSet; /// <summary>Event's task: allows logical grouping of events</summary> public EventTask Task { get; set; } #if FEATURE_MANAGED_ETW_CHANNELS /// <summary>Event's channel: defines an event log as an additional destination for the event</summary> public EventChannel Channel { get; set; } #endif /// <summary>Event's version</summary> public byte Version { get; set; } /// <summary> /// This can be specified to enable formatting and localization of the event's payload. You can /// use standard .NET substitution operators (eg {1}) in the string and they will be replaced /// with the 'ToString()' of the corresponding part of the event payload. /// </summary> public string? Message { get; set; } /// <summary> /// User defined options associated with the event. These do not have meaning to the EventSource but /// are passed through to listeners which given them semantics. /// </summary> public EventTags Tags { get; set; } /// <summary> /// Allows fine control over the Activity IDs generated by start and stop events /// </summary> public EventActivityOptions ActivityOptions { get; set; } #region private private EventOpcode m_opcode; private bool m_opcodeSet; #endregion } /// <summary> /// By default all instance methods in a class that subclasses code:EventSource that and return /// void are assumed to be methods that generate an event. This default can be overridden by specifying /// the code:NonEventAttribute /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class NonEventAttribute : Attribute { /// <summary> /// Constructs a default NonEventAttribute /// </summary> public NonEventAttribute() { } } // FUTURE we may want to expose this at some point once we have a partner that can help us validate the design. #if FEATURE_MANAGED_ETW_CHANNELS /// <summary> /// EventChannelAttribute allows customizing channels supported by an EventSource. This attribute must be /// applied to an member of type EventChannel defined in a Channels class nested in the EventSource class: /// <code> /// public static class Channels /// { /// [Channel(Enabled = true, EventChannelType = EventChannelType.Admin)] /// public const EventChannel Admin = (EventChannel)16; /// /// [Channel(Enabled = false, EventChannelType = EventChannelType.Operational)] /// public const EventChannel Operational = (EventChannel)17; /// } /// </code> /// </summary> [AttributeUsage(AttributeTargets.Field)] #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS public #else internal #endif class EventChannelAttribute : Attribute { /// <summary> /// Specified whether the channel is enabled by default /// </summary> public bool Enabled { get; set; } /// <summary> /// Legal values are in EventChannelType /// </summary> public EventChannelType EventChannelType { get; set; } #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS /// <summary> /// Specifies the isolation for the channel /// </summary> public EventChannelIsolation Isolation { get; set; } /// <summary> /// Specifies an SDDL access descriptor that controls access to the log file that backs the channel. /// See MSDN (https://docs.microsoft.com/en-us/windows/desktop/WES/eventmanifestschema-channeltype-complextype) for details. /// </summary> public string? Access { get; set; } /// <summary> /// Allows importing channels defined in external manifests /// </summary> public string? ImportChannel { get; set; } #endif // TODO: there is a convention that the name is the Provider/Type Should we provide an override? // public string Name { get; set; } } /// <summary> /// Allowed channel types /// </summary> #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS public #else internal #endif enum EventChannelType { /// <summary>The admin channel</summary> Admin = 1, /// <summary>The operational channel</summary> Operational, /// <summary>The Analytic channel</summary> Analytic, /// <summary>The debug channel</summary> Debug, } #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS /// <summary> /// Allowed isolation levels. See MSDN (https://docs.microsoft.com/en-us/windows/desktop/WES/eventmanifestschema-channeltype-complextype) /// for the default permissions associated with each level. EventChannelIsolation and Access allows control over the /// access permissions for the channel and backing file. /// </summary> public enum EventChannelIsolation { /// <summary> /// This is the default isolation level. All channels that specify Application isolation use the same ETW session /// </summary> Application = 1, /// <summary> /// All channels that specify System isolation use the same ETW session /// </summary> System, /// <summary> /// Use sparingly! When specifying Custom isolation, a separate ETW session is created for the channel. /// Using Custom isolation lets you control the access permissions for the channel and backing file. /// Because there are only 64 ETW sessions available, you should limit your use of Custom isolation. /// </summary> Custom, } #endif #endif /// <summary> /// Describes the pre-defined command (EventCommandEventArgs.Command property) that is passed to the OnEventCommand callback. /// </summary> public enum EventCommand { /// <summary> /// Update EventSource state /// </summary> Update = 0, /// <summary> /// Request EventSource to generate and send its manifest /// </summary> SendManifest = -1, /// <summary> /// Enable event /// </summary> Enable = -2, /// <summary> /// Disable event /// </summary> Disable = -3 } #region private classes // holds a bitfield representing a session mask /// <summary> /// A SessionMask represents a set of (at most MAX) sessions as a bit mask. The perEventSourceSessionId /// is the index in the SessionMask of the bit that will be set. These can translate to /// EventSource's reserved keywords bits using the provided ToEventKeywords() and /// FromEventKeywords() methods. /// </summary> internal struct SessionMask { public SessionMask(SessionMask m) { m_mask = m.m_mask; } public SessionMask(uint mask = 0) { m_mask = mask & MASK; } public bool IsEqualOrSupersetOf(SessionMask m) { return (this.m_mask | m.m_mask) == this.m_mask; } public static SessionMask All => new SessionMask(MASK); public static SessionMask FromId(int perEventSourceSessionId) { Debug.Assert(perEventSourceSessionId < MAX); return new SessionMask((uint)1 << perEventSourceSessionId); } public ulong ToEventKeywords() { return (ulong)m_mask << SHIFT_SESSION_TO_KEYWORD; } public static SessionMask FromEventKeywords(ulong m) { return new SessionMask((uint)(m >> SHIFT_SESSION_TO_KEYWORD)); } public bool this[int perEventSourceSessionId] { get { Debug.Assert(perEventSourceSessionId < MAX); return (m_mask & (1 << perEventSourceSessionId)) != 0; } set { Debug.Assert(perEventSourceSessionId < MAX); if (value) m_mask |= ((uint)1 << perEventSourceSessionId); else m_mask &= ~((uint)1 << perEventSourceSessionId); } } public static SessionMask operator |(SessionMask m1, SessionMask m2) => new SessionMask(m1.m_mask | m2.m_mask); public static SessionMask operator &(SessionMask m1, SessionMask m2) => new SessionMask(m1.m_mask & m2.m_mask); public static SessionMask operator ^(SessionMask m1, SessionMask m2) => new SessionMask(m1.m_mask ^ m2.m_mask); public static SessionMask operator ~(SessionMask m) => new SessionMask(MASK & ~(m.m_mask)); public static explicit operator ulong(SessionMask m) => m.m_mask; public static explicit operator uint(SessionMask m) => m.m_mask; private uint m_mask; internal const int SHIFT_SESSION_TO_KEYWORD = 44; // bits 44-47 inclusive are reserved internal const uint MASK = 0x0fU; // the mask of 4 reserved bits internal const uint MAX = 4; // maximum number of simultaneous ETW sessions supported } /// <summary> /// code:EventDispatchers are a simple 'helper' structure that holds the filtering state /// (m_EventEnabled) for a particular EventSource X EventListener tuple /// /// Thus a single EventListener may have many EventDispatchers (one for every EventSource /// that EventListener has activate) and a Single EventSource may also have many /// event Dispatchers (one for every EventListener that has activated it). /// /// Logically a particular EventDispatcher belongs to exactly one EventSource and exactly /// one EventListener (although EventDispatcher does not 'remember' the EventSource it is /// associated with. /// </summary> internal sealed class EventDispatcher { internal EventDispatcher(EventDispatcher? next, bool[]? eventEnabled, EventListener listener) { m_Next = next; m_EventEnabled = eventEnabled; m_Listener = listener; } // Instance fields internal readonly EventListener m_Listener; // The dispatcher this entry is for internal bool[]? m_EventEnabled; // For every event in a the eventSource, is it enabled? // Only guaranteed to exist after a InsureInit() internal EventDispatcher? m_Next; // These form a linked list in code:EventSource.m_Dispatchers // Of all listeners for that eventSource. } /// <summary> /// Flags that can be used with EventSource.GenerateManifest to control how the ETW manifest for the EventSource is /// generated. /// </summary> [Flags] public enum EventManifestOptions { /// <summary> /// Only the resources associated with current UI culture are included in the manifest /// </summary> None = 0x0, /// <summary> /// Throw exceptions for any inconsistency encountered /// </summary> Strict = 0x1, /// <summary> /// Generate a "resources" node under "localization" for every satellite assembly provided /// </summary> AllCultures = 0x2, /// <summary> /// Generate the manifest only if the event source needs to be registered on the machine, /// otherwise return null (but still perform validation if Strict is specified) /// </summary> OnlyIfNeededForRegistration = 0x4, /// <summary> /// When generating the manifest do *not* enforce the rule that the current EventSource class /// must be the base class for the user-defined type passed in. This allows validation of .net /// event sources using the new validation code /// </summary> AllowEventSourceOverride = 0x8, } /// <summary> /// ManifestBuilder is designed to isolate the details of the message of the event from the /// rest of EventSource. This one happens to create XML. /// </summary> internal sealed class ManifestBuilder { /// <summary> /// Build a manifest for 'providerName' with the given GUID, which will be packaged into 'dllName'. /// 'resources, is a resource manager. If specified all messages are localized using that manager. /// </summary> public ManifestBuilder(string providerName, Guid providerGuid, string? dllName, ResourceManager? resources, EventManifestOptions flags) { #if FEATURE_MANAGED_ETW_CHANNELS this.providerName = providerName; #endif this.flags = flags; this.resources = resources; sb = new StringBuilder(); events = new StringBuilder(); templates = new StringBuilder(); opcodeTab = new Dictionary<int, string>(); stringTab = new Dictionary<string, string>(); errors = new List<string>(); perEventByteArrayArgIndices = new Dictionary<string, List<int>>(); sb.AppendLine("<instrumentationManifest xmlns=\"http://schemas.microsoft.com/win/2004/08/events\">"); sb.AppendLine(" <instrumentation xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:win=\"http://manifests.microsoft.com/win/2004/08/windows/events\">"); sb.AppendLine(" <events xmlns=\"http://schemas.microsoft.com/win/2004/08/events\">"); sb.Append($"<provider name=\"{providerName}\" guid=\"{{{providerGuid}}}\""); if (dllName != null) sb.Append($" resourceFileName=\"{dllName}\" messageFileName=\"{dllName}\""); string symbolsName = providerName.Replace("-", "").Replace('.', '_'); // Period and - are illegal replace them. sb.AppendLine($" symbol=\"{symbolsName}\">"); } public void AddOpcode(string name, int value) { if ((flags & EventManifestOptions.Strict) != 0) { if (value <= 10 || value >= 239) { ManifestError(SR.Format(SR.EventSource_IllegalOpcodeValue, name, value)); } if (opcodeTab.TryGetValue(value, out string? prevName) && !name.Equals(prevName, StringComparison.Ordinal)) { ManifestError(SR.Format(SR.EventSource_OpcodeCollision, name, prevName, value)); } } opcodeTab[value] = name; } public void AddTask(string name, int value) { if ((flags & EventManifestOptions.Strict) != 0) { if (value <= 0 || value >= 65535) { ManifestError(SR.Format(SR.EventSource_IllegalTaskValue, name, value)); } if (taskTab != null && taskTab.TryGetValue(value, out string? prevName) && !name.Equals(prevName, StringComparison.Ordinal)) { ManifestError(SR.Format(SR.EventSource_TaskCollision, name, prevName, value)); } } taskTab ??= new Dictionary<int, string>(); taskTab[value] = name; } public void AddKeyword(string name, ulong value) { if ((value & (value - 1)) != 0) // Is it a power of 2? { ManifestError(SR.Format(SR.EventSource_KeywordNeedPowerOfTwo, "0x" + value.ToString("x", CultureInfo.CurrentCulture), name), true); } if ((flags & EventManifestOptions.Strict) != 0) { if (value >= 0x0000100000000000UL && !name.StartsWith("Session", StringComparison.Ordinal)) { ManifestError(SR.Format(SR.EventSource_IllegalKeywordsValue, name, "0x" + value.ToString("x", CultureInfo.CurrentCulture))); } if (keywordTab != null && keywordTab.TryGetValue(value, out string? prevName) && !name.Equals(prevName, StringComparison.Ordinal)) { ManifestError(SR.Format(SR.EventSource_KeywordCollision, name, prevName, "0x" + value.ToString("x", CultureInfo.CurrentCulture))); } } keywordTab ??= new Dictionary<ulong, string>(); keywordTab[value] = name; } #if FEATURE_MANAGED_ETW_CHANNELS /// <summary> /// Add a channel. channelAttribute can be null /// </summary> public void AddChannel(string? name, int value, EventChannelAttribute? channelAttribute) { EventChannel chValue = (EventChannel)value; if (value < (int)EventChannel.Admin || value > 255) ManifestError(SR.Format(SR.EventSource_EventChannelOutOfRange, name, value)); else if (chValue >= EventChannel.Admin && chValue <= EventChannel.Debug && channelAttribute != null && EventChannelToChannelType(chValue) != channelAttribute.EventChannelType) { // we want to ensure developers do not define EventChannels that conflict with the builtin ones, // but we want to allow them to override the default ones... ManifestError(SR.Format(SR.EventSource_ChannelTypeDoesNotMatchEventChannelValue, name, ((EventChannel)value).ToString())); } // TODO: validate there are no conflicting manifest exposed names (generally following the format "provider/type") ulong kwd = GetChannelKeyword(chValue); channelTab ??= new Dictionary<int, ChannelInfo>(4); channelTab[value] = new ChannelInfo { Name = name, Keywords = kwd, Attribs = channelAttribute }; } private static EventChannelType EventChannelToChannelType(EventChannel channel) { #if !ES_BUILD_STANDALONE Debug.Assert(channel >= EventChannel.Admin && channel <= EventChannel.Debug); #endif return (EventChannelType)((int)channel - (int)EventChannel.Admin + (int)EventChannelType.Admin); } private static EventChannelAttribute GetDefaultChannelAttribute(EventChannel channel) { EventChannelAttribute attrib = new EventChannelAttribute(); attrib.EventChannelType = EventChannelToChannelType(channel); if (attrib.EventChannelType <= EventChannelType.Operational) attrib.Enabled = true; return attrib; } public ulong[] GetChannelData() { if (this.channelTab == null) { return Array.Empty<ulong>(); } // We create an array indexed by the channel id for fast look up. // E.g. channelMask[Admin] will give you the bit mask for Admin channel. int maxkey = -1; foreach (int item in this.channelTab.Keys) { if (item > maxkey) { maxkey = item; } } ulong[] channelMask = new ulong[maxkey + 1]; foreach (KeyValuePair<int, ChannelInfo> item in this.channelTab) { channelMask[item.Key] = item.Value.Keywords; } return channelMask; } #endif public void StartEvent(string eventName, EventAttribute eventAttribute) { Debug.Assert(numParams == 0); Debug.Assert(this.eventName == null); this.eventName = eventName; numParams = 0; byteArrArgIndices = null; events.Append(" <event value=\"").Append(eventAttribute.EventId). Append("\" version=\"").Append(eventAttribute.Version). Append("\" level=\""); AppendLevelName(events, eventAttribute.Level); events.Append("\" symbol=\"").Append(eventName).Append('"'); // at this point we add to the manifest's stringTab a message that is as-of-yet // "untranslated to manifest convention", b/c we don't have the number or position // of any byte[] args (which require string format index updates) WriteMessageAttrib(events, "event", eventName, eventAttribute.Message); if (eventAttribute.Keywords != 0) { events.Append(" keywords=\""); AppendKeywords(events, (ulong)eventAttribute.Keywords, eventName); events.Append('"'); } if (eventAttribute.Opcode != 0) { events.Append(" opcode=\"").Append(GetOpcodeName(eventAttribute.Opcode, eventName)).Append('"'); } if (eventAttribute.Task != 0) { events.Append(" task=\"").Append(GetTaskName(eventAttribute.Task, eventName)).Append('"'); } #if FEATURE_MANAGED_ETW_CHANNELS if (eventAttribute.Channel != 0) { events.Append(" channel=\"").Append(GetChannelName(eventAttribute.Channel, eventName, eventAttribute.Message)).Append('"'); } #endif } public void AddEventParameter(Type type, string name) { if (numParams == 0) templates.Append(" <template tid=\"").Append(eventName).AppendLine("Args\">"); if (type == typeof(byte[])) { // mark this index as "extraneous" (it has no parallel in the managed signature) // we use these values in TranslateToManifestConvention() byteArrArgIndices ??= new List<int>(4); byteArrArgIndices.Add(numParams); // add an extra field to the template representing the length of the binary blob numParams++; templates.Append(" <data name=\"").Append(name).AppendLine("Size\" inType=\"win:UInt32\"/>"); } numParams++; templates.Append(" <data name=\"").Append(name).Append("\" inType=\"").Append(GetTypeName(type)).Append('"'); // TODO: for 'byte*' types it assumes the user provided length is named using the same naming convention // as for 'byte[]' args (blob_arg_name + "Size") if ((type.IsArray || type.IsPointer) && type.GetElementType() == typeof(byte)) { // add "length" attribute to the "blob" field in the template (referencing the field added above) templates.Append(" length=\"").Append(name).Append("Size\""); } // ETW does not support 64-bit value maps, so we don't specify these as ETW maps if (type.IsEnum && Enum.GetUnderlyingType(type) != typeof(ulong) && Enum.GetUnderlyingType(type) != typeof(long)) { templates.Append(" map=\"").Append(type.Name).Append('"'); mapsTab ??= new Dictionary<string, Type>(); if (!mapsTab.ContainsKey(type.Name)) mapsTab.Add(type.Name, type); // Remember that we need to dump the type enumeration } templates.AppendLine("/>"); } public void EndEvent() { Debug.Assert(eventName != null); if (numParams > 0) { templates.AppendLine(" </template>"); events.Append(" template=\"").Append(eventName).Append("Args\""); } events.AppendLine("/>"); if (byteArrArgIndices != null) perEventByteArrayArgIndices[eventName] = byteArrArgIndices; // at this point we have all the information we need to translate the C# Message // to the manifest string we'll put in the stringTab string prefixedEventName = "event_" + eventName; if (stringTab.TryGetValue(prefixedEventName, out string? msg)) { msg = TranslateToManifestConvention(msg, eventName); stringTab[prefixedEventName] = msg; } eventName = null; numParams = 0; byteArrArgIndices = null; } #if FEATURE_MANAGED_ETW_CHANNELS // Channel keywords are generated one per channel to allow channel based filtering in event viewer. These keywords are autogenerated // by mc.exe for compiling a manifest and are based on the order of the channels (fields) in the Channels inner class (when advanced // channel support is enabled), or based on the order the predefined channels appear in the EventAttribute properties (for simple // support). The manifest generated *MUST* have the channels specified in the same order (that's how our computed keywords are mapped // to channels by the OS infrastructure). // If channelKeyworkds is present, and has keywords bits in the ValidPredefinedChannelKeywords then it is // assumed that the keyword for that channel should be that bit. // otherwise we allocate a channel bit for the channel. // explicit channel bits are only used by WCF to mimic an existing manifest, // so we don't dont do error checking. public ulong GetChannelKeyword(EventChannel channel, ulong channelKeyword = 0) { // strip off any non-channel keywords, since we are only interested in channels here. channelKeyword &= ValidPredefinedChannelKeywords; channelTab ??= new Dictionary<int, ChannelInfo>(4); if (channelTab.Count == MaxCountChannels) ManifestError(SR.EventSource_MaxChannelExceeded); if (!channelTab.TryGetValue((int)channel, out ChannelInfo? info)) { // If we were not given an explicit channel, allocate one. if (channelKeyword == 0) { channelKeyword = nextChannelKeywordBit; nextChannelKeywordBit >>= 1; } } else { channelKeyword = info.Keywords; } return channelKeyword; } #endif public byte[] CreateManifest() { string str = CreateManifestString(); return Encoding.UTF8.GetBytes(str); } public IList<string> Errors => errors; public bool HasResources => resources != null; /// <summary> /// When validating an event source it adds the error to the error collection. /// When not validating it throws an exception if runtimeCritical is "true". /// Otherwise the error is ignored. /// </summary> /// <param name="msg"></param> /// <param name="runtimeCritical"></param> public void ManifestError(string msg, bool runtimeCritical = false) { if ((flags & EventManifestOptions.Strict) != 0) errors.Add(msg); else if (runtimeCritical) throw new ArgumentException(msg); } private string CreateManifestString() { #if !ES_BUILD_STANDALONE Span<char> ulongHexScratch = stackalloc char[16]; // long enough for ulong.MaxValue formatted as hex #endif #if FEATURE_MANAGED_ETW_CHANNELS // Write out the channels if (channelTab != null) { sb.AppendLine(" <channels>"); var sortedChannels = new List<KeyValuePair<int, ChannelInfo>>(); foreach (KeyValuePair<int, ChannelInfo> p in channelTab) { sortedChannels.Add(p); } sortedChannels.Sort((p1, p2) => -Comparer<ulong>.Default.Compare(p1.Value.Keywords, p2.Value.Keywords)); foreach (KeyValuePair<int, ChannelInfo> kvpair in sortedChannels) { int channel = kvpair.Key; ChannelInfo channelInfo = kvpair.Value; string? channelType = null; bool enabled = false; string? fullName = null; #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS string? isolation = null; string? access = null; #endif if (channelInfo.Attribs != null) { EventChannelAttribute attribs = channelInfo.Attribs; if (Enum.IsDefined(typeof(EventChannelType), attribs.EventChannelType)) channelType = attribs.EventChannelType.ToString(); enabled = attribs.Enabled; #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS if (attribs.ImportChannel != null) { fullName = attribs.ImportChannel; elementName = "importChannel"; } if (Enum.IsDefined(typeof(EventChannelIsolation), attribs.Isolation)) isolation = attribs.Isolation.ToString(); access = attribs.Access; #endif } fullName ??= providerName + "/" + channelInfo.Name; sb.Append(" <channel chid=\"").Append(channelInfo.Name).Append("\" name=\"").Append(fullName).Append('"'); Debug.Assert(channelInfo.Name != null); WriteMessageAttrib(sb, "channel", channelInfo.Name, null); sb.Append(" value=\"").Append(channel).Append('"'); if (channelType != null) sb.Append(" type=\"").Append(channelType).Append('"'); sb.Append(" enabled=\"").Append(enabled ? "true" : "false").Append('"'); #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS if (access != null) sb.Append(" access=\"").Append(access).Append("\""); if (isolation != null) sb.Append(" isolation=\"").Append(isolation).Append("\""); #endif sb.AppendLine("/>"); } sb.AppendLine(" </channels>"); } #endif // Write out the tasks if (taskTab != null) { sb.AppendLine(" <tasks>"); var sortedTasks = new List<int>(taskTab.Keys); sortedTasks.Sort(); foreach (int task in sortedTasks) { sb.Append(" <task"); WriteNameAndMessageAttribs(sb, "task", taskTab[task]); sb.Append(" value=\"").Append(task).AppendLine("\"/>"); } sb.AppendLine(" </tasks>"); } // Write out the maps // Scoping the call to enum GetFields to a local function to limit the linker suppression #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "Trimmer does not trim enums")] #endif static FieldInfo[] GetEnumFields(Type localEnumType) { Debug.Assert(localEnumType.IsEnum); return localEnumType.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static); } if (mapsTab != null) { sb.AppendLine(" <maps>"); foreach (Type enumType in mapsTab.Values) { bool isbitmap = EventSource.IsCustomAttributeDefinedHelper(enumType, typeof(FlagsAttribute), flags); string mapKind = isbitmap ? "bitMap" : "valueMap"; sb.Append(" <").Append(mapKind).Append(" name=\"").Append(enumType.Name).AppendLine("\">"); // write out each enum value FieldInfo[] staticFields = GetEnumFields(enumType); bool anyValuesWritten = false; foreach (FieldInfo staticField in staticFields) { object? constantValObj = staticField.GetRawConstantValue(); if (constantValObj != null) { ulong hexValue; if (constantValObj is ulong) hexValue = (ulong)constantValObj; // This is the only integer type that can't be represented by a long. else hexValue = (ulong)Convert.ToInt64(constantValObj); // Handles all integer types except ulong. // ETW requires all bitmap values to be powers of 2. Skip the ones that are not. // TODO: Warn people about the dropping of values. if (isbitmap && ((hexValue & (hexValue - 1)) != 0 || hexValue == 0)) continue; #if ES_BUILD_STANDALONE string hexValueFormatted = hexValue.ToString("x", CultureInfo.InvariantCulture); #else hexValue.TryFormat(ulongHexScratch, out int charsWritten, "x"); Span<char> hexValueFormatted = ulongHexScratch.Slice(0, charsWritten); #endif sb.Append(" <map value=\"0x").Append(hexValueFormatted).Append('"'); WriteMessageAttrib(sb, "map", enumType.Name + "." + staticField.Name, staticField.Name); sb.AppendLine("/>"); anyValuesWritten = true; } } // the OS requires that bitmaps and valuemaps have at least one value or it reject the whole manifest. // To avoid that put a 'None' entry if there are no other values. if (!anyValuesWritten) { sb.Append(" <map value=\"0x0\""); WriteMessageAttrib(sb, "map", enumType.Name + ".None", "None"); sb.AppendLine("/>"); } sb.Append(" </").Append(mapKind).AppendLine(">"); } sb.AppendLine(" </maps>"); } // Write out the opcodes sb.AppendLine(" <opcodes>"); var sortedOpcodes = new List<int>(opcodeTab.Keys); sortedOpcodes.Sort(); foreach (int opcode in sortedOpcodes) { sb.Append(" <opcode"); WriteNameAndMessageAttribs(sb, "opcode", opcodeTab[opcode]); sb.Append(" value=\"").Append(opcode).AppendLine("\"/>"); } sb.AppendLine(" </opcodes>"); // Write out the keywords if (keywordTab != null) { sb.AppendLine(" <keywords>"); var sortedKeywords = new List<ulong>(keywordTab.Keys); sortedKeywords.Sort(); foreach (ulong keyword in sortedKeywords) { sb.Append(" <keyword"); WriteNameAndMessageAttribs(sb, "keyword", keywordTab[keyword]); #if ES_BUILD_STANDALONE string keywordFormatted = keyword.ToString("x", CultureInfo.InvariantCulture); #else keyword.TryFormat(ulongHexScratch, out int charsWritten, "x"); Span<char> keywordFormatted = ulongHexScratch.Slice(0, charsWritten); #endif sb.Append(" mask=\"0x").Append(keywordFormatted).AppendLine("\"/>"); } sb.AppendLine(" </keywords>"); } sb.AppendLine(" <events>"); sb.Append(events); sb.AppendLine(" </events>"); sb.AppendLine(" <templates>"); if (templates.Length > 0) { sb.Append(templates); } else { // Work around a cornercase ETW issue where a manifest with no templates causes // ETW events to not get sent to their associated channel. sb.AppendLine(" <template tid=\"_empty\"></template>"); } sb.AppendLine(" </templates>"); sb.AppendLine("</provider>"); sb.AppendLine("</events>"); sb.AppendLine("</instrumentation>"); // Output the localization information. sb.AppendLine("<localization>"); var sortedStrings = new string[stringTab.Keys.Count]; stringTab.Keys.CopyTo(sortedStrings, 0); Array.Sort<string>(sortedStrings, 0, sortedStrings.Length); CultureInfo ci = CultureInfo.CurrentUICulture; sb.Append(" <resources culture=\"").Append(ci.Name).AppendLine("\">"); sb.AppendLine(" <stringTable>"); foreach (string stringKey in sortedStrings) { string? val = GetLocalizedMessage(stringKey, ci, etwFormat: true); sb.Append(" <string id=\"").Append(stringKey).Append("\" value=\"").Append(val).AppendLine("\"/>"); } sb.AppendLine(" </stringTable>"); sb.AppendLine(" </resources>"); sb.AppendLine("</localization>"); sb.AppendLine("</instrumentationManifest>"); return sb.ToString(); } #region private private void WriteNameAndMessageAttribs(StringBuilder stringBuilder, string elementName, string name) { stringBuilder.Append(" name=\"").Append(name).Append('"'); WriteMessageAttrib(sb, elementName, name, name); } private void WriteMessageAttrib(StringBuilder stringBuilder, string elementName, string name, string? value) { string? key = null; // See if the user wants things localized. if (resources != null) { // resource fallback: strings in the neutral culture will take precedence over inline strings key = elementName + "_" + name; if (resources.GetString(key, CultureInfo.InvariantCulture) is string localizedString) value = localizedString; } if (value == null) return; key ??= elementName + "_" + name; stringBuilder.Append(" message=\"$(string.").Append(key).Append(")\""); if (stringTab.TryGetValue(key, out string? prevValue) && !prevValue.Equals(value)) { ManifestError(SR.Format(SR.EventSource_DuplicateStringKey, key), true); return; } stringTab[key] = value; } internal string? GetLocalizedMessage(string key, CultureInfo ci, bool etwFormat) { string? value = null; if (resources != null) { string? localizedString = resources.GetString(key, ci); if (localizedString != null) { value = localizedString; if (etwFormat && key.StartsWith("event_", StringComparison.Ordinal)) { string evtName = key.Substring("event_".Length); value = TranslateToManifestConvention(value, evtName); } } } if (etwFormat && value == null) stringTab.TryGetValue(key, out value); return value; } private static void AppendLevelName(StringBuilder sb, EventLevel level) { if ((int)level < 16) { sb.Append("win:"); } sb.Append(level switch // avoid boxing that comes from level.ToString() { EventLevel.LogAlways => nameof(EventLevel.LogAlways), EventLevel.Critical => nameof(EventLevel.Critical), EventLevel.Error => nameof(EventLevel.Error), EventLevel.Warning => nameof(EventLevel.Warning), EventLevel.Informational => nameof(EventLevel.Informational), EventLevel.Verbose => nameof(EventLevel.Verbose), _ => ((int)level).ToString() }); } #if FEATURE_MANAGED_ETW_CHANNELS private string? GetChannelName(EventChannel channel, string eventName, string? eventMessage) { if (channelTab == null || !channelTab.TryGetValue((int)channel, out ChannelInfo? info)) { if (channel < EventChannel.Admin) // || channel > EventChannel.Debug) ManifestError(SR.Format(SR.EventSource_UndefinedChannel, channel, eventName)); // allow channels to be auto-defined. The well known ones get their well known names, and the // rest get names Channel<N>. This allows users to modify the Manifest if they want more advanced features. channelTab ??= new Dictionary<int, ChannelInfo>(4); string channelName = channel.ToString(); // For well know channels this is a nice name, otherwise a number if (EventChannel.Debug < channel) channelName = "Channel" + channelName; // Add a 'Channel' prefix for numbers. AddChannel(channelName, (int)channel, GetDefaultChannelAttribute(channel)); if (!channelTab.TryGetValue((int)channel, out info)) ManifestError(SR.Format(SR.EventSource_UndefinedChannel, channel, eventName)); } // events that specify admin channels *must* have non-null "Message" attributes if (resources != null) eventMessage ??= resources.GetString("event_" + eventName, CultureInfo.InvariantCulture); Debug.Assert(info!.Attribs != null); if (info.Attribs.EventChannelType == EventChannelType.Admin && eventMessage == null) ManifestError(SR.Format(SR.EventSource_EventWithAdminChannelMustHaveMessage, eventName, info.Name)); return info.Name; } #endif private string GetTaskName(EventTask task, string eventName) { if (task == EventTask.None) return ""; taskTab ??= new Dictionary<int, string>(); if (!taskTab.TryGetValue((int)task, out string? ret)) ret = taskTab[(int)task] = eventName; return ret; } private string? GetOpcodeName(EventOpcode opcode, string eventName) { switch (opcode) { case EventOpcode.Info: return "win:Info"; case EventOpcode.Start: return "win:Start"; case EventOpcode.Stop: return "win:Stop"; case EventOpcode.DataCollectionStart: return "win:DC_Start"; case EventOpcode.DataCollectionStop: return "win:DC_Stop"; case EventOpcode.Extension: return "win:Extension"; case EventOpcode.Reply: return "win:Reply"; case EventOpcode.Resume: return "win:Resume"; case EventOpcode.Suspend: return "win:Suspend"; case EventOpcode.Send: return "win:Send"; case EventOpcode.Receive: return "win:Receive"; } if (opcodeTab == null || !opcodeTab.TryGetValue((int)opcode, out string? ret)) { ManifestError(SR.Format(SR.EventSource_UndefinedOpcode, opcode, eventName), true); ret = null; } return ret; } private void AppendKeywords(StringBuilder sb, ulong keywords, string eventName) { #if FEATURE_MANAGED_ETW_CHANNELS // ignore keywords associate with channels // See ValidPredefinedChannelKeywords def for more. keywords &= ~ValidPredefinedChannelKeywords; #endif bool appended = false; for (ulong bit = 1; bit != 0; bit <<= 1) { if ((keywords & bit) != 0) { string? keyword = null; if ((keywordTab == null || !keywordTab.TryGetValue(bit, out keyword)) && (bit >= (ulong)0x1000000000000)) { // do not report Windows reserved keywords in the manifest (this allows the code // to be resilient to potential renaming of these keywords) keyword = string.Empty; } if (keyword == null) { ManifestError(SR.Format(SR.EventSource_UndefinedKeyword, "0x" + bit.ToString("x", CultureInfo.CurrentCulture), eventName), true); keyword = string.Empty; } if (keyword.Length != 0) { if (appended) { sb.Append(' '); } sb.Append(keyword); appended = true; } } } } private string GetTypeName(Type type) { if (type.IsEnum) { string typeName = GetTypeName(type.GetEnumUnderlyingType()); return typeName.Replace("win:Int", "win:UInt"); // ETW requires enums to be unsigned. } switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: return "win:Boolean"; case TypeCode.Byte: return "win:UInt8"; case TypeCode.Char: case TypeCode.UInt16: return "win:UInt16"; case TypeCode.UInt32: return "win:UInt32"; case TypeCode.UInt64: return "win:UInt64"; case TypeCode.SByte: return "win:Int8"; case TypeCode.Int16: return "win:Int16"; case TypeCode.Int32: return "win:Int32"; case TypeCode.Int64: return "win:Int64"; case TypeCode.String: return "win:UnicodeString"; case TypeCode.Single: return "win:Float"; case TypeCode.Double: return "win:Double"; case TypeCode.DateTime: return "win:FILETIME"; default: if (type == typeof(Guid)) return "win:GUID"; else if (type == typeof(IntPtr)) return "win:Pointer"; else if ((type.IsArray || type.IsPointer) && type.GetElementType() == typeof(byte)) return "win:Binary"; ManifestError(SR.Format(SR.EventSource_UnsupportedEventTypeInManifest, type.Name), true); return string.Empty; } } private static void UpdateStringBuilder([NotNull] ref StringBuilder? stringBuilder, string eventMessage, int startIndex, int count) { stringBuilder ??= new StringBuilder(); stringBuilder.Append(eventMessage, startIndex, count); } private static readonly string[] s_escapes = { "&amp;", "&lt;", "&gt;", "&apos;", "&quot;", "%r", "%n", "%t" }; // Manifest messages use %N conventions for their message substitutions. Translate from // .NET conventions. We can't use RegEx for this (we are in mscorlib), so we do it 'by hand' private string TranslateToManifestConvention(string eventMessage, string evtName) { StringBuilder? stringBuilder = null; // We lazily create this int writtenSoFar = 0; for (int i = 0; ;) { if (i >= eventMessage.Length) { if (stringBuilder == null) return eventMessage; UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar); return stringBuilder.ToString(); } int chIdx; if (eventMessage[i] == '%') { // handle format message escaping character '%' by escaping it UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar); stringBuilder.Append("%%"); i++; writtenSoFar = i; } else if (i < eventMessage.Length - 1 && (eventMessage[i] == '{' && eventMessage[i + 1] == '{' || eventMessage[i] == '}' && eventMessage[i + 1] == '}')) { // handle C# escaped '{" and '}' UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar); stringBuilder.Append(eventMessage[i]); i++; i++; writtenSoFar = i; } else if (eventMessage[i] == '{') { int leftBracket = i; i++; int argNum = 0; while (i < eventMessage.Length && char.IsDigit(eventMessage[i])) { argNum = argNum * 10 + eventMessage[i] - '0'; i++; } if (i < eventMessage.Length && eventMessage[i] == '}') { i++; UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, leftBracket - writtenSoFar); int manIndex = TranslateIndexToManifestConvention(argNum, evtName); stringBuilder.Append('%').Append(manIndex); // An '!' after the insert specifier {n} will be interpreted as a literal. // We'll escape it so that mc.exe does not attempt to consider it the // beginning of a format string. if (i < eventMessage.Length && eventMessage[i] == '!') { i++; stringBuilder.Append("%!"); } writtenSoFar = i; } else { ManifestError(SR.Format(SR.EventSource_UnsupportedMessageProperty, evtName, eventMessage)); } } else if ((chIdx = "&<>'\"\r\n\t".IndexOf(eventMessage[i])) >= 0) { UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar); i++; stringBuilder.Append(s_escapes[chIdx]); writtenSoFar = i; } else i++; } } private int TranslateIndexToManifestConvention(int idx, string evtName) { if (perEventByteArrayArgIndices.TryGetValue(evtName, out List<int>? byteArrArgIndices)) { foreach (int byArrIdx in byteArrArgIndices) { if (idx >= byArrIdx) ++idx; else break; } } return idx + 1; } #if FEATURE_MANAGED_ETW_CHANNELS private sealed class ChannelInfo { public string? Name; public ulong Keywords; public EventChannelAttribute? Attribs; } #endif private readonly Dictionary<int, string> opcodeTab; private Dictionary<int, string>? taskTab; #if FEATURE_MANAGED_ETW_CHANNELS private Dictionary<int, ChannelInfo>? channelTab; #endif private Dictionary<ulong, string>? keywordTab; private Dictionary<string, Type>? mapsTab; private readonly Dictionary<string, string> stringTab; // Maps unlocalized strings to localized ones #if FEATURE_MANAGED_ETW_CHANNELS // WCF used EventSource to mimic a existing ETW manifest. To support this // in just their case, we allowed them to specify the keywords associated // with their channels explicitly. ValidPredefinedChannelKeywords is // this set of channel keywords that we allow to be explicitly set. You // can ignore these bits otherwise. internal const ulong ValidPredefinedChannelKeywords = 0xF000000000000000; private ulong nextChannelKeywordBit = 0x8000000000000000; // available Keyword bit to be used for next channel definition, grows down private const int MaxCountChannels = 8; // a manifest can defined at most 8 ETW channels #endif private readonly StringBuilder sb; // Holds the provider information. private readonly StringBuilder events; // Holds the events. private readonly StringBuilder templates; #if FEATURE_MANAGED_ETW_CHANNELS private readonly string providerName; #endif private readonly ResourceManager? resources; // Look up localized strings here. private readonly EventManifestOptions flags; private readonly IList<string> errors; // list of currently encountered errors private readonly Dictionary<string, List<int>> perEventByteArrayArgIndices; // "event_name" -> List_of_Indices_of_Byte[]_Arg // State we track between StartEvent and EndEvent. private string? eventName; // Name of the event currently being processed. private int numParams; // keeps track of the number of args the event has. private List<int>? byteArrArgIndices; // keeps track of the index of each byte[] argument #endregion } /// <summary> /// Used to send the m_rawManifest into the event dispatcher as a series of events. /// </summary> internal struct ManifestEnvelope { public const int MaxChunkSize = 0xFF00; public enum ManifestFormats : byte { SimpleXmlFormat = 1, // simply dump the XML manifest as UTF8 } #if FEATURE_MANAGED_ETW public ManifestFormats Format; public byte MajorVersion; public byte MinorVersion; public byte Magic; public ushort TotalChunks; public ushort ChunkNumber; #endif } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // This program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in. // It is available from http://www.codeplex.com/hyperAddin #if ES_BUILD_STANDALONE #define FEATURE_MANAGED_ETW_CHANNELS // #define FEATURE_ADVANCED_MANAGED_ETW_CHANNELS #endif /* DESIGN NOTES DESIGN NOTES DESIGN NOTES DESIGN NOTES */ // DESIGN NOTES // Over the years EventSource has become more complex and so it is important to understand // the basic structure of the code to insure that it does not grow more complex. // // Basic Model // // PRINCIPLE: EventSource - ETW decoupling // // Conceptually an EventSouce is something that takes event logging data from the source methods // to the EventListener that can subscribe to them. Note that CONCEPTUALLY EVENTSOURCES DON'T // KNOW ABOUT ETW!. The MODEL of the system is that there is a special EventListener which // we will call the EtwEventListener, that forwards commands from ETW to EventSources and // listens to EventSources and forwards on those events to ETW. Thus the model should // be that you DON'T NEED ETW. // // Now in actual practice, EventSouce have rather intimate knowledge of ETW and send events // to it directly, but this can be VIEWED AS AN OPTIMIZATION. // // Basic Event Data Flow: // // There are two ways for event Data to enter the system // 1) WriteEvent* and friends. This is called the 'contract' based approach because // you write a method per event which forms a contract that is know at compile time. // In this scheme each event is given an EVENTID (small integer), which is its identity // 2) Write<T> methods. This is called the 'dynamic' approach because new events // can be created on the fly. Event identity is determined by the event NAME, and these // are not quite as efficient at runtime since you have at least a hash table lookup // on every event write. // // EventSource-EventListener transfer fully supports both ways of writing events (either contract // based (WriteEvent*) or dynamic (Write<T>)). Both ways fully support the same set of data // types. It is recommended, however, that you use the contract based approach when the event scheme // is known at compile time (that is whenever possible). It is more efficient, but more importantly // it makes the contract very explicit, and centralizes all policy about logging. These are good // things. The Write<T> API is really meant for more ad-hoc cases. // // Allowed Data: // // Note that EventSource-EventListeners have a conceptual serialization-deserialization that happens // during the transfer. In particular object identity is not preserved, some objects are morphed, // and not all data types are supported. In particular you can pass // // A Valid type to log to an EventSource include // * Primitive data types // * IEnumerable<T> of valid types T (this include arrays) (* New for V4.6) // * Explicitly Opted in class or struct with public property Getters over Valid types. (* New for V4.6) // // This set of types is roughly a generalization of JSON support (basically primitives, bags, and arrays). // // Explicitly allowed structs include (* New for V4.6) // * Marked with the EventData attribute // * implicitly defined (e.g the C# new {x = 3, y = 5} syntax) // * KeyValuePair<K,V> (thus dictionaries can be passed since they are an IEnumerable of KeyValuePair) // // When classes are returned in an EventListener, what is returned is something that implements // IDictionary<string, T>. Thus when objects are passed to an EventSource they are transformed // into a key-value bag (the IDictionary<string, T>) for consumption in the listener. These // are obviously NOT the original objects. // // ETW serialization formats: // // As mentioned, conceptually EventSources send data to EventListeners and there is a conceptual // copy/morph of that data as described above. In addition the .NET framework supports a conceptual // ETWListener that will send the data to the ETW stream. If you use this feature, the data needs // to be serialized in a way that ETW supports. ETW supports the following serialization formats // // 1) Manifest Based serialization. // 2) SelfDescribing serialization (TraceLogging style in the TraceLogging directory) // // A key factor is that the Write<T> method, which supports on the fly definition of events, can't // support the manifest based serialization because the manifest needs the schema of all events // to be known before any events are emitted. This implies the following: // // If you use Write<T> and the output goes to ETW it will use the SelfDescribing format. // If you use the EventSource(string) constructor for an eventSource (in which you don't // create a subclass), the default is also to use Self-Describing serialization. In addition // you can use the EventSoruce(EventSourceSettings) constructor to also explicitly specify // Self-Describing serialization format. These affect the WriteEvent* APIs going to ETW. // // Note that none of this ETW serialization logic affects EventListeners. Only the ETW listener. // // ************************************************************************************* // *** INTERNALS: Event Propagation // // Data enters the system either though // // 1) A user defined method in the user defined subclass of EventSource which calls // A) A typesafe type specific overload of WriteEvent(ID, ...) e.g. WriteEvent(ID, string, string) // * which calls into the unsafe WriteEventCore(ID COUNT EventData*) WriteEventWithRelatedActivityIdCore() // B) The typesafe overload WriteEvent(ID, object[]) which calls the private helper WriteEventVarargs(ID, Guid* object[]) // C) Directly into the unsafe WriteEventCore(ID, COUNT EventData*) or WriteEventWithRelatedActivityIdCore() // // All event data eventually flows to one of // * WriteEventWithRelatedActivityIdCore(ID, Guid*, COUNT, EventData*) // * WriteEventVarargs(ID, Guid*, object[]) // // 2) A call to one of the overloads of Write<T>. All these overloads end up in // * WriteImpl<T>(EventName, Options, Data, Guid*, Guid*) // // On output there are the following routines // Writing to all listeners that are NOT ETW, we have the following routines // * WriteToAllListeners(ID, Guid*, Guid*, COUNT, EventData*) // * WriteToAllListeners(ID, Guid*, Guid*, object[]) // * WriteToAllListeners(NAME, Guid*, Guid*, EventPayload) // // EventPayload is the internal type that implements the IDictionary<string, object> interface // The EventListeners will pass back for serialized classes for nested object, but // WriteToAllListeners(NAME, Guid*, Guid*, EventPayload) unpacks this and uses the fields as if they // were parameters to a method. // // The first two are used for the WriteEvent* case, and the later is used for the Write<T> case. // // Writing to ETW, Manifest Based // EventProvider.WriteEvent(EventDescriptor, Guid*, COUNT, EventData*) // EventProvider.WriteEvent(EventDescriptor, Guid*, object[]) // Writing to ETW, Self-Describing format // WriteMultiMerge(NAME, Options, Types, EventData*) // WriteMultiMerge(NAME, Options, Types, object[]) // WriteImpl<T> has logic that knows how to serialize (like WriteMultiMerge) but also knows // where it will write it to // // All ETW writes eventually call // EventWriteTransfer // EventProvider.WriteEventRaw - sets last error // EventSource.WriteEventRaw - Does EventSource exception handling logic // WriteMultiMerge // WriteImpl<T> // EventProvider.WriteEvent(EventDescriptor, Guid*, COUNT, EventData*) // EventProvider.WriteEvent(EventDescriptor, Guid*, object[]) // // Serialization: We have a bit of a hodge-podge of serializers right now. Only the one for ETW knows // how to deal with nested classes or arrays. I will call this serializer the 'TypeInfo' serializer // since it is the TraceLoggingTypeInfo structure that knows how to do this. Effectively for a type you // can call one of these // WriteMetadata - transforms the type T into serialization meta data blob for that type // WriteObjectData - transforms an object of T into serialization data blob for that instance // GetData - transforms an object of T into its deserialized form suitable for passing to EventListener. // The first two are used to serialize something for ETW. The second one is used to transform the object // for use by the EventListener. We also have a 'DecodeObject' method that will take a EventData* and // deserialize to pass to an EventListener, but it only works on primitive types (types supported in version V4.5). // // It is an important observation that while EventSource does support users directly calling with EventData* // blobs, we ONLY support that for the primitive types (V4.5 level support). Thus while there is a EventData* // path through the system it is only for some types. The object[] path is the more general (but less efficient) path. // // TODO There is cleanup needed There should be no divergence until WriteEventRaw. // // TODO: We should have a single choke point (right now we always have this parallel EventData* and object[] path. This // was historical (at one point we tried to pass object directly from EventSoruce to EventListener. That was always // fragile and a compatibility headache, but we have finally been forced into the idea that there is always a transformation. // This allows us to use the EventData* form to be the canonical data format in the low level APIs. This also gives us the // opportunity to expose this format to EventListeners in the future. // using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Numerics; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; #if ES_BUILD_STANDALONE using System.Security.Permissions; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing { #else namespace System.Diagnostics.Tracing { [Conditional("NEEDED_FOR_SOURCE_GENERATOR_ONLY")] [AttributeUsage(AttributeTargets.Class)] internal sealed class EventSourceAutoGenerateAttribute : Attribute { } #endif /// <summary> /// This class is meant to be inherited by a user-defined event source in order to define a managed /// ETW provider. Please See DESIGN NOTES above for the internal architecture. /// The minimal definition of an EventSource simply specifies a number of ETW event methods that /// call one of the EventSource.WriteEvent overloads, <see cref="EventSource.WriteEventCore"/>, /// or <see cref="EventSource.WriteEventWithRelatedActivityIdCore"/> to log them. This functionality /// is sufficient for many users. /// <para> /// To achieve more control over the ETW provider manifest exposed by the event source type, the /// [<see cref="EventAttribute"/>] attributes can be specified for the ETW event methods. /// </para><para> /// For very advanced EventSources, it is possible to intercept the commands being given to the /// eventSource and change what filtering is done (see EventListener.EnableEvents and /// <see cref="EventListener.DisableEvents"/>) or cause actions to be performed by the eventSource, /// e.g. dumping a data structure (see EventSource.SendCommand and /// <see cref="EventSource.OnEventCommand"/>). /// </para><para> /// The eventSources can be turned on with Windows ETW controllers (e.g. logman), immediately. /// It is also possible to control and intercept the data dispatcher programmatically. See /// <see cref="EventListener"/> for more. /// </para> /// </summary> /// <remarks> /// This is a minimal definition for a custom event source: /// <code> /// [EventSource(Name="Samples.Demos.Minimal")] /// sealed class MinimalEventSource : EventSource /// { /// public static MinimalEventSource Log = new MinimalEventSource(); /// public void Load(long ImageBase, string Name) { WriteEvent(1, ImageBase, Name); } /// public void Unload(long ImageBase) { WriteEvent(2, ImageBase); } /// private MinimalEventSource() {} /// } /// </code> /// </remarks> #if !ES_BUILD_STANDALONE // The EnsureDescriptorsInitialized() method might need to access EventSource and its derived type // members and the trimmer ensures that these members are preserved. [DynamicallyAccessedMembers(ManifestMemberTypes)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2113:ReflectionToRequiresUnreferencedCode", Justification = "EnsureDescriptorsInitialized's use of GetType preserves methods on Delegate and MulticastDelegate " + "because the nested type OverrideEventProvider's base type EventProvider defines a delegate. " + "This includes Delegate and MulticastDelegate methods which require unreferenced code, but " + "EnsureDescriptorsInitialized does not access these members and is safe to call.")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2115:ReflectionToDynamicallyAccessedMembers", Justification = "EnsureDescriptorsInitialized's use of GetType preserves methods on Delegate and MulticastDelegate " + "because the nested type OverrideEventProvider's base type EventProvider defines a delegate. " + "This includes Delegate and MulticastDelegate methods which have dynamically accessed members requirements, but " + "EnsureDescriptorsInitialized does not access these members and is safe to call.")] #endif public partial class EventSource : IDisposable { internal static bool IsSupported { get; } = InitializeIsSupported(); private static bool InitializeIsSupported() => AppContext.TryGetSwitch("System.Diagnostics.Tracing.EventSource.IsSupported", out bool isSupported) ? isSupported : true; #if FEATURE_EVENTSOURCE_XPLAT #pragma warning disable CA1823 // field is used to keep listener alive private static readonly EventListener? persistent_Xplat_Listener = IsSupported ? XplatEventLogger.InitializePersistentListener() : null; #pragma warning restore CA1823 #endif //FEATURE_EVENTSOURCE_XPLAT /// <summary> /// The human-friendly name of the eventSource. It defaults to the simple name of the class /// </summary> public string Name => m_name; /// <summary> /// Every eventSource is assigned a GUID to uniquely identify it to the system. /// </summary> public Guid Guid => m_guid; /// <summary> /// Returns true if the eventSource has been enabled at all. This is the preferred test /// to be performed before a relatively expensive EventSource operation. /// </summary> public bool IsEnabled() { return m_eventSourceEnabled; } /// <summary> /// Returns true if events with greater than or equal 'level' and have one of 'keywords' set are enabled. /// /// Note that the result of this function is only an approximation on whether a particular /// event is active or not. It is only meant to be used as way of avoiding expensive /// computation for logging when logging is not on, therefore it sometimes returns false /// positives (but is always accurate when returning false). EventSources are free to /// have additional filtering. /// </summary> public bool IsEnabled(EventLevel level, EventKeywords keywords) { return IsEnabled(level, keywords, EventChannel.None); } /// <summary> /// Returns true if events with greater than or equal 'level' and have one of 'keywords' set are enabled, or /// if 'keywords' specifies a channel bit for a channel that is enabled. /// /// Note that the result of this function only an approximation on whether a particular /// event is active or not. It is only meant to be used as way of avoiding expensive /// computation for logging when logging is not on, therefore it sometimes returns false /// positives (but is always accurate when returning false). EventSources are free to /// have additional filtering. /// </summary> public bool IsEnabled(EventLevel level, EventKeywords keywords, EventChannel channel) { if (!IsEnabled()) return false; if (!IsEnabledCommon(m_eventSourceEnabled, m_level, m_matchAnyKeyword, level, keywords, channel)) return false; return true; } /// <summary> /// Returns the settings for the event source instance /// </summary> public EventSourceSettings Settings => m_config; // Manifest support /// <summary> /// Returns the GUID that uniquely identifies the eventSource defined by 'eventSourceType'. /// This API allows you to compute this without actually creating an instance of the EventSource. /// It only needs to reflect over the type. /// </summary> public static Guid GetGuid(Type eventSourceType) { if (eventSourceType == null) throw new ArgumentNullException(nameof(eventSourceType)); EventSourceAttribute? attrib = (EventSourceAttribute?)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute)); string name = eventSourceType.Name; if (attrib != null) { if (attrib.Guid != null) { if (Guid.TryParse(attrib.Guid, out Guid g)) return g; } if (attrib.Name != null) name = attrib.Name; } if (name == null) { throw new ArgumentException(SR.Argument_InvalidTypeName, nameof(eventSourceType)); } return GenerateGuidFromName(name.ToUpperInvariant()); // Make it case insensitive. } /// <summary> /// Returns the official ETW Provider name for the eventSource defined by 'eventSourceType'. /// This API allows you to compute this without actually creating an instance of the EventSource. /// It only needs to reflect over the type. /// </summary> public static string GetName(Type eventSourceType) { return GetName(eventSourceType, EventManifestOptions.None); } #if !ES_BUILD_STANDALONE private const DynamicallyAccessedMemberTypes ManifestMemberTypes = DynamicallyAccessedMemberTypes.All; #endif /// <summary> /// Returns a string of the XML manifest associated with the eventSourceType. The scheme for this XML is /// documented at in EventManifest Schema https://docs.microsoft.com/en-us/windows/desktop/WES/eventmanifestschema-schema. /// This is the preferred way of generating a manifest to be embedded in the ETW stream as it is fast and /// the fact that it only includes localized entries for the current UI culture is an acceptable tradeoff. /// </summary> /// <param name="eventSourceType">The type of the event source class for which the manifest is generated</param> /// <param name="assemblyPathToIncludeInManifest">The manifest XML fragment contains the string name of the DLL name in /// which it is embedded. This parameter specifies what name will be used</param> /// <returns>The XML data string</returns> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2114:ReflectionToDynamicallyAccessedMembers", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "has dynamically accessed members requirements, but EnsureDescriptorsInitialized does not "+ "access this member and is safe to call.")] #endif public static string? GenerateManifest( #if !ES_BUILD_STANDALONE [DynamicallyAccessedMembers(ManifestMemberTypes)] #endif Type eventSourceType, string? assemblyPathToIncludeInManifest) { return GenerateManifest(eventSourceType, assemblyPathToIncludeInManifest, EventManifestOptions.None); } /// <summary> /// Returns a string of the XML manifest associated with the eventSourceType. The scheme for this XML is /// documented at in EventManifest Schema https://docs.microsoft.com/en-us/windows/desktop/WES/eventmanifestschema-schema. /// Pass EventManifestOptions.AllCultures when generating a manifest to be registered on the machine. This /// ensures that the entries in the event log will be "optimally" localized. /// </summary> /// <param name="eventSourceType">The type of the event source class for which the manifest is generated</param> /// <param name="assemblyPathToIncludeInManifest">The manifest XML fragment contains the string name of the DLL name in /// which it is embedded. This parameter specifies what name will be used</param> /// <param name="flags">The flags to customize manifest generation. If flags has bit OnlyIfNeededForRegistration specified /// this returns null when the eventSourceType does not require explicit registration</param> /// <returns>The XML data string or null</returns> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2114:ReflectionToDynamicallyAccessedMembers", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "has dynamically accessed members requirements, but EnsureDescriptorsInitialized does not "+ "access this member and is safe to call.")] #endif public static string? GenerateManifest( #if !ES_BUILD_STANDALONE [DynamicallyAccessedMembers(ManifestMemberTypes)] #endif Type eventSourceType, string? assemblyPathToIncludeInManifest, EventManifestOptions flags) { if (!IsSupported) { return null; } if (eventSourceType == null) throw new ArgumentNullException(nameof(eventSourceType)); byte[]? manifestBytes = EventSource.CreateManifestAndDescriptors(eventSourceType, assemblyPathToIncludeInManifest, null, flags); return (manifestBytes == null) ? null : Encoding.UTF8.GetString(manifestBytes, 0, manifestBytes.Length); } // EventListener support /// <summary> /// returns a list (IEnumerable) of all sources in the appdomain). EventListeners typically need this. /// </summary> /// <returns></returns> public static IEnumerable<EventSource> GetSources() { if (!IsSupported) { return Array.Empty<EventSource>(); } var ret = new List<EventSource>(); lock (EventListener.EventListenersLock) { Debug.Assert(EventListener.s_EventSources != null); foreach (WeakReference<EventSource> eventSourceRef in EventListener.s_EventSources) { if (eventSourceRef.TryGetTarget(out EventSource? eventSource) && !eventSource.IsDisposed) ret.Add(eventSource); } } return ret; } /// <summary> /// Send a command to a particular EventSource identified by 'eventSource'. /// Calling this routine simply forwards the command to the EventSource.OnEventCommand /// callback. What the EventSource does with the command and its arguments are from /// that point EventSource-specific. /// </summary> /// <param name="eventSource">The instance of EventSource to send the command to</param> /// <param name="command">A positive user-defined EventCommand, or EventCommand.SendManifest</param> /// <param name="commandArguments">A set of (name-argument, value-argument) pairs associated with the command</param> public static void SendCommand(EventSource eventSource, EventCommand command, IDictionary<string, string?>? commandArguments) { if (!IsSupported) { return; } if (eventSource is null) { throw new ArgumentNullException(nameof(eventSource)); } // User-defined EventCommands should not conflict with the reserved commands. if ((int)command <= (int)EventCommand.Update && (int)command != (int)EventCommand.SendManifest) { throw new ArgumentException(SR.EventSource_InvalidCommand, nameof(command)); } eventSource.SendCommand(null, EventProviderType.ETW, 0, 0, command, true, EventLevel.LogAlways, EventKeywords.None, commandArguments); } // Error APIs. (We don't throw by default, but you can probe for status) /// <summary> /// Because /// /// 1) Logging is often optional and thus should not generate fatal errors (exceptions) /// 2) EventSources are often initialized in class constructors (which propagate exceptions poorly) /// /// The event source constructor does not throw exceptions. Instead we remember any exception that /// was generated (it is also logged to Trace.WriteLine). /// </summary> public Exception? ConstructionException => m_constructionException; /// <summary> /// EventSources can have arbitrary string key-value pairs associated with them called Traits. /// These traits are not interpreted by the EventSource but may be interpreted by EventListeners /// (e.g. like the built in ETW listener). These traits are specified at EventSource /// construction time and can be retrieved by using this GetTrait API. /// </summary> /// <param name="key">The key to look up in the set of key-value pairs passed to the EventSource constructor</param> /// <returns>The value string associated with key. Will return null if there is no such key.</returns> public string? GetTrait(string key) { if (m_traits != null) { for (int i = 0; i < m_traits.Length - 1; i += 2) { if (m_traits[i] == key) return m_traits[i + 1]; } } return null; } /// <summary> /// Displays the name and GUID for the eventSource for debugging purposes. /// </summary> public override string ToString() { if (!IsSupported) return base.ToString()!; return SR.Format(SR.EventSource_ToString, Name, Guid); } /// <summary> /// Fires when a Command (e.g. Enable) comes from a an EventListener. /// </summary> public event EventHandler<EventCommandEventArgs>? EventCommandExecuted { add { if (value == null) return; m_eventCommandExecuted += value; // If we have an EventHandler<EventCommandEventArgs> attached to the EventSource before the first command arrives // It should get a chance to handle the deferred commands. EventCommandEventArgs? deferredCommands = m_deferredCommands; while (deferredCommands != null) { value(this, deferredCommands); deferredCommands = deferredCommands.nextCommand; } } remove { m_eventCommandExecuted -= value; } } #region ActivityID /// <summary> /// When a thread starts work that is on behalf of 'something else' (typically another /// thread or network request) it should mark the thread as working on that other work. /// This API marks the current thread as working on activity 'activityID'. This API /// should be used when the caller knows the thread's current activity (the one being /// overwritten) has completed. Otherwise, callers should prefer the overload that /// return the oldActivityThatWillContinue (below). /// /// All events created with the EventSource on this thread are also tagged with the /// activity ID of the thread. /// /// It is common, and good practice after setting the thread to an activity to log an event /// with a 'start' opcode to indicate that precise time/thread where the new activity /// started. /// </summary> /// <param name="activityId">A Guid that represents the new activity with which to mark /// the current thread</param> public static void SetCurrentThreadActivityId(Guid activityId) { if (!IsSupported) { return; } if (TplEventSource.Log != null) TplEventSource.Log.SetActivityId(activityId); // We ignore errors to keep with the convention that EventSources do not throw errors. // Note we can't access m_throwOnWrites because this is a static method. #if FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING // Set the activity id via EventPipe. EventPipeEventProvider.EventActivityIdControl( Interop.Advapi32.ActivityControl.EVENT_ACTIVITY_CTRL_SET_ID, ref activityId); #endif // FEATURE_PERFTRACING #if TARGET_WINDOWS // Set the activity id via ETW. Interop.Advapi32.EventActivityIdControl( Interop.Advapi32.ActivityControl.EVENT_ACTIVITY_CTRL_SET_ID, ref activityId); #endif // TARGET_WINDOWS #endif // FEATURE_MANAGED_ETW } /// <summary> /// Retrieves the ETW activity ID associated with the current thread. /// </summary> public static Guid CurrentThreadActivityId { get { if (!IsSupported) { return default; } // We ignore errors to keep with the convention that EventSources do not throw // errors. Note we can't access m_throwOnWrites because this is a static method. Guid retVal = default; #if FEATURE_MANAGED_ETW #if TARGET_WINDOWS Interop.Advapi32.EventActivityIdControl( Interop.Advapi32.ActivityControl.EVENT_ACTIVITY_CTRL_GET_ID, ref retVal); #elif FEATURE_PERFTRACING EventPipeEventProvider.EventActivityIdControl( Interop.Advapi32.ActivityControl.EVENT_ACTIVITY_CTRL_GET_ID, ref retVal); #endif // TARGET_WINDOWS #endif // FEATURE_MANAGED_ETW return retVal; } } /// <summary> /// When a thread starts work that is on behalf of 'something else' (typically another /// thread or network request) it should mark the thread as working on that other work. /// This API marks the current thread as working on activity 'activityID'. It returns /// whatever activity the thread was previously marked with. There is a convention that /// callers can assume that callees restore this activity mark before the callee returns. /// To encourage this, this API returns the old activity, so that it can be restored later. /// /// All events created with the EventSource on this thread are also tagged with the /// activity ID of the thread. /// /// It is common, and good practice after setting the thread to an activity to log an event /// with a 'start' opcode to indicate that precise time/thread where the new activity /// started. /// </summary> /// <param name="activityId">A Guid that represents the new activity with which to mark /// the current thread</param> /// <param name="oldActivityThatWillContinue">The Guid that represents the current activity /// which will continue at some point in the future, on the current thread</param> public static void SetCurrentThreadActivityId(Guid activityId, out Guid oldActivityThatWillContinue) { if (!IsSupported) { oldActivityThatWillContinue = default; return; } oldActivityThatWillContinue = activityId; #if FEATURE_MANAGED_ETW // We ignore errors to keep with the convention that EventSources do not throw errors. // Note we can't access m_throwOnWrites because this is a static method. #if FEATURE_PERFTRACING && TARGET_WINDOWS EventPipeEventProvider.EventActivityIdControl( Interop.Advapi32.ActivityControl.EVENT_ACTIVITY_CTRL_SET_ID, ref oldActivityThatWillContinue); #elif FEATURE_PERFTRACING EventPipeEventProvider.EventActivityIdControl( Interop.Advapi32.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID, ref oldActivityThatWillContinue); #endif // FEATURE_PERFTRACING && TARGET_WINDOWS #if TARGET_WINDOWS Interop.Advapi32.EventActivityIdControl( Interop.Advapi32.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID, ref oldActivityThatWillContinue); #endif // TARGET_WINDOWS #endif // FEATURE_MANAGED_ETW // We don't call the activityDying callback here because the caller has declared that // it is not dying. if (TplEventSource.Log != null) TplEventSource.Log.SetActivityId(activityId); } #endregion #region protected /// <summary> /// This is the constructor that most users will use to create their eventSource. It takes /// no parameters. The ETW provider name and GUID of the EventSource are determined by the EventSource /// custom attribute (so you can determine these things declaratively). If the GUID for the eventSource /// is not specified in the EventSourceAttribute (recommended), it is Generated by hashing the name. /// If the ETW provider name of the EventSource is not given, the name of the EventSource class is used as /// the ETW provider name. /// </summary> protected EventSource() : this(EventSourceSettings.EtwManifestEventFormat) { } /// <summary> /// By default calling the 'WriteEvent' methods do NOT throw on errors (they silently discard the event). /// This is because in most cases users assume logging is not 'precious' and do NOT wish to have logging failures /// crash the program. However for those applications where logging is 'precious' and if it fails the caller /// wishes to react, setting 'throwOnEventWriteErrors' will cause an exception to be thrown if WriteEvent /// fails. Note the fact that EventWrite succeeds does not necessarily mean that the event reached its destination /// only that operation of writing it did not fail. These EventSources will not generate self-describing ETW events. /// /// For compatibility only use the EventSourceSettings.ThrowOnEventWriteErrors flag instead. /// </summary> // [Obsolete("Use the EventSource(EventSourceSettings) overload")] protected EventSource(bool throwOnEventWriteErrors) : this(EventSourceSettings.EtwManifestEventFormat | (throwOnEventWriteErrors ? EventSourceSettings.ThrowOnEventWriteErrors : 0)) { } /// <summary> /// Construct an EventSource with additional non-default settings (see EventSourceSettings for more) /// </summary> protected EventSource(EventSourceSettings settings) : this(settings, null) { } /// <summary> /// Construct an EventSource with additional non-default settings. /// /// Also specify a list of key-value pairs called traits (you must pass an even number of strings). /// The first string is the key and the second is the value. These are not interpreted by EventSource /// itself but may be interpreted the listeners. Can be fetched with GetTrait(string). /// </summary> /// <param name="settings">See EventSourceSettings for more.</param> /// <param name="traits">A collection of key-value strings (must be an even number).</param> protected EventSource(EventSourceSettings settings, params string[]? traits) { if (IsSupported) { #if FEATURE_PERFTRACING m_eventHandleTable = new TraceLoggingEventHandleTable(); #endif m_config = ValidateSettings(settings); Type myType = this.GetType(); Guid eventSourceGuid = GetGuid(myType); string eventSourceName = GetName(myType); Initialize(eventSourceGuid, eventSourceName, traits); } } #if FEATURE_PERFTRACING // Generate the serialized blobs that describe events for all strongly typed events (that is events that define strongly // typed event methods. Dynamically defined events (that use Write) hare defined on the fly and are handled elsewhere. private unsafe void DefineEventPipeEvents() { // If the EventSource is set to emit all events as TraceLogging events, skip this initialization. // Events will be defined when they are emitted for the first time. if (SelfDescribingEvents) { return; } Debug.Assert(m_eventData != null); Debug.Assert(m_eventPipeProvider != null); int cnt = m_eventData.Length; for (int i = 0; i < cnt; i++) { uint eventID = (uint)m_eventData[i].Descriptor.EventId; if (eventID == 0) continue; byte[]? metadata = EventPipeMetadataGenerator.Instance.GenerateEventMetadata(m_eventData[i]); uint metadataLength = (metadata != null) ? (uint)metadata.Length : 0; string eventName = m_eventData[i].Name; long keywords = m_eventData[i].Descriptor.Keywords; uint eventVersion = m_eventData[i].Descriptor.Version; uint level = m_eventData[i].Descriptor.Level; fixed (byte *pMetadata = metadata) { IntPtr eventHandle = m_eventPipeProvider.m_eventProvider.DefineEventHandle( eventID, eventName, keywords, eventVersion, level, pMetadata, metadataLength); Debug.Assert(eventHandle != IntPtr.Zero); m_eventData[i].EventHandle = eventHandle; } } } #endif /// <summary> /// This method is called when the eventSource is updated by the controller. /// </summary> protected virtual void OnEventCommand(EventCommandEventArgs command) { } #pragma warning disable 1591 // optimized for common signatures (no args) #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId) { WriteEventCore(eventId, 0, null); } // optimized for common signatures (ints) #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, int arg1) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[1]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 4; descrs[0].Reserved = 0; WriteEventCore(eventId, 1, descrs); } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, int arg1, int arg2) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 4; descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 4; descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, int arg1, int arg2, int arg3) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 4; descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 4; descrs[1].Reserved = 0; descrs[2].DataPointer = (IntPtr)(&arg3); descrs[2].Size = 4; descrs[2].Reserved = 0; WriteEventCore(eventId, 3, descrs); } } // optimized for common signatures (longs) #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, long arg1) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[1]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[0].Reserved = 0; WriteEventCore(eventId, 1, descrs); } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, long arg1, long arg2) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 8; descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, long arg1, long arg2, long arg3) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 8; descrs[1].Reserved = 0; descrs[2].DataPointer = (IntPtr)(&arg3); descrs[2].Size = 8; descrs[2].Reserved = 0; WriteEventCore(eventId, 3, descrs); } } // optimized for common signatures (strings) #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, string? arg1) { if (IsEnabled()) { arg1 ??= ""; fixed (char* string1Bytes = arg1) { EventSource.EventData* descrs = stackalloc EventSource.EventData[1]; descrs[0].DataPointer = (IntPtr)string1Bytes; descrs[0].Size = ((arg1.Length + 1) * 2); descrs[0].Reserved = 0; WriteEventCore(eventId, 1, descrs); } } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, string? arg1, string? arg2) { if (IsEnabled()) { arg1 ??= ""; arg2 ??= ""; fixed (char* string1Bytes = arg1) fixed (char* string2Bytes = arg2) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; descrs[0].DataPointer = (IntPtr)string1Bytes; descrs[0].Size = ((arg1.Length + 1) * 2); descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)string2Bytes; descrs[1].Size = ((arg2.Length + 1) * 2); descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, string? arg1, string? arg2, string? arg3) { if (IsEnabled()) { arg1 ??= ""; arg2 ??= ""; arg3 ??= ""; fixed (char* string1Bytes = arg1) fixed (char* string2Bytes = arg2) fixed (char* string3Bytes = arg3) { EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; descrs[0].DataPointer = (IntPtr)string1Bytes; descrs[0].Size = ((arg1.Length + 1) * 2); descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)string2Bytes; descrs[1].Size = ((arg2.Length + 1) * 2); descrs[1].Reserved = 0; descrs[2].DataPointer = (IntPtr)string3Bytes; descrs[2].Size = ((arg3.Length + 1) * 2); descrs[2].Reserved = 0; WriteEventCore(eventId, 3, descrs); } } } // optimized for common signatures (string and ints) #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, string? arg1, int arg2) { if (IsEnabled()) { arg1 ??= ""; fixed (char* string1Bytes = arg1) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; descrs[0].DataPointer = (IntPtr)string1Bytes; descrs[0].Size = ((arg1.Length + 1) * 2); descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 4; descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, string? arg1, int arg2, int arg3) { if (IsEnabled()) { arg1 ??= ""; fixed (char* string1Bytes = arg1) { EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; descrs[0].DataPointer = (IntPtr)string1Bytes; descrs[0].Size = ((arg1.Length + 1) * 2); descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 4; descrs[1].Reserved = 0; descrs[2].DataPointer = (IntPtr)(&arg3); descrs[2].Size = 4; descrs[2].Reserved = 0; WriteEventCore(eventId, 3, descrs); } } } // optimized for common signatures (string and longs) #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, string? arg1, long arg2) { if (IsEnabled()) { arg1 ??= ""; fixed (char* string1Bytes = arg1) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; descrs[0].DataPointer = (IntPtr)string1Bytes; descrs[0].Size = ((arg1.Length + 1) * 2); descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 8; descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } } } // optimized for common signatures (long and string) #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, long arg1, string? arg2) { if (IsEnabled()) { arg2 ??= ""; fixed (char* string2Bytes = arg2) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)string2Bytes; descrs[1].Size = ((arg2.Length + 1) * 2); descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } } } // optimized for common signatures (int and string) #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, int arg1, string? arg2) { if (IsEnabled()) { arg2 ??= ""; fixed (char* string2Bytes = arg2) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 4; descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)string2Bytes; descrs[1].Size = ((arg2.Length + 1) * 2); descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, byte[]? arg1) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; if (arg1 == null || arg1.Length == 0) { int blobSize = 0; descrs[0].DataPointer = (IntPtr)(&blobSize); descrs[0].Size = 4; descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)(&blobSize); // valid address instead of empty content descrs[1].Size = 0; descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } else { int blobSize = arg1.Length; fixed (byte* blob = &arg1[0]) { descrs[0].DataPointer = (IntPtr)(&blobSize); descrs[0].Size = 4; descrs[0].Reserved = 0; descrs[1].DataPointer = (IntPtr)blob; descrs[1].Size = blobSize; descrs[1].Reserved = 0; WriteEventCore(eventId, 2, descrs); } } } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif protected unsafe void WriteEvent(int eventId, long arg1, byte[]? arg2) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[0].Reserved = 0; if (arg2 == null || arg2.Length == 0) { int blobSize = 0; descrs[1].DataPointer = (IntPtr)(&blobSize); descrs[1].Size = 4; descrs[1].Reserved = 0; descrs[2].DataPointer = (IntPtr)(&blobSize); // valid address instead of empty contents descrs[2].Size = 0; descrs[2].Reserved = 0; WriteEventCore(eventId, 3, descrs); } else { int blobSize = arg2.Length; fixed (byte* blob = &arg2[0]) { descrs[1].DataPointer = (IntPtr)(&blobSize); descrs[1].Size = 4; descrs[1].Reserved = 0; descrs[2].DataPointer = (IntPtr)blob; descrs[2].Size = blobSize; descrs[2].Reserved = 0; WriteEventCore(eventId, 3, descrs); } } } } #pragma warning restore 1591 /// <summary> /// Used to construct the data structure to be passed to the native ETW APIs - EventWrite and EventWriteTransfer. /// </summary> protected internal struct EventData { /// <summary> /// Address where the one argument lives (if this points to managed memory you must ensure the /// managed object is pinned. /// </summary> public unsafe IntPtr DataPointer { get => (IntPtr)(void*)m_Ptr; set => m_Ptr = unchecked((ulong)(void*)value); } /// <summary> /// Size of the argument referenced by DataPointer /// </summary> public int Size { get => m_Size; set => m_Size = value; } /// <summary> /// Reserved by ETW. This property is present to ensure that we can zero it /// since System.Private.CoreLib uses are not zero'd. /// </summary> internal int Reserved { get => m_Reserved; set => m_Reserved = value; } #region private /// <summary> /// Initializes the members of this EventData object to point at a previously-pinned /// tracelogging-compatible metadata blob. /// </summary> /// <param name="pointer">Pinned tracelogging-compatible metadata blob.</param> /// <param name="size">The size of the metadata blob.</param> /// <param name="reserved">Value for reserved: 2 for per-provider metadata, 1 for per-event metadata</param> internal unsafe void SetMetadata(byte* pointer, int size, int reserved) { this.m_Ptr = (ulong)pointer; this.m_Size = size; this.m_Reserved = reserved; // Mark this descriptor as containing tracelogging-compatible metadata. } // Important, we pass this structure directly to the Win32 EventWrite API, so this structure must // be layed out exactly the way EventWrite wants it. internal ulong m_Ptr; internal int m_Size; #pragma warning disable 0649 internal int m_Reserved; // Used to pad the size to match the Win32 API #pragma warning restore 0649 #endregion } /// <summary> /// This routine allows you to create efficient WriteEvent helpers, however the code that you use to /// do this, while straightforward, is unsafe. /// </summary> /// <remarks> /// <code> /// protected unsafe void WriteEvent(int eventId, string arg1, long arg2) /// { /// if (IsEnabled()) /// { /// arg2 ??= ""; /// fixed (char* string2Bytes = arg2) /// { /// EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; /// descrs[0].DataPointer = (IntPtr)(&amp;arg1); /// descrs[0].Size = 8; /// descrs[0].Reserved = 0; /// descrs[1].DataPointer = (IntPtr)string2Bytes; /// descrs[1].Size = ((arg2.Length + 1) * 2); /// descrs[1].Reserved = 0; /// WriteEventCore(eventId, 2, descrs); /// } /// } /// } /// </code> /// </remarks> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "requires unreferenced code, but EnsureDescriptorsInitialized does not access this member and is safe to call.")] [RequiresUnreferencedCode(EventSourceRequiresUnreferenceMessage)] #endif [CLSCompliant(false)] protected unsafe void WriteEventCore(int eventId, int eventDataCount, EventSource.EventData* data) { WriteEventWithRelatedActivityIdCore(eventId, null, eventDataCount, data); } /// <summary> /// This routine allows you to create efficient WriteEventWithRelatedActivityId helpers, however the code /// that you use to do this, while straightforward, is unsafe. The only difference from /// <see cref="WriteEventCore"/> is that you pass the relatedActivityId from caller through to this API /// </summary> /// <remarks> /// <code> /// protected unsafe void WriteEventWithRelatedActivityId(int eventId, Guid relatedActivityId, string arg1, long arg2) /// { /// if (IsEnabled()) /// { /// arg2 ??= ""; /// fixed (char* string2Bytes = arg2) /// { /// EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; /// descrs[0].DataPointer = (IntPtr)(&amp;arg1); /// descrs[0].Size = 8; /// descrs[1].DataPointer = (IntPtr)string2Bytes; /// descrs[1].Size = ((arg2.Length + 1) * 2); /// WriteEventWithRelatedActivityIdCore(eventId, relatedActivityId, 2, descrs); /// } /// } /// } /// </code> /// </remarks> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "requires unreferenced code, but EnsureDescriptorsInitialized does not access this member and is safe to call.")] [RequiresUnreferencedCode(EventSourceRequiresUnreferenceMessage)] #endif [CLSCompliant(false)] protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, Guid* relatedActivityId, int eventDataCount, EventSource.EventData* data) { if (IsEnabled()) { Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source. try { ref EventMetadata metadata = ref m_eventData[eventId]; EventOpcode opcode = (EventOpcode)metadata.Descriptor.Opcode; Guid* pActivityId = null; Guid activityId = Guid.Empty; Guid relActivityId = Guid.Empty; if (opcode != EventOpcode.Info && relatedActivityId == null && ((metadata.ActivityOptions & EventActivityOptions.Disable) == 0)) { if (opcode == EventOpcode.Start) { m_activityTracker.OnStart(m_name, metadata.Name, metadata.Descriptor.Task, ref activityId, ref relActivityId, metadata.ActivityOptions); } else if (opcode == EventOpcode.Stop) { m_activityTracker.OnStop(m_name, metadata.Name, metadata.Descriptor.Task, ref activityId); } if (activityId != Guid.Empty) pActivityId = &activityId; if (relActivityId != Guid.Empty) relatedActivityId = &relActivityId; } #if FEATURE_MANAGED_ETW if (!SelfDescribingEvents) { if (metadata.EnabledForETW && !m_etwProvider.WriteEvent(ref metadata.Descriptor, metadata.EventHandle, pActivityId, relatedActivityId, eventDataCount, (IntPtr)data)) ThrowEventSourceException(metadata.Name); #if FEATURE_PERFTRACING if (metadata.EnabledForEventPipe && !m_eventPipeProvider.WriteEvent(ref metadata.Descriptor, metadata.EventHandle, pActivityId, relatedActivityId, eventDataCount, (IntPtr)data)) ThrowEventSourceException(metadata.Name); #endif // FEATURE_PERFTRACING } else if (metadata.EnabledForETW #if FEATURE_PERFTRACING || metadata.EnabledForEventPipe #endif // FEATURE_PERFTRACING ) { EventSourceOptions opt = new EventSourceOptions { Keywords = (EventKeywords)metadata.Descriptor.Keywords, Level = (EventLevel)metadata.Descriptor.Level, Opcode = (EventOpcode)metadata.Descriptor.Opcode }; WriteMultiMerge(metadata.Name, ref opt, metadata.TraceLoggingEventTypes, pActivityId, relatedActivityId, data); } #endif // FEATURE_MANAGED_ETW if (m_Dispatchers != null && metadata.EnabledForAnyListener) { #if MONO && !TARGET_BROWSER // On Mono, managed events from NativeRuntimeEventSource are written using WriteEventCore which can be // written doubly because EventPipe tries to pump it back up to EventListener via NativeRuntimeEventSource.ProcessEvents. // So we need to prevent this from getting written directly to the Listeners. if (this.GetType() != typeof(NativeRuntimeEventSource)) #endif // MONO && !TARGET_BROWSER { var eventCallbackArgs = new EventWrittenEventArgs(this, eventId, pActivityId, relatedActivityId); WriteToAllListeners(eventCallbackArgs, eventDataCount, data); } } } catch (Exception ex) { if (ex is EventSourceException) throw; else ThrowEventSourceException(m_eventData[eventId].Name, ex); } } } // fallback varags helpers. /// <summary> /// This is the varargs helper for writing an event. It does create an array and box all the arguments so it is /// relatively inefficient and should only be used for relatively rare events (e.g. less than 100 / sec). If your /// rates are faster than that you should use <see cref="WriteEventCore"/> to create fast helpers for your particular /// method signature. Even if you use this for rare events, this call should be guarded by an <see cref="IsEnabled()"/> /// check so that the varargs call is not made when the EventSource is not active. /// </summary> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "requires unreferenced code, but EnsureDescriptorsInitialized does not access this member and is safe to call.")] [RequiresUnreferencedCode(EventSourceRequiresUnreferenceMessage)] #endif protected unsafe void WriteEvent(int eventId, params object?[] args) { WriteEventVarargs(eventId, null, args); } /// <summary> /// This is the varargs helper for writing an event which also specifies a related activity. It is completely analogous /// to corresponding WriteEvent (they share implementation). It does create an array and box all the arguments so it is /// relatively inefficient and should only be used for relatively rare events (e.g. less than 100 / sec). If your /// rates are faster than that you should use <see cref="WriteEventWithRelatedActivityIdCore"/> to create fast helpers for your /// particular method signature. Even if you use this for rare events, this call should be guarded by an <see cref="IsEnabled()"/> /// check so that the varargs call is not made when the EventSource is not active. /// </summary> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "requires unreferenced code, but EnsureDescriptorsInitialized does not access this member and is safe to call.")] [RequiresUnreferencedCode(EventSourceRequiresUnreferenceMessage)] #endif protected unsafe void WriteEventWithRelatedActivityId(int eventId, Guid relatedActivityId, params object?[] args) { WriteEventVarargs(eventId, &relatedActivityId, args); } #endregion #region IDisposable Members /// <summary> /// Disposes of an EventSource. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Disposes of an EventSource. /// </summary> /// <remarks> /// Called from Dispose() with disposing=true, and from the finalizer (~EventSource) with disposing=false. /// Guidelines: /// 1. We may be called more than once: do nothing after the first call. /// 2. Avoid throwing exceptions if disposing is false, i.e. if we're being finalized. /// </remarks> /// <param name="disposing">True if called from Dispose(), false if called from the finalizer.</param> protected virtual void Dispose(bool disposing) { if (!IsSupported) { return; } // Do not invoke Dispose under the lock as this can lead to a deadlock. // See https://github.com/dotnet/runtime/issues/48342 for details. Debug.Assert(!Monitor.IsEntered(EventListener.EventListenersLock)); if (disposing) { #if FEATURE_MANAGED_ETW // Send the manifest one more time to ensure circular buffers have a chance to get to this information // even in scenarios with a high volume of ETW events. if (m_eventSourceEnabled) { try { SendManifest(m_rawManifest); } catch { } // If it fails, simply give up. m_eventSourceEnabled = false; } if (m_etwProvider != null) { m_etwProvider.Dispose(); m_etwProvider = null!; } #endif #if FEATURE_PERFTRACING if (m_eventPipeProvider != null) { m_eventPipeProvider.Dispose(); m_eventPipeProvider = null!; } #endif } m_eventSourceEnabled = false; m_eventSourceDisposed = true; } /// <summary> /// Finalizer for EventSource /// </summary> ~EventSource() { this.Dispose(false); } #endregion #region private private unsafe void WriteEventRaw( string? eventName, ref EventDescriptor eventDescriptor, IntPtr eventHandle, Guid* activityID, Guid* relatedActivityID, int dataCount, IntPtr data) { #if FEATURE_MANAGED_ETW || FEATURE_PERFTRACING bool allAreNull = true; #if FEATURE_MANAGED_ETW allAreNull &= (m_etwProvider == null); if (m_etwProvider != null && !m_etwProvider.WriteEventRaw(ref eventDescriptor, eventHandle, activityID, relatedActivityID, dataCount, data)) { ThrowEventSourceException(eventName); } #endif // FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING allAreNull &= (m_eventPipeProvider == null); if (m_eventPipeProvider != null && !m_eventPipeProvider.WriteEventRaw(ref eventDescriptor, eventHandle, activityID, relatedActivityID, dataCount, data)) { ThrowEventSourceException(eventName); } #endif // FEATURE_PERFTRACING if (allAreNull) { ThrowEventSourceException(eventName); } #endif // FEATURE_MANAGED_ETW || FEATURE_PERFTRACING } // FrameworkEventSource is on the startup path for the framework, so we have this internal overload that it can use // to prevent the working set hit from looking at the custom attributes on the type to get the Guid. internal EventSource(Guid eventSourceGuid, string eventSourceName) : this(eventSourceGuid, eventSourceName, EventSourceSettings.EtwManifestEventFormat) { } // Used by the internal FrameworkEventSource constructor and the TraceLogging-style event source constructor internal EventSource(Guid eventSourceGuid, string eventSourceName, EventSourceSettings settings, string[]? traits = null) { if (IsSupported) { #if FEATURE_PERFTRACING m_eventHandleTable = new TraceLoggingEventHandleTable(); #endif m_config = ValidateSettings(settings); Initialize(eventSourceGuid, eventSourceName, traits); } } /// <summary> /// This method is responsible for the common initialization path from our constructors. It must /// not leak any exceptions (otherwise, since most EventSource classes define a static member, /// "Log", such an exception would become a cached exception for the initialization of the static /// member, and any future access to the "Log" would throw the cached exception). /// </summary> private unsafe void Initialize(Guid eventSourceGuid, string eventSourceName, string[]? traits) { try { m_traits = traits; if (m_traits != null && m_traits.Length % 2 != 0) { throw new ArgumentException(SR.EventSource_TraitEven, nameof(traits)); } if (eventSourceGuid == Guid.Empty) { throw new ArgumentException(SR.EventSource_NeedGuid); } if (eventSourceName == null) { throw new ArgumentException(SR.EventSource_NeedName); } m_name = eventSourceName; m_guid = eventSourceGuid; // Enable Implicit Activity tracker m_activityTracker = ActivityTracker.Instance; #if FEATURE_MANAGED_ETW || FEATURE_PERFTRACING #if !DEBUG if (ProviderMetadata.Length == 0) #endif { // Create and register our provider traits. We do this early because it is needed to log errors // In the self-describing event case. InitializeProviderMetadata(); } #endif #if FEATURE_MANAGED_ETW // Register the provider with ETW var etwProvider = new OverrideEventProvider(this, EventProviderType.ETW); etwProvider.Register(this); #endif #if FEATURE_PERFTRACING // Register the provider with EventPipe var eventPipeProvider = new OverrideEventProvider(this, EventProviderType.EventPipe); lock (EventListener.EventListenersLock) { eventPipeProvider.Register(this); } #endif // Add the eventSource to the global (weak) list. // This also sets m_id, which is the index in the list. EventListener.AddEventSource(this); #if FEATURE_MANAGED_ETW // OK if we get this far without an exception, then we can at least write out error messages. // Set m_provider, which allows this. m_etwProvider = etwProvider; #if TARGET_WINDOWS #if (!ES_BUILD_STANDALONE) // API available on OS >= Win 8 and patched Win 7. // Disable only for FrameworkEventSource to avoid recursion inside exception handling. if (this.Name != "System.Diagnostics.Eventing.FrameworkEventSource" || Environment.IsWindows8OrAbove) #endif { var providerMetadata = ProviderMetadata; fixed (byte* pMetadata = providerMetadata) { m_etwProvider.SetInformation( Interop.Advapi32.EVENT_INFO_CLASS.SetTraits, pMetadata, (uint)providerMetadata.Length); } } #endif // TARGET_WINDOWS #endif // FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING m_eventPipeProvider = eventPipeProvider; #endif Debug.Assert(!m_eventSourceEnabled); // We can't be enabled until we are completely initted. // We are logically completely initialized at this point. m_completelyInited = true; } catch (Exception e) { m_constructionException ??= e; ReportOutOfBandMessage("ERROR: Exception during construction of EventSource " + Name + ": " + e.Message); } // Once m_completelyInited is set, you can have concurrency, so all work is under the lock. lock (EventListener.EventListenersLock) { // If there are any deferred commands, we can do them now. // This is the most likely place for exceptions to happen. // Note that we are NOT resetting m_deferredCommands to NULL here, // We are giving for EventHandler<EventCommandEventArgs> that will be attached later EventCommandEventArgs? deferredCommands = m_deferredCommands; while (deferredCommands != null) { DoCommand(deferredCommands); // This can never throw, it catches them and reports the errors. deferredCommands = deferredCommands.nextCommand; } } } private static string GetName(Type eventSourceType, EventManifestOptions flags) { if (eventSourceType == null) throw new ArgumentNullException(nameof(eventSourceType)); EventSourceAttribute? attrib = (EventSourceAttribute?)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute), flags); if (attrib != null && attrib.Name != null) return attrib.Name; return eventSourceType.Name; } private static Guid GenerateGuidFromName(string name) { #if ES_BUILD_STANDALONE if (namespaceBytes == null) { namespaceBytes = new byte[] { 0x48, 0x2C, 0x2D, 0xB2, 0xC3, 0x90, 0x47, 0xC8, 0x87, 0xF8, 0x1A, 0x15, 0xBF, 0xC1, 0x30, 0xFB, }; } #else ReadOnlySpan<byte> namespaceBytes = new byte[] // rely on C# compiler optimization to remove byte[] allocation { 0x48, 0x2C, 0x2D, 0xB2, 0xC3, 0x90, 0x47, 0xC8, 0x87, 0xF8, 0x1A, 0x15, 0xBF, 0xC1, 0x30, 0xFB, }; #endif byte[] bytes = Encoding.BigEndianUnicode.GetBytes(name); Sha1ForNonSecretPurposes hash = default; hash.Start(); hash.Append(namespaceBytes); hash.Append(bytes); Array.Resize(ref bytes, 16); hash.Finish(bytes); bytes[7] = unchecked((byte)((bytes[7] & 0x0F) | 0x50)); // Set high 4 bits of octet 7 to 5, as per RFC 4122 return new Guid(bytes); } private static unsafe void DecodeObjects(object?[] decodedObjects, Type[] parameterTypes, EventData* data) { for (int i = 0; i < decodedObjects.Length; i++, data++) { IntPtr dataPointer = data->DataPointer; Type dataType = parameterTypes[i]; object? decoded; if (dataType == typeof(string)) { goto String; } else if (dataType == typeof(int)) { Debug.Assert(data->Size == 4); decoded = *(int*)dataPointer; } else { TypeCode typeCode = Type.GetTypeCode(dataType); int size = data->Size; if (size == 4) { if ((uint)(typeCode - TypeCode.SByte) <= TypeCode.Int32 - TypeCode.SByte) { Debug.Assert(dataType.IsEnum); // Enums less than 4 bytes in size should be treated as int. decoded = *(int*)dataPointer; } else if (typeCode == TypeCode.UInt32) { decoded = *(uint*)dataPointer; } else if (typeCode == TypeCode.Single) { decoded = *(float*)dataPointer; } else if (typeCode == TypeCode.Boolean) { // The manifest defines a bool as a 32bit type (WIN32 BOOL), not 1 bit as CLR Does. decoded = *(int*)dataPointer == 1; } else if (dataType == typeof(byte[])) { // byte[] are written to EventData* as an int followed by a blob Debug.Assert(*(int*)dataPointer == (data + 1)->Size); data++; goto BytePtr; } else if (IntPtr.Size == 4 && dataType == typeof(IntPtr)) { decoded = *(IntPtr*)dataPointer; } else { goto Unknown; } } else if (size <= 2) { Debug.Assert(!dataType.IsEnum); if (typeCode == TypeCode.Byte) { Debug.Assert(size == 1); decoded = *(byte*)dataPointer; } else if (typeCode == TypeCode.SByte) { Debug.Assert(size == 1); decoded = *(sbyte*)dataPointer; } else if (typeCode == TypeCode.Int16) { Debug.Assert(size == 2); decoded = *(short*)dataPointer; } else if (typeCode == TypeCode.UInt16) { Debug.Assert(size == 2); decoded = *(ushort*)dataPointer; } else if (typeCode == TypeCode.Char) { Debug.Assert(size == 2); decoded = *(char*)dataPointer; } else { goto Unknown; } } else if (size == 8) { if (typeCode == TypeCode.Int64) { decoded = *(long*)dataPointer; } else if (typeCode == TypeCode.UInt64) { decoded = *(ulong*)dataPointer; } else if (typeCode == TypeCode.Double) { decoded = *(double*)dataPointer; } else if (typeCode == TypeCode.DateTime) { decoded = *(DateTime*)dataPointer; } else if (IntPtr.Size == 8 && dataType == typeof(IntPtr)) { decoded = *(IntPtr*)dataPointer; } else { goto Unknown; } } else if (typeCode == TypeCode.Decimal) { Debug.Assert(size == 16); decoded = *(decimal*)dataPointer; } else if (dataType == typeof(Guid)) { Debug.Assert(size == 16); decoded = *(Guid*)dataPointer; } else { goto Unknown; } } goto Store; Unknown: if (dataType != typeof(byte*)) { // Everything else is marshaled as a string. goto String; } BytePtr: if (data->Size == 0) { decoded = Array.Empty<byte>(); } else { var blob = new byte[data->Size]; Marshal.Copy(data->DataPointer, blob, 0, blob.Length); decoded = blob; } goto Store; String: // ETW strings are NULL-terminated, so marshal everything up to the first null in the string. AssertValidString(data); decoded = dataPointer == IntPtr.Zero ? null : new string((char*)dataPointer, 0, (data->Size >> 1) - 1); Store: decodedObjects[i] = decoded; } } [Conditional("DEBUG")] private static unsafe void AssertValidString(EventData* data) { Debug.Assert(data->Size >= 0 && data->Size % 2 == 0, "String size should be even"); char* charPointer = (char*)data->DataPointer; int charLength = data->Size / 2 - 1; for (int i = 0; i < charLength; i++) { Debug.Assert(*(charPointer + i) != 0, "String may not contain null chars"); } Debug.Assert(*(charPointer + charLength) == 0, "String must be null terminated"); } // Finds the Dispatcher (which holds the filtering state), for a given dispatcher for the current // eventSource). private EventDispatcher? GetDispatcher(EventListener? listener) { EventDispatcher? dispatcher = m_Dispatchers; while (dispatcher != null) { if (dispatcher.m_Listener == listener) return dispatcher; dispatcher = dispatcher.m_Next; } return dispatcher; } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "requires unreferenced code, but EnsureDescriptorsInitialized does not access this member and is safe to call.")] [RequiresUnreferencedCode(EventSourceRequiresUnreferenceMessage)] #endif private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object?[] args) { if (IsEnabled()) { Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source. try { ref EventMetadata metadata = ref m_eventData[eventId]; if (childActivityID != null) { // If you use WriteEventWithRelatedActivityID you MUST declare the first argument to be a GUID // with the name 'relatedActivityID, and NOT pass this argument to the WriteEvent method. // During manifest creation we modify the ParameterInfo[] that we store to strip out any // first parameter that is of type Guid and named "relatedActivityId." Thus, if you call // WriteEventWithRelatedActivityID from a method that doesn't name its first parameter correctly // we can end up in a state where the ParameterInfo[] doesn't have its first parameter stripped, // and this leads to a mismatch between the number of arguments and the number of ParameterInfos, // which would cause a cryptic IndexOutOfRangeException later if we don't catch it here. if (!metadata.HasRelatedActivityID) { throw new ArgumentException(SR.EventSource_NoRelatedActivityId); } } LogEventArgsMismatches(eventId, args); Guid* pActivityId = null; Guid activityId = Guid.Empty; Guid relatedActivityId = Guid.Empty; EventOpcode opcode = (EventOpcode)metadata.Descriptor.Opcode; EventActivityOptions activityOptions = metadata.ActivityOptions; if (childActivityID == null && ((activityOptions & EventActivityOptions.Disable) == 0)) { if (opcode == EventOpcode.Start) { m_activityTracker.OnStart(m_name, metadata.Name, metadata.Descriptor.Task, ref activityId, ref relatedActivityId, metadata.ActivityOptions); } else if (opcode == EventOpcode.Stop) { m_activityTracker.OnStop(m_name, metadata.Name, metadata.Descriptor.Task, ref activityId); } if (activityId != Guid.Empty) pActivityId = &activityId; if (relatedActivityId != Guid.Empty) childActivityID = &relatedActivityId; } #if FEATURE_MANAGED_ETW if (metadata.EnabledForETW #if FEATURE_PERFTRACING || metadata.EnabledForEventPipe #endif // FEATURE_PERFTRACING ) { if (!SelfDescribingEvents) { if (!m_etwProvider.WriteEvent(ref metadata.Descriptor, metadata.EventHandle, pActivityId, childActivityID, args)) ThrowEventSourceException(metadata.Name); #if FEATURE_PERFTRACING if (!m_eventPipeProvider.WriteEvent(ref metadata.Descriptor, metadata.EventHandle, pActivityId, childActivityID, args)) ThrowEventSourceException(metadata.Name); #endif // FEATURE_PERFTRACING } else { // TODO: activity ID support EventSourceOptions opt = new EventSourceOptions { Keywords = (EventKeywords)metadata.Descriptor.Keywords, Level = (EventLevel)metadata.Descriptor.Level, Opcode = (EventOpcode)metadata.Descriptor.Opcode }; WriteMultiMerge(metadata.Name, ref opt, metadata.TraceLoggingEventTypes, pActivityId, childActivityID, args); } } #endif // FEATURE_MANAGED_ETW if (m_Dispatchers != null && metadata.EnabledForAnyListener) { #if !ES_BUILD_STANDALONE // Maintain old behavior - object identity is preserved if (!LocalAppContextSwitches.PreserveEventListnerObjectIdentity) #endif // !ES_BUILD_STANDALONE { args = SerializeEventArgs(eventId, args); } var eventCallbackArgs = new EventWrittenEventArgs(this, eventId, pActivityId, childActivityID) { Payload = new ReadOnlyCollection<object?>(args) }; DispatchToAllListeners(eventCallbackArgs); } } catch (Exception ex) { if (ex is EventSourceException) throw; else ThrowEventSourceException(m_eventData[eventId].Name, ex); } } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "requires unreferenced code, but EnsureDescriptorsInitialized does not access this member and is safe to call.")] [RequiresUnreferencedCode(EventSourceRequiresUnreferenceMessage)] #endif private unsafe object?[] SerializeEventArgs(int eventId, object?[] args) { Debug.Assert(m_eventData != null); TraceLoggingEventTypes eventTypes = m_eventData[eventId].TraceLoggingEventTypes; int paramCount = Math.Min(eventTypes.typeInfos.Length, args.Length); // parameter count mismatch get logged in LogEventArgsMismatches var eventData = new object?[eventTypes.typeInfos.Length]; for (int i = 0; i < paramCount; i++) { eventData[i] = eventTypes.typeInfos[i].GetData(args[i]); } return eventData; } /// <summary> /// We expect that the arguments to the Event method and the arguments to WriteEvent match. This function /// checks that they in fact match and logs a warning to the debugger if they don't. /// </summary> /// <param name="eventId"></param> /// <param name="args"></param> private void LogEventArgsMismatches(int eventId, object?[] args) { Debug.Assert(m_eventData != null); ParameterInfo[] infos = m_eventData[eventId].Parameters; if (args.Length != infos.Length) { ReportOutOfBandMessage(SR.Format(SR.EventSource_EventParametersMismatch, eventId, args.Length, infos.Length)); return; } for (int i = 0; i < args.Length; i++) { Type pType = infos[i].ParameterType; object? arg = args[i]; // Checking to see if the Parameter types (from the Event method) match the supplied argument types. // Fail if one of two things hold : either the argument type is not equal or assignable to the parameter type, or the // argument is null and the parameter type is a non-Nullable<T> value type. if ((arg != null && !pType.IsAssignableFrom(arg.GetType())) || (arg == null && (pType.IsValueType && !(pType.IsGenericType && pType.GetGenericTypeDefinition() == typeof(Nullable<>)))) ) { ReportOutOfBandMessage(SR.Format(SR.EventSource_VarArgsParameterMismatch, eventId, infos[i].Name)); return; } } } private unsafe void WriteToAllListeners(EventWrittenEventArgs eventCallbackArgs, int eventDataCount, EventData* data) { Debug.Assert(m_eventData != null); ref EventMetadata metadata = ref m_eventData[eventCallbackArgs.EventId]; if (eventDataCount != metadata.EventListenerParameterCount) { ReportOutOfBandMessage(SR.Format(SR.EventSource_EventParametersMismatch, eventCallbackArgs.EventId, eventDataCount, metadata.Parameters.Length)); } object?[] args; if (eventDataCount == 0) { eventCallbackArgs.Payload = EventWrittenEventArgs.EmptyPayload; } else { args = new object?[Math.Min(eventDataCount, metadata.Parameters.Length)]; if (metadata.AllParametersAreString) { for (int i = 0; i < args.Length; i++, data++) { AssertValidString(data); IntPtr dataPointer = data->DataPointer; args[i] = dataPointer == IntPtr.Zero ? null : new string((char*)dataPointer, 0, (data->Size >> 1) - 1); } } else if (metadata.AllParametersAreInt32) { for (int i = 0; i < args.Length; i++, data++) { Debug.Assert(data->Size == 4); args[i] = *(int*)data->DataPointer; } } else { DecodeObjects(args, metadata.ParameterTypes, data); } eventCallbackArgs.Payload = new ReadOnlyCollection<object?>(args); } DispatchToAllListeners(eventCallbackArgs); } internal unsafe void DispatchToAllListeners(EventWrittenEventArgs eventCallbackArgs) { int eventId = eventCallbackArgs.EventId; Exception? lastThrownException = null; for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) { Debug.Assert(dispatcher.m_EventEnabled != null); if (eventId == -1 || dispatcher.m_EventEnabled[eventId]) { { try { dispatcher.m_Listener.OnEventWritten(eventCallbackArgs); } catch (Exception e) { ReportOutOfBandMessage("ERROR: Exception during EventSource.OnEventWritten: " + e.Message); lastThrownException = e; } } } } if (lastThrownException != null && ThrowOnEventWriteErrors) { throw new EventSourceException(lastThrownException); } } // WriteEventString is used for logging an error message (or similar) to // ETW and EventPipe providers. It is not a general purpose API, it will // log the message with Level=LogAlways and Keywords=All to make sure whoever // is listening gets the message. private unsafe void WriteEventString(string msgString) { #if FEATURE_MANAGED_ETW || FEATURE_PERFTRACING bool allAreNull = true; #if FEATURE_MANAGED_ETW allAreNull &= (m_etwProvider == null); #endif // FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING allAreNull &= (m_eventPipeProvider == null); #endif // FEATURE_PERFTRACING if (allAreNull) { return; } EventLevel level = EventLevel.LogAlways; long keywords = -1; const string EventName = "EventSourceMessage"; if (SelfDescribingEvents) { EventSourceOptions opt = new EventSourceOptions { Keywords = (EventKeywords)unchecked(keywords), Level = level }; #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The call to TraceLoggingEventTypes with the below parameter values are trim safe")] #endif static TraceLoggingEventTypes GetTrimSafeTraceLoggingEventTypes() => new TraceLoggingEventTypes(EventName, EventTags.None, new Type[] { typeof(string) }); var tlet = GetTrimSafeTraceLoggingEventTypes(); WriteMultiMergeInner(EventName, ref opt, tlet, null, null, msgString); } else { // We want the name of the provider to show up so if we don't have a manifest we create // on that at least has the provider name (I don't define any events). if (m_rawManifest == null && m_outOfBandMessageCount == 1) { ManifestBuilder manifestBuilder = new ManifestBuilder(Name, Guid, Name, null, EventManifestOptions.None); manifestBuilder.StartEvent(EventName, new EventAttribute(0) { Level = level, Task = (EventTask)0xFFFE }); manifestBuilder.AddEventParameter(typeof(string), "message"); manifestBuilder.EndEvent(); SendManifest(manifestBuilder.CreateManifest()); } // We use this low level routine to bypass the enabled checking, since the eventSource itself is only partially inited. fixed (char* msgStringPtr = msgString) { EventDescriptor descr = new EventDescriptor(0, 0, 0, (byte)level, 0, 0, keywords); EventProvider.EventData data = default; data.Ptr = (ulong)msgStringPtr; data.Size = (uint)(2 * (msgString.Length + 1)); data.Reserved = 0; #if FEATURE_MANAGED_ETW if (m_etwProvider != null) { m_etwProvider.WriteEvent(ref descr, IntPtr.Zero, null, null, 1, (IntPtr)((void*)&data)); } #endif // FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING if (m_eventPipeProvider != null) { if (m_writeEventStringEventHandle == IntPtr.Zero) { if (m_createEventLock is null) { Interlocked.CompareExchange(ref m_createEventLock, new object(), null); } lock (m_createEventLock) { if (m_writeEventStringEventHandle == IntPtr.Zero) { string eventName = "EventSourceMessage"; EventParameterInfo paramInfo = default(EventParameterInfo); paramInfo.SetInfo("message", typeof(string)); byte[]? metadata = EventPipeMetadataGenerator.Instance.GenerateMetadata(0, eventName, keywords, (uint)level, 0, EventOpcode.Info, new EventParameterInfo[] { paramInfo }); uint metadataLength = (metadata != null) ? (uint)metadata.Length : 0; fixed (byte* pMetadata = metadata) { m_writeEventStringEventHandle = m_eventPipeProvider.m_eventProvider.DefineEventHandle(0, eventName, keywords, 0, (uint)level, pMetadata, metadataLength); } } } } m_eventPipeProvider.WriteEvent(ref descr, m_writeEventStringEventHandle, null, null, 1, (IntPtr)((void*)&data)); } #endif // FEATURE_PERFTRACING } } #endif // FEATURE_MANAGED_ETW || FEATURE_PERFTRACING } /// <summary> /// Since this is a means of reporting errors (see ReportoutOfBandMessage) any failure encountered /// while writing the message to any one of the listeners will be silently ignored. /// </summary> private void WriteStringToAllListeners(string eventName, string msg) { var eventCallbackArgs = new EventWrittenEventArgs(this, 0) { EventName = eventName, Message = msg, Payload = new ReadOnlyCollection<object?>(new object[] { msg }), PayloadNames = new ReadOnlyCollection<string>(new string[] { "message" }) }; for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) { bool dispatcherEnabled = false; if (dispatcher.m_EventEnabled == null) { // if the listeners that weren't correctly initialized, we will send to it // since this is an error message and we want to see it go out. dispatcherEnabled = true; } else { // if there's *any* enabled event on the dispatcher we'll write out the string // otherwise we'll treat the listener as disabled and skip it for (int evtId = 0; evtId < dispatcher.m_EventEnabled.Length; ++evtId) { if (dispatcher.m_EventEnabled[evtId]) { dispatcherEnabled = true; break; } } } try { if (dispatcherEnabled) dispatcher.m_Listener.OnEventWritten(eventCallbackArgs); } catch { // ignore any exceptions thrown by listeners' OnEventWritten } } } /// <summary> /// Returns true if 'eventNum' is enabled if you only consider the level and matchAnyKeyword filters. /// It is possible that eventSources turn off the event based on additional filtering criteria. /// </summary> private bool IsEnabledByDefault(int eventNum, bool enable, EventLevel currentLevel, EventKeywords currentMatchAnyKeyword) { if (!enable) return false; Debug.Assert(m_eventData != null); EventLevel eventLevel = (EventLevel)m_eventData[eventNum].Descriptor.Level; EventKeywords eventKeywords = unchecked((EventKeywords)((ulong)m_eventData[eventNum].Descriptor.Keywords & (~(SessionMask.All.ToEventKeywords())))); #if FEATURE_MANAGED_ETW_CHANNELS EventChannel channel = unchecked((EventChannel)m_eventData[eventNum].Descriptor.Channel); #else EventChannel channel = EventChannel.None; #endif return IsEnabledCommon(enable, currentLevel, currentMatchAnyKeyword, eventLevel, eventKeywords, channel); } private bool IsEnabledCommon(bool enabled, EventLevel currentLevel, EventKeywords currentMatchAnyKeyword, EventLevel eventLevel, EventKeywords eventKeywords, EventChannel eventChannel) { if (!enabled) return false; // does is pass the level test? if ((currentLevel != 0) && (currentLevel < eventLevel)) return false; // if yes, does it pass the keywords test? if (currentMatchAnyKeyword != 0 && eventKeywords != 0) { #if FEATURE_MANAGED_ETW_CHANNELS // is there a channel with keywords that match currentMatchAnyKeyword? if (eventChannel != EventChannel.None && this.m_channelData != null && this.m_channelData.Length > (int)eventChannel) { EventKeywords channel_keywords = unchecked((EventKeywords)(m_channelData[(int)eventChannel] | (ulong)eventKeywords)); if (channel_keywords != 0 && (channel_keywords & currentMatchAnyKeyword) == 0) return false; } else #endif { if ((unchecked((ulong)eventKeywords & (ulong)currentMatchAnyKeyword)) == 0) return false; } } return true; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private void ThrowEventSourceException(string? eventName, Exception? innerEx = null) { // If we fail during out of band logging we may end up trying // to throw another EventSourceException, thus hitting a StackOverflowException. // Avoid StackOverflow by making sure we do not recursively call this method. if (m_EventSourceExceptionRecurenceCount > 0) return; try { m_EventSourceExceptionRecurenceCount++; string errorPrefix = "EventSourceException"; if (eventName != null) { errorPrefix += " while processing event \"" + eventName + "\""; } // TODO Create variations of EventSourceException that indicate more information using the error code. switch (EventProvider.GetLastWriteEventError()) { case EventProvider.WriteEventErrorCode.EventTooBig: ReportOutOfBandMessage(errorPrefix + ": " + SR.EventSource_EventTooBig); if (ThrowOnEventWriteErrors) throw new EventSourceException(SR.EventSource_EventTooBig, innerEx); break; case EventProvider.WriteEventErrorCode.NoFreeBuffers: ReportOutOfBandMessage(errorPrefix + ": " + SR.EventSource_NoFreeBuffers); if (ThrowOnEventWriteErrors) throw new EventSourceException(SR.EventSource_NoFreeBuffers, innerEx); break; case EventProvider.WriteEventErrorCode.NullInput: ReportOutOfBandMessage(errorPrefix + ": " + SR.EventSource_NullInput); if (ThrowOnEventWriteErrors) throw new EventSourceException(SR.EventSource_NullInput, innerEx); break; case EventProvider.WriteEventErrorCode.TooManyArgs: ReportOutOfBandMessage(errorPrefix + ": " + SR.EventSource_TooManyArgs); if (ThrowOnEventWriteErrors) throw new EventSourceException(SR.EventSource_TooManyArgs, innerEx); break; default: if (innerEx != null) { innerEx = innerEx.GetBaseException(); ReportOutOfBandMessage(errorPrefix + ": " + innerEx.GetType() + ":" + innerEx.Message); } else ReportOutOfBandMessage(errorPrefix); if (ThrowOnEventWriteErrors) throw new EventSourceException(innerEx); break; } } finally { m_EventSourceExceptionRecurenceCount--; } } internal static EventOpcode GetOpcodeWithDefault(EventOpcode opcode, string? eventName) { if (opcode == EventOpcode.Info && eventName != null) { if (eventName.EndsWith(s_ActivityStartSuffix, StringComparison.Ordinal)) { return EventOpcode.Start; } else if (eventName.EndsWith(s_ActivityStopSuffix, StringComparison.Ordinal)) { return EventOpcode.Stop; } } return opcode; } #if FEATURE_MANAGED_ETW /// <summary> /// This class lets us hook the 'OnEventCommand' from the eventSource. /// </summary> private sealed class OverrideEventProvider : EventProvider { public OverrideEventProvider(EventSource eventSource, EventProviderType providerType) : base(providerType) { this.m_eventSource = eventSource; this.m_eventProviderType = providerType; } protected override void OnControllerCommand(ControllerCommand command, IDictionary<string, string?>? arguments, int perEventSourceSessionId, int etwSessionId) { // We use null to represent the ETW EventListener. EventListener? listener = null; m_eventSource.SendCommand(listener, m_eventProviderType, perEventSourceSessionId, etwSessionId, (EventCommand)command, IsEnabled(), Level, MatchAnyKeyword, arguments); } private readonly EventSource m_eventSource; private readonly EventProviderType m_eventProviderType; } #endif /// <summary> /// Used to hold all the static information about an event. This includes everything in the event /// descriptor as well as some stuff we added specifically for EventSource. see the /// code:m_eventData for where we use this. /// </summary> internal partial struct EventMetadata { public EventDescriptor Descriptor; public IntPtr EventHandle; // EventPipeEvent handle. public EventTags Tags; public bool EnabledForAnyListener; // true if any dispatcher has this event turned on public bool EnabledForETW; // is this event on for ETW? #if FEATURE_PERFTRACING public bool EnabledForEventPipe; // is this event on for EventPipe? #endif public bool HasRelatedActivityID; // Set if the event method's first parameter is a Guid named 'relatedActivityId' public string Name; // the name of the event public string? Message; // If the event has a message associated with it, this is it. public ParameterInfo[] Parameters; // TODO can we remove? public int EventListenerParameterCount; public bool AllParametersAreString; public bool AllParametersAreInt32; public EventActivityOptions ActivityOptions; private TraceLoggingEventTypes _traceLoggingEventTypes; public TraceLoggingEventTypes TraceLoggingEventTypes { #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "requires unreferenced code, but EnsureDescriptorsInitialized does not access this member and is safe to call.")] [RequiresUnreferencedCode(EventSourceRequiresUnreferenceMessage)] #endif get { if (_traceLoggingEventTypes is null) { var tlet = new TraceLoggingEventTypes(Name, Tags, Parameters); Interlocked.CompareExchange(ref _traceLoggingEventTypes, tlet, null); } return _traceLoggingEventTypes; } } private ReadOnlyCollection<string>? _parameterNames; public ReadOnlyCollection<string> ParameterNames { get { if (_parameterNames is null) { ParameterInfo[] parameters = Parameters; var names = new string[parameters.Length]; for (int i = 0; i < names.Length; i++) { names[i] = parameters[i].Name!; } _parameterNames = new ReadOnlyCollection<string>(names); } return _parameterNames; } } private Type[]? _parameterTypes; public Type[] ParameterTypes { get { return _parameterTypes ??= GetParameterTypes(Parameters); static Type[] GetParameterTypes(ParameterInfo[] parameters) { var types = new Type[parameters.Length]; for (int i = 0; i < types.Length; i++) { types[i] = parameters[i].ParameterType; } return types; } } } } // This is the internal entry point that code:EventListeners call when wanting to send a command to a // eventSource. The logic is as follows // // * if Command == Update // * perEventSourceSessionId specifies the per-provider ETW session ID that the command applies // to (if listener != null) // perEventSourceSessionId = 0 - reserved for EventListeners // perEventSourceSessionId = 1..SessionMask.MAX - reserved for activity tracing aware ETW sessions // perEventSourceSessionId-1 represents the bit in the reserved field (bits 44..47) in // Keywords that identifies the session // perEventSourceSessionId = SessionMask.MAX+1 - reserved for legacy ETW sessions; these are // discriminated by etwSessionId // * etwSessionId specifies a machine-wide ETW session ID; this allows correlation of // activity tracing across different providers (which might have different sessionIds // for the same ETW session) // * enable, level, matchAnyKeywords are used to set a default for all events for the // eventSource. In particular, if 'enabled' is false, 'level' and // 'matchAnyKeywords' are not used. // * OnEventCommand is invoked, which may cause calls to // code:EventSource.EnableEventForDispatcher which may cause changes in the filtering // depending on the logic in that routine. // * else (command != Update) // * Simply call OnEventCommand. The expectation is that filtering is NOT changed. // * The 'enabled' 'level', matchAnyKeyword' arguments are ignored (must be true, 0, 0). // // dispatcher == null has special meaning. It is the 'ETW' dispatcher. internal void SendCommand(EventListener? listener, EventProviderType eventProviderType, int perEventSourceSessionId, int etwSessionId, EventCommand command, bool enable, EventLevel level, EventKeywords matchAnyKeyword, IDictionary<string, string?>? commandArguments) { if (!IsSupported) { return; } var commandArgs = new EventCommandEventArgs(command, commandArguments, this, listener, eventProviderType, perEventSourceSessionId, etwSessionId, enable, level, matchAnyKeyword); lock (EventListener.EventListenersLock) { if (m_completelyInited) { // After the first command arrive after construction, we are ready to get rid of the deferred commands this.m_deferredCommands = null; // We are fully initialized, do the command DoCommand(commandArgs); } else { // We can't do the command, simply remember it and we do it when we are fully constructed. if (m_deferredCommands == null) { m_deferredCommands = commandArgs; // create the first entry } else { // We have one or more entries, find the last one and add it to that. EventCommandEventArgs lastCommand = m_deferredCommands; while (lastCommand.nextCommand != null) lastCommand = lastCommand.nextCommand; lastCommand.nextCommand = commandArgs; } } } } /// <summary> /// We want the eventSource to be fully initialized when we do commands because that way we can send /// error messages and other logging directly to the event stream. Unfortunately we can get callbacks /// when we are not fully initialized. In that case we store them in 'commandArgs' and do them later. /// This helper actually does all actual command logic. /// </summary> internal void DoCommand(EventCommandEventArgs commandArgs) { if (!IsSupported) { return; } // PRECONDITION: We should be holding the EventListener.EventListenersLock // We defer commands until we are completely inited. This allows error messages to be sent. Debug.Assert(m_completelyInited); #if FEATURE_MANAGED_ETW if (m_etwProvider == null) // If we failed to construct return; #endif // FEATURE_MANAGED_ETW #if FEATURE_PERFTRACING if (m_eventPipeProvider == null) return; #endif m_outOfBandMessageCount = 0; try { EnsureDescriptorsInitialized(); Debug.Assert(m_eventData != null); // Find the per-EventSource dispatcher corresponding to registered dispatcher commandArgs.dispatcher = GetDispatcher(commandArgs.listener); if (commandArgs.dispatcher == null && commandArgs.listener != null) // dispatcher == null means ETW dispatcher { throw new ArgumentException(SR.EventSource_ListenerNotFound); } commandArgs.Arguments ??= new Dictionary<string, string?>(); if (commandArgs.Command == EventCommand.Update) { // Set it up using the 'standard' filtering bitfields (use the "global" enable, not session specific one) for (int i = 0; i < m_eventData.Length; i++) EnableEventForDispatcher(commandArgs.dispatcher, commandArgs.eventProviderType, i, IsEnabledByDefault(i, commandArgs.enable, commandArgs.level, commandArgs.matchAnyKeyword)); if (commandArgs.enable) { if (!m_eventSourceEnabled) { // EventSource turned on for the first time, simply copy the bits. m_level = commandArgs.level; m_matchAnyKeyword = commandArgs.matchAnyKeyword; } else { // Already enabled, make it the most verbose of the existing and new filter if (commandArgs.level > m_level) m_level = commandArgs.level; if (commandArgs.matchAnyKeyword == 0) m_matchAnyKeyword = 0; else if (m_matchAnyKeyword != 0) m_matchAnyKeyword = unchecked(m_matchAnyKeyword | commandArgs.matchAnyKeyword); } } // interpret perEventSourceSessionId's sign, and adjust perEventSourceSessionId to // represent 0-based positive values bool bSessionEnable = (commandArgs.perEventSourceSessionId >= 0); if (commandArgs.perEventSourceSessionId == 0 && !commandArgs.enable) bSessionEnable = false; if (commandArgs.listener == null) { if (!bSessionEnable) commandArgs.perEventSourceSessionId = -commandArgs.perEventSourceSessionId; // for "global" enable/disable (passed in with listener == null and // perEventSourceSessionId == 0) perEventSourceSessionId becomes -1 --commandArgs.perEventSourceSessionId; } commandArgs.Command = bSessionEnable ? EventCommand.Enable : EventCommand.Disable; // perEventSourceSessionId = -1 when ETW sent a notification, but the set of active sessions // hasn't changed. // sesisonId = SessionMask.MAX when one of the legacy ETW sessions changed // 0 <= perEventSourceSessionId < SessionMask.MAX for activity-tracing aware sessions Debug.Assert(commandArgs.perEventSourceSessionId >= -1 && commandArgs.perEventSourceSessionId <= SessionMask.MAX); // Send the manifest if we are enabling an ETW session if (bSessionEnable && commandArgs.dispatcher == null) { // eventSourceDispatcher == null means this is the ETW manifest // Note that we unconditionally send the manifest whenever we are enabled, even if // we were already enabled. This is because there may be multiple sessions active // and we can't know that all the sessions have seen the manifest. if (!SelfDescribingEvents) SendManifest(m_rawManifest); } // Turn on the enable bit before making the OnEventCommand callback This allows you to do useful // things like log messages, or test if keywords are enabled in the callback. if (commandArgs.enable) { Debug.Assert(m_eventData != null); m_eventSourceEnabled = true; } this.OnEventCommand(commandArgs); this.m_eventCommandExecuted?.Invoke(this, commandArgs); if (!commandArgs.enable) { // If we are disabling, maybe we can turn on 'quick checks' to filter // quickly. These are all just optimizations (since later checks will still filter) // There is a good chance EnabledForAnyListener are not as accurate as // they could be, go ahead and get a better estimate. for (int i = 0; i < m_eventData.Length; i++) { bool isEnabledForAnyListener = false; for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) { Debug.Assert(dispatcher.m_EventEnabled != null); if (dispatcher.m_EventEnabled[i]) { isEnabledForAnyListener = true; break; } } m_eventData[i].EnabledForAnyListener = isEnabledForAnyListener; } // If no events are enabled, disable the global enabled bit. if (!AnyEventEnabled()) { m_level = 0; m_matchAnyKeyword = 0; m_eventSourceEnabled = false; } } } else { if (commandArgs.Command == EventCommand.SendManifest) { // TODO: should we generate the manifest here if we hadn't already? if (m_rawManifest != null) SendManifest(m_rawManifest); } // These are not used for non-update commands and thus should always be 'default' values // Debug.Assert(enable == true); // Debug.Assert(level == EventLevel.LogAlways); // Debug.Assert(matchAnyKeyword == EventKeywords.None); this.OnEventCommand(commandArgs); m_eventCommandExecuted?.Invoke(this, commandArgs); } } catch (Exception e) { // When the ETW session is created after the EventSource has registered with the ETW system // we can send any error messages here. ReportOutOfBandMessage("ERROR: Exception in Command Processing for EventSource " + Name + ": " + e.Message); // We never throw when doing a command. } } /// <summary> /// If 'value is 'true' then set the eventSource so that 'dispatcher' will receive event with the eventId /// of 'eventId. If value is 'false' disable the event for that dispatcher. If 'eventId' is out of /// range return false, otherwise true. /// </summary> internal bool EnableEventForDispatcher(EventDispatcher? dispatcher, EventProviderType eventProviderType, int eventId, bool value) { if (!IsSupported) return false; Debug.Assert(m_eventData != null); if (dispatcher == null) { if (eventId >= m_eventData.Length) return false; #if FEATURE_MANAGED_ETW if (m_etwProvider != null && eventProviderType == EventProviderType.ETW) m_eventData[eventId].EnabledForETW = value; #endif #if FEATURE_PERFTRACING if (m_eventPipeProvider != null && eventProviderType == EventProviderType.EventPipe) m_eventData[eventId].EnabledForEventPipe = value; #endif } else { Debug.Assert(dispatcher.m_EventEnabled != null); if (eventId >= dispatcher.m_EventEnabled.Length) return false; dispatcher.m_EventEnabled[eventId] = value; if (value) m_eventData[eventId].EnabledForAnyListener = true; } return true; } /// <summary> /// Returns true if any event at all is on. /// </summary> private bool AnyEventEnabled() { Debug.Assert(m_eventData != null); for (int i = 0; i < m_eventData.Length; i++) if (m_eventData[i].EnabledForETW || m_eventData[i].EnabledForAnyListener #if FEATURE_PERFTRACING || m_eventData[i].EnabledForEventPipe #endif // FEATURE_PERFTRACING ) return true; return false; } private bool IsDisposed => m_eventSourceDisposed; private void EnsureDescriptorsInitialized() { #if !ES_BUILD_STANDALONE Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif if (m_eventData == null) { // get the metadata via reflection. Debug.Assert(m_rawManifest == null); m_rawManifest = CreateManifestAndDescriptors(this.GetType(), Name, this); Debug.Assert(m_eventData != null); // TODO Enforce singleton pattern if (!AllowDuplicateSourceNames) { Debug.Assert(EventListener.s_EventSources != null, "should be called within lock on EventListener.EventListenersLock which ensures s_EventSources to be initialized"); foreach (WeakReference<EventSource> eventSourceRef in EventListener.s_EventSources) { if (eventSourceRef.TryGetTarget(out EventSource? eventSource) && eventSource.Guid == m_guid && !eventSource.IsDisposed) { if (eventSource != this) { throw new ArgumentException(SR.Format(SR.EventSource_EventSourceGuidInUse, m_guid)); } } } } // Make certain all dispatchers also have their arrays initialized EventDispatcher? dispatcher = m_Dispatchers; while (dispatcher != null) { dispatcher.m_EventEnabled ??= new bool[m_eventData.Length]; dispatcher = dispatcher.m_Next; } #if FEATURE_PERFTRACING // Initialize the EventPipe event handles. DefineEventPipeEvents(); #endif } } // Send out the ETW manifest XML out to ETW // Today, we only send the manifest to ETW, custom listeners don't get it. private unsafe void SendManifest(byte[]? rawManifest) { if (rawManifest == null) return; Debug.Assert(!SelfDescribingEvents); #if FEATURE_MANAGED_ETW fixed (byte* dataPtr = rawManifest) { // we don't want the manifest to show up in the event log channels so we specify as keywords // everything but the first 8 bits (reserved for the 8 channels) var manifestDescr = new EventDescriptor(0xFFFE, 1, 0, 0, 0xFE, 0xFFFE, 0x00ffFFFFffffFFFF); ManifestEnvelope envelope = default; envelope.Format = ManifestEnvelope.ManifestFormats.SimpleXmlFormat; envelope.MajorVersion = 1; envelope.MinorVersion = 0; envelope.Magic = 0x5B; // An unusual number that can be checked for consistency. int dataLeft = rawManifest.Length; envelope.ChunkNumber = 0; EventProvider.EventData* dataDescrs = stackalloc EventProvider.EventData[2]; dataDescrs[0].Ptr = (ulong)&envelope; dataDescrs[0].Size = (uint)sizeof(ManifestEnvelope); dataDescrs[0].Reserved = 0; dataDescrs[1].Ptr = (ulong)dataPtr; dataDescrs[1].Reserved = 0; int chunkSize = ManifestEnvelope.MaxChunkSize; TRY_AGAIN_WITH_SMALLER_CHUNK_SIZE: envelope.TotalChunks = (ushort)((dataLeft + (chunkSize - 1)) / chunkSize); while (dataLeft > 0) { dataDescrs[1].Size = (uint)Math.Min(dataLeft, chunkSize); if (m_etwProvider != null) { if (!m_etwProvider.WriteEvent(ref manifestDescr, IntPtr.Zero, null, null, 2, (IntPtr)dataDescrs)) { // Turns out that if users set the BufferSize to something less than 64K then WriteEvent // can fail. If we get this failure on the first chunk try again with something smaller // The smallest BufferSize is 1K so if we get to 256 (to account for envelope overhead), we can give up making it smaller. if (EventProvider.GetLastWriteEventError() == EventProvider.WriteEventErrorCode.EventTooBig) { if (envelope.ChunkNumber == 0 && chunkSize > 256) { chunkSize /= 2; goto TRY_AGAIN_WITH_SMALLER_CHUNK_SIZE; } } if (ThrowOnEventWriteErrors) ThrowEventSourceException("SendManifest"); break; } } dataLeft -= chunkSize; dataDescrs[1].Ptr += (uint)chunkSize; envelope.ChunkNumber++; // For large manifests we want to not overflow any receiver's buffer. Most manifests will fit within // 5 chunks, so only the largest manifests will hit the pause. if ((envelope.ChunkNumber % 5) == 0) { Thread.Sleep(15); } } } #endif // FEATURE_MANAGED_ETW } // Helper to deal with the fact that the type we are reflecting over might be loaded in the ReflectionOnly context. // When that is the case, we have to build the custom assemblies on a member by hand. internal static bool IsCustomAttributeDefinedHelper( MemberInfo member, Type attributeType, EventManifestOptions flags = EventManifestOptions.None) { // AllowEventSourceOverride is an option that allows either Microsoft.Diagnostics.Tracing or // System.Diagnostics.Tracing EventSource to be considered valid. This should not mattter anywhere but in Microsoft.Diagnostics.Tracing (nuget package). if (!member.Module.Assembly.ReflectionOnly && (flags & EventManifestOptions.AllowEventSourceOverride) == 0) { // Let the runtime do the work for us, since we can execute code in this context. return member.IsDefined(attributeType, inherit: false); } foreach (CustomAttributeData data in CustomAttributeData.GetCustomAttributes(member)) { if (AttributeTypeNamesMatch(attributeType, data.Constructor.ReflectedType!)) { return true; } } return false; } // Helper to deal with the fact that the type we are reflecting over might be loaded in the ReflectionOnly context. // When that is the case, we have the build the custom assemblies on a member by hand. #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2114:ReflectionToDynamicallyAccessedMembers", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "has dynamically accessed members requirements, but EnsureDescriptorsInitialized does not "+ "access this member and is safe to call.")] #endif internal static Attribute? GetCustomAttributeHelper( MemberInfo member, #if !ES_BUILD_STANDALONE [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicProperties)] #endif Type attributeType, EventManifestOptions flags = EventManifestOptions.None) { Debug.Assert(attributeType == typeof(EventAttribute) || attributeType == typeof(EventSourceAttribute)); // AllowEventSourceOverride is an option that allows either Microsoft.Diagnostics.Tracing or // System.Diagnostics.Tracing EventSource to be considered valid. This should not mattter anywhere but in Microsoft.Diagnostics.Tracing (nuget package). if (!member.Module.Assembly.ReflectionOnly && (flags & EventManifestOptions.AllowEventSourceOverride) == 0) { // Let the runtime do the work for us, since we can execute code in this context. return member.GetCustomAttribute(attributeType, inherit: false); } foreach (CustomAttributeData data in CustomAttributeData.GetCustomAttributes(member)) { if (AttributeTypeNamesMatch(attributeType, data.Constructor.ReflectedType!)) { Attribute? attr = null; Debug.Assert(data.ConstructorArguments.Count <= 1); if (data.ConstructorArguments.Count == 1) { attr = (Attribute?)Activator.CreateInstance(attributeType, new object?[] { data.ConstructorArguments[0].Value }); } else if (data.ConstructorArguments.Count == 0) { attr = (Attribute?)Activator.CreateInstance(attributeType); } if (attr != null) { foreach (CustomAttributeNamedArgument namedArgument in data.NamedArguments) { PropertyInfo p = attributeType.GetProperty(namedArgument.MemberInfo.Name, BindingFlags.Public | BindingFlags.Instance)!; object value = namedArgument.TypedValue.Value!; if (p.PropertyType.IsEnum) { string val = value.ToString()!; value = Enum.Parse(p.PropertyType, val); } p.SetValue(attr, value, null); } return attr; } } } return null; } /// <summary> /// Evaluates if two related "EventSource"-domain types should be considered the same /// </summary> /// <param name="attributeType">The attribute type in the load context - it's associated with the running /// EventSource type. This type may be different fromt he base type of the user-defined EventSource.</param> /// <param name="reflectedAttributeType">The attribute type in the reflection context - it's associated with /// the user-defined EventSource, and is in the same assembly as the eventSourceType passed to /// </param> /// <returns>True - if the types should be considered equivalent, False - otherwise</returns> private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAttributeType) { return // are these the same type? attributeType == reflectedAttributeType || // are the full typenames equal? string.Equals(attributeType.FullName, reflectedAttributeType.FullName, StringComparison.Ordinal) || // are the typenames equal and the namespaces under "Diagnostics.Tracing" (typically // either Microsoft.Diagnostics.Tracing or System.Diagnostics.Tracing)? string.Equals(attributeType.Name, reflectedAttributeType.Name, StringComparison.Ordinal) && attributeType.Namespace!.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal) && (reflectedAttributeType.Namespace!.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal) #if EVENT_SOURCE_LEGACY_NAMESPACE_SUPPORT || reflectedAttributeType.Namespace.EndsWith("Diagnostics.Eventing", StringComparison.Ordinal) #endif ); } private static Type? GetEventSourceBaseType(Type eventSourceType, bool allowEventSourceOverride, bool reflectionOnly) { Type? ret = eventSourceType; // return false for "object" and interfaces if (ret.BaseType == null) return null; // now go up the inheritance chain until hitting a concrete type ("object" at worse) do { ret = ret.BaseType; } while (ret != null && ret.IsAbstract); if (ret != null) { if (!allowEventSourceOverride) { if (reflectionOnly && ret.FullName != typeof(EventSource).FullName || !reflectionOnly && ret != typeof(EventSource)) return null; } else { if (ret.Name != "EventSource") return null; } } return ret; } // Use reflection to look at the attributes of a class, and generate a manifest for it (as UTF8) and // return the UTF8 bytes. It also sets up the code:EventData structures needed to dispatch events // at run time. 'source' is the event source to place the descriptors. If it is null, // then the descriptors are not created, and just the manifest is generated. #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2114:ReflectionToDynamicallyAccessedMembers", Justification = "EnsureDescriptorsInitialized's use of GetType preserves this method which " + "has dynamically accessed members requirements, but its use of this method satisfies " + "these requirements because it passes in the result of GetType with the same annotations.")] #endif private static byte[]? CreateManifestAndDescriptors( #if !ES_BUILD_STANDALONE [DynamicallyAccessedMembers(ManifestMemberTypes)] #endif Type eventSourceType, string? eventSourceDllName, EventSource? source, EventManifestOptions flags = EventManifestOptions.None) { ManifestBuilder? manifest = null; bool bNeedsManifest = source != null ? !source.SelfDescribingEvents : true; Exception? exception = null; // exception that might get raised during validation b/c we couldn't/didn't recover from a previous error byte[]? res = null; if (eventSourceType.IsAbstract && (flags & EventManifestOptions.Strict) == 0) return null; try { MethodInfo[] methods = eventSourceType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); EventAttribute defaultEventAttribute; int eventId = 1; // The number given to an event that does not have a explicitly given ID. EventMetadata[]? eventData = null; Dictionary<string, string>? eventsByName = null; if (source != null || (flags & EventManifestOptions.Strict) != 0) { eventData = new EventMetadata[methods.Length + 1]; eventData[0].Name = ""; // Event 0 is the 'write messages string' event, and has an empty name. } // See if we have localization information. ResourceManager? resources = null; EventSourceAttribute? eventSourceAttrib = (EventSourceAttribute?)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute), flags); if (eventSourceAttrib != null && eventSourceAttrib.LocalizationResources != null) resources = new ResourceManager(eventSourceAttrib.LocalizationResources, eventSourceType.Assembly); if (source is not null) { // We have the source so don't need to use reflection to get the Name and Guid manifest = new ManifestBuilder(source.Name, source.Guid, eventSourceDllName, resources, flags); } else { manifest = new ManifestBuilder(GetName(eventSourceType, flags), GetGuid(eventSourceType), eventSourceDllName, resources, flags); } // Add an entry unconditionally for event ID 0 which will be for a string message. manifest.StartEvent("EventSourceMessage", new EventAttribute(0) { Level = EventLevel.LogAlways, Task = (EventTask)0xFFFE }); manifest.AddEventParameter(typeof(string), "message"); manifest.EndEvent(); // eventSourceType must be sealed and must derive from this EventSource if ((flags & EventManifestOptions.Strict) != 0) { bool typeMatch = GetEventSourceBaseType(eventSourceType, (flags & EventManifestOptions.AllowEventSourceOverride) != 0, eventSourceType.Assembly.ReflectionOnly) != null; if (!typeMatch) { manifest.ManifestError(SR.EventSource_TypeMustDeriveFromEventSource); } if (!eventSourceType.IsAbstract && !eventSourceType.IsSealed) { manifest.ManifestError(SR.EventSource_TypeMustBeSealedOrAbstract); } } // Collect task, opcode, keyword and channel information #if FEATURE_MANAGED_ETW_CHANNELS && FEATURE_ADVANCED_MANAGED_ETW_CHANNELS foreach (var providerEnumKind in new string[] { "Keywords", "Tasks", "Opcodes", "Channels" }) #else foreach (string providerEnumKind in new string[] { "Keywords", "Tasks", "Opcodes" }) #endif { Type? nestedType = eventSourceType.GetNestedType(providerEnumKind); if (nestedType != null) { if (eventSourceType.IsAbstract) { manifest.ManifestError(SR.Format(SR.EventSource_AbstractMustNotDeclareKTOC, nestedType.Name)); } else { foreach (FieldInfo staticField in nestedType.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)) { AddProviderEnumKind(manifest, staticField, providerEnumKind); } } } } // ensure we have keywords for the session-filtering reserved bits { manifest.AddKeyword("Session3", (long)0x1000 << 32); manifest.AddKeyword("Session2", (long)0x2000 << 32); manifest.AddKeyword("Session1", (long)0x4000 << 32); manifest.AddKeyword("Session0", (long)0x8000 << 32); } if (eventSourceType != typeof(EventSource)) { for (int i = 0; i < methods.Length; i++) { MethodInfo method = methods[i]; ParameterInfo[] args = method.GetParameters(); // Get the EventDescriptor (from the Custom attributes) EventAttribute? eventAttribute = (EventAttribute?)GetCustomAttributeHelper(method, typeof(EventAttribute), flags); // Compat: until v4.5.1 we ignored any non-void returning methods as well as virtual methods for // the only reason of limiting the number of methods considered to be events. This broke a common // design of having event sources implement specific interfaces. To fix this in a compatible way // we will now allow both non-void returning and virtual methods to be Event methods, as long // as they are marked with the [Event] attribute if (/* method.IsVirtual || */ method.IsStatic) { continue; } if (eventSourceType.IsAbstract) { if (eventAttribute != null) { manifest.ManifestError(SR.Format(SR.EventSource_AbstractMustNotDeclareEventMethods, method.Name, eventAttribute.EventId)); } continue; } else if (eventAttribute == null) { // Methods that don't return void can't be events, if they're NOT marked with [Event]. // (see Compat comment above) if (method.ReturnType != typeof(void)) { continue; } // Continue to ignore virtual methods if they do NOT have the [Event] attribute // (see Compat comment above) if (method.IsVirtual) { continue; } // If we explicitly mark the method as not being an event, then honor that. if (IsCustomAttributeDefinedHelper(method, typeof(NonEventAttribute), flags)) continue; defaultEventAttribute = new EventAttribute(eventId); eventAttribute = defaultEventAttribute; } else if (eventAttribute.EventId <= 0) { manifest.ManifestError(SR.EventSource_NeedPositiveId, true); continue; // don't validate anything else for this event } if (method.Name.LastIndexOf('.') >= 0) { manifest.ManifestError(SR.Format(SR.EventSource_EventMustNotBeExplicitImplementation, method.Name, eventAttribute.EventId)); } eventId++; string eventName = method.Name; if (eventAttribute.Opcode == EventOpcode.Info) // We are still using the default opcode. { // By default pick a task ID derived from the EventID, starting with the highest task number and working back bool noTask = (eventAttribute.Task == EventTask.None); if (noTask) eventAttribute.Task = (EventTask)(0xFFFE - eventAttribute.EventId); // Unless we explicitly set the opcode to Info (to override the auto-generate of Start or Stop opcodes, // pick a default opcode based on the event name (either Info or start or stop if the name ends with that suffix). if (!eventAttribute.IsOpcodeSet) eventAttribute.Opcode = GetOpcodeWithDefault(EventOpcode.Info, eventName); // Make the stop opcode have the same task as the start opcode. if (noTask) { if (eventAttribute.Opcode == EventOpcode.Start) { string taskName = eventName.Substring(0, eventName.Length - s_ActivityStartSuffix.Length); // Remove the Stop suffix to get the task name if (string.Compare(eventName, 0, taskName, 0, taskName.Length) == 0 && string.Compare(eventName, taskName.Length, s_ActivityStartSuffix, 0, Math.Max(eventName.Length - taskName.Length, s_ActivityStartSuffix.Length)) == 0) { // Add a task that is just the task name for the start event. This suppress the auto-task generation // That would otherwise happen (and create 'TaskName'Start as task name rather than just 'TaskName' manifest.AddTask(taskName, (int)eventAttribute.Task); } } else if (eventAttribute.Opcode == EventOpcode.Stop) { // Find the start associated with this stop event. We require start to be immediately before the stop int startEventId = eventAttribute.EventId - 1; if (eventData != null && startEventId < eventData.Length) { Debug.Assert(0 <= startEventId); // Since we reserve id 0, we know that id-1 is <= 0 EventMetadata startEventMetadata = eventData[startEventId]; // If you remove the Stop and add a Start does that name match the Start Event's Name? // Ideally we would throw an error string taskName = eventName.Substring(0, eventName.Length - s_ActivityStopSuffix.Length); // Remove the Stop suffix to get the task name if (startEventMetadata.Descriptor.Opcode == (byte)EventOpcode.Start && string.Compare(startEventMetadata.Name, 0, taskName, 0, taskName.Length) == 0 && string.Compare(startEventMetadata.Name, taskName.Length, s_ActivityStartSuffix, 0, Math.Max(startEventMetadata.Name.Length - taskName.Length, s_ActivityStartSuffix.Length)) == 0) { // Make the stop event match the start event eventAttribute.Task = (EventTask)startEventMetadata.Descriptor.Task; noTask = false; } } if (noTask && (flags & EventManifestOptions.Strict) != 0) // Throw an error if we can compatibly. { throw new ArgumentException(SR.EventSource_StopsFollowStarts); } } } } bool hasRelatedActivityID = RemoveFirstArgIfRelatedActivityId(ref args); if (!(source != null && source.SelfDescribingEvents)) { manifest.StartEvent(eventName, eventAttribute); for (int fieldIdx = 0; fieldIdx < args.Length; fieldIdx++) { manifest.AddEventParameter(args[fieldIdx].ParameterType, args[fieldIdx].Name!); } manifest.EndEvent(); } if (source != null || (flags & EventManifestOptions.Strict) != 0) { Debug.Assert(eventData != null); // Do checking for user errors (optional, but not a big deal so we do it). DebugCheckEvent(ref eventsByName, eventData, method, eventAttribute, manifest, flags); #if FEATURE_MANAGED_ETW_CHANNELS // add the channel keyword for Event Viewer channel based filters. This is added for creating the EventDescriptors only // and is not required for the manifest if (eventAttribute.Channel != EventChannel.None) { unchecked { eventAttribute.Keywords |= (EventKeywords)manifest.GetChannelKeyword(eventAttribute.Channel, (ulong)eventAttribute.Keywords); } } #endif if (manifest.HasResources) { string eventKey = "event_" + eventName; if (manifest.GetLocalizedMessage(eventKey, CultureInfo.CurrentUICulture, etwFormat: false) is string msg) { // overwrite inline message with the localized message eventAttribute.Message = msg; } } AddEventDescriptor(ref eventData, eventName, eventAttribute, args, hasRelatedActivityID); } } } // Tell the TraceLogging stuff where to start allocating its own IDs. NameInfo.ReserveEventIDsBelow(eventId); if (source != null) { Debug.Assert(eventData != null); TrimEventDescriptors(ref eventData); source.m_eventData = eventData; // officially initialize it. We do this at most once (it is racy otherwise). #if FEATURE_MANAGED_ETW_CHANNELS source.m_channelData = manifest.GetChannelData(); #endif } // if this is an abstract event source we've already performed all the validation we can if (!eventSourceType.IsAbstract && (source == null || !source.SelfDescribingEvents)) { bNeedsManifest = (flags & EventManifestOptions.OnlyIfNeededForRegistration) == 0 #if FEATURE_MANAGED_ETW_CHANNELS || manifest.GetChannelData().Length > 0 #endif ; // if the manifest is not needed and we're not requested to validate the event source return early if (!bNeedsManifest && (flags & EventManifestOptions.Strict) == 0) return null; res = manifest.CreateManifest(); } } catch (Exception e) { // if this is a runtime manifest generation let the exception propagate if ((flags & EventManifestOptions.Strict) == 0) throw; // else store it to include it in the Argument exception we raise below exception = e; } if ((flags & EventManifestOptions.Strict) != 0 && (manifest?.Errors.Count > 0 || exception != null)) { string msg = string.Empty; if (manifest?.Errors.Count > 0) { bool firstError = true; foreach (string error in manifest.Errors) { if (!firstError) msg += System.Environment.NewLine; firstError = false; msg += error; } } else msg = "Unexpected error: " + exception!.Message; throw new ArgumentException(msg, exception); } return bNeedsManifest ? res : null; } private static bool RemoveFirstArgIfRelatedActivityId(ref ParameterInfo[] args) { // If the first parameter is (case insensitive) 'relatedActivityId' then skip it. if (args.Length > 0 && args[0].ParameterType == typeof(Guid) && string.Equals(args[0].Name, "relatedActivityId", StringComparison.OrdinalIgnoreCase)) { var newargs = new ParameterInfo[args.Length - 1]; Array.Copy(args, 1, newargs, 0, args.Length - 1); args = newargs; return true; } return false; } // adds a enumeration (keyword, opcode, task or channel) represented by 'staticField' // to the manifest. private static void AddProviderEnumKind(ManifestBuilder manifest, FieldInfo staticField, string providerEnumKind) { bool reflectionOnly = staticField.Module.Assembly.ReflectionOnly; Type staticFieldType = staticField.FieldType; if (!reflectionOnly && (staticFieldType == typeof(EventOpcode)) || AttributeTypeNamesMatch(staticFieldType, typeof(EventOpcode))) { if (providerEnumKind != "Opcodes") goto Error; int value = (int)staticField.GetRawConstantValue()!; manifest.AddOpcode(staticField.Name, value); } else if (!reflectionOnly && (staticFieldType == typeof(EventTask)) || AttributeTypeNamesMatch(staticFieldType, typeof(EventTask))) { if (providerEnumKind != "Tasks") goto Error; int value = (int)staticField.GetRawConstantValue()!; manifest.AddTask(staticField.Name, value); } else if (!reflectionOnly && (staticFieldType == typeof(EventKeywords)) || AttributeTypeNamesMatch(staticFieldType, typeof(EventKeywords))) { if (providerEnumKind != "Keywords") goto Error; ulong value = unchecked((ulong)(long)staticField.GetRawConstantValue()!); manifest.AddKeyword(staticField.Name, value); } #if FEATURE_MANAGED_ETW_CHANNELS && FEATURE_ADVANCED_MANAGED_ETW_CHANNELS else if (!reflectionOnly && (staticFieldType == typeof(EventChannel)) || AttributeTypeNamesMatch(staticFieldType, typeof(EventChannel))) { if (providerEnumKind != "Channels") goto Error; var channelAttribute = (EventChannelAttribute)GetCustomAttributeHelper(staticField, typeof(EventChannelAttribute)); manifest.AddChannel(staticField.Name, (byte)staticField.GetRawConstantValue(), channelAttribute); } #endif return; Error: manifest.ManifestError(SR.Format(SR.EventSource_EnumKindMismatch, staticField.FieldType.Name, providerEnumKind)); } // Helper used by code:CreateManifestAndDescriptors to add a code:EventData descriptor for a method // with the code:EventAttribute 'eventAttribute'. resourceManger may be null in which case we populate it // it is populated if we need to look up message resources private static void AddEventDescriptor( [NotNull] ref EventMetadata[] eventData, string eventName, EventAttribute eventAttribute, ParameterInfo[] eventParameters, bool hasRelatedActivityID) { if (eventData.Length <= eventAttribute.EventId) { EventMetadata[] newValues = new EventMetadata[Math.Max(eventData.Length + 16, eventAttribute.EventId + 1)]; Array.Copy(eventData, newValues, eventData.Length); eventData = newValues; } ref EventMetadata metadata = ref eventData[eventAttribute.EventId]; metadata.Descriptor = new EventDescriptor( eventAttribute.EventId, eventAttribute.Version, #if FEATURE_MANAGED_ETW_CHANNELS (byte)eventAttribute.Channel, #else (byte)0, #endif (byte)eventAttribute.Level, (byte)eventAttribute.Opcode, (int)eventAttribute.Task, unchecked((long)((ulong)eventAttribute.Keywords | SessionMask.All.ToEventKeywords()))); metadata.Tags = eventAttribute.Tags; metadata.Name = eventName; metadata.Parameters = eventParameters; metadata.Message = eventAttribute.Message; metadata.ActivityOptions = eventAttribute.ActivityOptions; metadata.HasRelatedActivityID = hasRelatedActivityID; metadata.EventHandle = IntPtr.Zero; // We represent a byte[] with 2 EventData entries: an integer denoting the length and a blob of bytes in the data pointer. // This causes a spurious warning because eventDataCount is off by one for the byte[] case. // When writing to EventListeners, we want to check that the number of parameters is correct against the byte[] case. int eventListenerParameterCount = eventParameters.Length; bool allParametersAreInt32 = true; bool allParametersAreString = true; foreach (ParameterInfo parameter in eventParameters) { Type dataType = parameter.ParameterType; if (dataType == typeof(string)) { allParametersAreInt32 = false; } else if (dataType == typeof(int) || (dataType.IsEnum && Type.GetTypeCode(dataType.GetEnumUnderlyingType()) <= TypeCode.UInt32)) { // Int32 or an enum with a 1/2/4 byte backing type allParametersAreString = false; } else { if (dataType == typeof(byte[])) { eventListenerParameterCount++; } allParametersAreInt32 = false; allParametersAreString = false; } } metadata.AllParametersAreInt32 = allParametersAreInt32; metadata.AllParametersAreString = allParametersAreString; metadata.EventListenerParameterCount = eventListenerParameterCount; } // Helper used by code:CreateManifestAndDescriptors that trims the m_eventData array to the correct // size after all event descriptors have been added. private static void TrimEventDescriptors(ref EventMetadata[] eventData) { int idx = eventData.Length; while (0 < idx) { --idx; if (eventData[idx].Descriptor.EventId != 0) break; } if (eventData.Length - idx > 2) // allow one wasted slot. { EventMetadata[] newValues = new EventMetadata[idx + 1]; Array.Copy(eventData, newValues, newValues.Length); eventData = newValues; } } // Helper used by code:EventListener.AddEventSource and code:EventListener.EventListener // when a listener gets attached to a eventSource internal void AddListener(EventListener listener) { lock (EventListener.EventListenersLock) { bool[]? enabledArray = null; if (m_eventData != null) enabledArray = new bool[m_eventData.Length]; m_Dispatchers = new EventDispatcher(m_Dispatchers, enabledArray, listener); listener.OnEventSourceCreated(this); } } // Helper used by code:CreateManifestAndDescriptors to find user mistakes like reusing an event // index for two distinct events etc. Throws exceptions when it finds something wrong. private static void DebugCheckEvent(ref Dictionary<string, string>? eventsByName, EventMetadata[] eventData, MethodInfo method, EventAttribute eventAttribute, ManifestBuilder manifest, EventManifestOptions options) { int evtId = eventAttribute.EventId; string evtName = method.Name; int eventArg = GetHelperCallFirstArg(method); if (eventArg >= 0 && evtId != eventArg) { manifest.ManifestError(SR.Format(SR.EventSource_MismatchIdToWriteEvent, evtName, evtId, eventArg), true); } if (evtId < eventData.Length && eventData[evtId].Descriptor.EventId != 0) { manifest.ManifestError(SR.Format(SR.EventSource_EventIdReused, evtName, evtId), true); } // We give a task to things if they don't have one. // TODO this is moderately expensive (N*N). We probably should not even bother.... Debug.Assert(eventAttribute.Task != EventTask.None || eventAttribute.Opcode != EventOpcode.Info); for (int idx = 0; idx < eventData.Length; ++idx) { // skip unused Event IDs. if (eventData[idx].Name == null) continue; if (eventData[idx].Descriptor.Task == (int)eventAttribute.Task && eventData[idx].Descriptor.Opcode == (int)eventAttribute.Opcode) { manifest.ManifestError(SR.Format(SR.EventSource_TaskOpcodePairReused, evtName, evtId, eventData[idx].Name, idx)); // If we are not strict stop on first error. We have had problems with really large providers taking forever. because of many errors. if ((options & EventManifestOptions.Strict) == 0) break; } } // for non-default event opcodes the user must define a task! if (eventAttribute.Opcode != EventOpcode.Info) { bool failure = false; if (eventAttribute.Task == EventTask.None) failure = true; else { // If you have the auto-assigned Task, then you did not explicitly set one. // This is OK for Start events because we have special logic to assign the task to a prefix derived from the event name // But all other cases we want to catch the omission. var autoAssignedTask = (EventTask)(0xFFFE - evtId); if (eventAttribute.Opcode != EventOpcode.Start && eventAttribute.Opcode != EventOpcode.Stop && eventAttribute.Task == autoAssignedTask) failure = true; } if (failure) { manifest.ManifestError(SR.Format(SR.EventSource_EventMustHaveTaskIfNonDefaultOpcode, evtName, evtId)); } } // If we ever want to enforce the rule: MethodName = TaskName + OpcodeName here's how: // (the reason we don't is backwards compat and the need for handling this as a non-fatal error // by eventRegister.exe) // taskName & opcodeName could be passed in by the caller which has opTab & taskTab handy // if (!(((int)eventAttribute.Opcode == 0 && evtName == taskName) || (evtName == taskName+opcodeName))) // { // throw new WarningException(SR.EventSource_EventNameDoesNotEqualTaskPlusOpcode); // } eventsByName ??= new Dictionary<string, string>(); if (eventsByName.ContainsKey(evtName)) { manifest.ManifestError(SR.Format(SR.EventSource_EventNameReused, evtName), true); } eventsByName[evtName] = evtName; } /// <summary> /// This method looks at the IL and tries to pattern match against the standard /// 'boilerplate' event body /// <code> /// { if (Enabled()) WriteEvent(#, ...) } /// </code> /// If the pattern matches, it returns the literal number passed as the first parameter to /// the WriteEvent. This is used to find common user errors (mismatching this /// number with the EventAttribute ID). It is only used for validation. /// </summary> /// <param name="method">The method to probe.</param> /// <returns>The literal value or -1 if the value could not be determined. </returns> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The method calls MethodBase.GetMethodBody. Trimming application can change IL of various methods" + "which can lead to change of behavior. This method only uses this to validate usage of event source APIs." + "In the worst case it will not be able to determine the value it's looking for and will not perform" + "any validation.")] #endif private static int GetHelperCallFirstArg(MethodInfo method) { #if !CORERT // Currently searches for the following pattern // // ... // CAN ONLY BE THE INSTRUCTIONS BELOW // LDARG0 // LDC.I4 XXX // ... // CAN ONLY BE THE INSTRUCTIONS BELOW CAN'T BE A BRANCH OR A CALL // CALL // NOP // 0 or more times // RET // // If we find this pattern we return the XXX. Otherwise we return -1. #if ES_BUILD_STANDALONE (new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)).Assert(); #endif byte[] instrs = method.GetMethodBody()!.GetILAsByteArray()!; int retVal = -1; for (int idx = 0; idx < instrs.Length;) { switch (instrs[idx]) { case 0: // NOP case 1: // BREAK case 2: // LDARG_0 case 3: // LDARG_1 case 4: // LDARG_2 case 5: // LDARG_3 case 6: // LDLOC_0 case 7: // LDLOC_1 case 8: // LDLOC_2 case 9: // LDLOC_3 case 10: // STLOC_0 case 11: // STLOC_1 case 12: // STLOC_2 case 13: // STLOC_3 break; case 14: // LDARG_S case 16: // STARG_S idx++; break; case 20: // LDNULL break; case 21: // LDC_I4_M1 case 22: // LDC_I4_0 case 23: // LDC_I4_1 case 24: // LDC_I4_2 case 25: // LDC_I4_3 case 26: // LDC_I4_4 case 27: // LDC_I4_5 case 28: // LDC_I4_6 case 29: // LDC_I4_7 case 30: // LDC_I4_8 if (idx > 0 && instrs[idx - 1] == 2) // preceeded by LDARG0 retVal = instrs[idx] - 22; break; case 31: // LDC_I4_S if (idx > 0 && instrs[idx - 1] == 2) // preceeded by LDARG0 retVal = instrs[idx + 1]; idx++; break; case 32: // LDC_I4 idx += 4; break; case 37: // DUP break; case 40: // CALL idx += 4; if (retVal >= 0) { // Is this call just before return? for (int search = idx + 1; search < instrs.Length; search++) { if (instrs[search] == 42) // RET return retVal; if (instrs[search] != 0) // NOP break; } } retVal = -1; break; case 44: // BRFALSE_S case 45: // BRTRUE_S retVal = -1; idx++; break; case 57: // BRFALSE case 58: // BRTRUE retVal = -1; idx += 4; break; case 103: // CONV_I1 case 104: // CONV_I2 case 105: // CONV_I4 case 106: // CONV_I8 case 109: // CONV_U4 case 110: // CONV_U8 break; case 140: // BOX case 141: // NEWARR idx += 4; break; case 162: // STELEM_REF break; case 254: // PREFIX idx++; // Covers the CEQ instructions used in debug code for some reason. if (idx >= instrs.Length || instrs[idx] >= 6) goto default; break; default: /* Debug.Fail("Warning: User validation code sub-optimial: Unsuported opcode " + instrs[idx] + " at " + idx + " in method " + method.Name); */ return -1; } idx++; } #endif return -1; } /// <summary> /// Sends an error message to the debugger (outputDebugString), as well as the EventListeners /// It will do this even if the EventSource is not enabled. /// </summary> internal void ReportOutOfBandMessage(string msg) { try { if (m_outOfBandMessageCount < 16 - 1) // Note this is only if size byte { m_outOfBandMessageCount++; } else { if (m_outOfBandMessageCount == 16) return; m_outOfBandMessageCount = 16; // Mark that we hit the limit. Notify them that this is the case. msg = "Reached message limit. End of EventSource error messages."; } // send message to debugger Debugger.Log(0, null, $"EventSource Error: {msg}{System.Environment.NewLine}"); // Send it to all listeners. WriteEventString(msg); WriteStringToAllListeners("EventSourceMessage", msg); } catch { } // If we fail during last chance logging, well, we have to give up.... } private static EventSourceSettings ValidateSettings(EventSourceSettings settings) { const EventSourceSettings evtFormatMask = EventSourceSettings.EtwManifestEventFormat | EventSourceSettings.EtwSelfDescribingEventFormat; if ((settings & evtFormatMask) == evtFormatMask) { throw new ArgumentException(SR.EventSource_InvalidEventFormat, nameof(settings)); } // If you did not explicitly ask for manifest, you get self-describing. if ((settings & evtFormatMask) == 0) settings |= EventSourceSettings.EtwSelfDescribingEventFormat; return settings; } private bool ThrowOnEventWriteErrors => (m_config & EventSourceSettings.ThrowOnEventWriteErrors) != 0; private bool SelfDescribingEvents { get { Debug.Assert(((m_config & EventSourceSettings.EtwManifestEventFormat) != 0) != ((m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != 0)); return (m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != 0; } } // private instance state private string m_name = null!; // My friendly name (privided in ctor) internal int m_id; // A small integer that is unique to this instance. private Guid m_guid; // GUID representing the ETW eventSource to the OS. internal volatile EventMetadata[]? m_eventData; // None per-event data private volatile byte[]? m_rawManifest; // Bytes to send out representing the event schema private EventHandler<EventCommandEventArgs>? m_eventCommandExecuted; private readonly EventSourceSettings m_config; // configuration information private bool m_eventSourceDisposed; // has Dispose been called. // Enabling bits private bool m_eventSourceEnabled; // am I enabled (any of my events are enabled for any dispatcher) internal EventLevel m_level; // highest level enabled by any output dispatcher internal EventKeywords m_matchAnyKeyword; // the logical OR of all levels enabled by any output dispatcher (zero is a special case) meaning 'all keywords' // Dispatching state internal volatile EventDispatcher? m_Dispatchers; // Linked list of code:EventDispatchers we write the data to (we also do ETW specially) #if FEATURE_MANAGED_ETW private volatile OverrideEventProvider m_etwProvider = null!; // This hooks up ETW commands to our 'OnEventCommand' callback #endif #if FEATURE_PERFTRACING private object? m_createEventLock; private IntPtr m_writeEventStringEventHandle = IntPtr.Zero; private volatile OverrideEventProvider m_eventPipeProvider = null!; #endif private bool m_completelyInited; // The EventSource constructor has returned without exception. private Exception? m_constructionException; // If there was an exception construction, this is it private byte m_outOfBandMessageCount; // The number of out of band messages sent (we throttle them private EventCommandEventArgs? m_deferredCommands; // If we get commands before we are fully we store them here and run the when we are fully inited. private string[]? m_traits; // Used to implement GetTraits [ThreadStatic] private static byte m_EventSourceExceptionRecurenceCount; // current recursion count inside ThrowEventSourceException #if FEATURE_MANAGED_ETW_CHANNELS internal volatile ulong[]? m_channelData; #endif // We use a single instance of ActivityTracker for all EventSources instances to allow correlation between multiple event providers. // We have m_activityTracker field simply because instance field is more efficient than static field fetch. private ActivityTracker m_activityTracker = null!; internal const string s_ActivityStartSuffix = "Start"; internal const string s_ActivityStopSuffix = "Stop"; // This switch controls an opt-in, off-by-default mechanism for allowing multiple EventSources to have the same // name and by extension GUID. This is not considered a mainline scenario and is explicitly intended as a release // valve for users that make heavy use of AssemblyLoadContext and experience exceptions from EventSource. // This does not solve any issues that might arise from this configuration. For instance: // // * If multiple manifest-mode EventSources have the same name/GUID, it is ambiguous which manifest should be used by an ETW parser. // This can result in events being incorrectly parse. The data will still be there, but EventTrace (or other libraries) won't // know how to parse it. // * Potential issues in parsing self-describing EventSources that use the same name/GUID, event name, and payload type from the same AssemblyLoadContext // but have different event IDs set. // // Most users should not turn this on. internal const string DuplicateSourceNamesSwitch = "System.Diagnostics.Tracing.EventSource.AllowDuplicateSourceNames"; private static readonly bool AllowDuplicateSourceNames = AppContext.TryGetSwitch(DuplicateSourceNamesSwitch, out bool isEnabled) ? isEnabled : false; // WARNING: Do not depend upon initialized statics during creation of EventSources, as it is possible for creation of an EventSource to trigger // creation of yet another EventSource. When this happens, these statics may not yet be initialized. // Rather than depending on initialized statics, use lazy initialization to ensure that the statics are initialized exactly when they are needed. #if ES_BUILD_STANDALONE // used for generating GUID from eventsource name private static byte[]? namespaceBytes; #endif #endregion } /// <summary> /// Enables specifying event source configuration options to be used in the EventSource constructor. /// </summary> [Flags] public enum EventSourceSettings { /// <summary> /// This specifies none of the special configuration options should be enabled. /// </summary> Default = 0, /// <summary> /// Normally an EventSource NEVER throws; setting this option will tell it to throw when it encounters errors. /// </summary> ThrowOnEventWriteErrors = 1, /// <summary> /// Setting this option is a directive to the ETW listener should use manifest-based format when /// firing events. This is the default option when defining a type derived from EventSource /// (using the protected EventSource constructors). /// Only one of EtwManifestEventFormat or EtwSelfDescribingEventFormat should be specified /// </summary> EtwManifestEventFormat = 4, /// <summary> /// Setting this option is a directive to the ETW listener should use self-describing event format /// when firing events. This is the default option when creating a new instance of the EventSource /// type (using the public EventSource constructors). /// Only one of EtwManifestEventFormat or EtwSelfDescribingEventFormat should be specified /// </summary> EtwSelfDescribingEventFormat = 8, } /// <summary> /// An EventListener represents a target for the events generated by EventSources (that is subclasses /// of <see cref="EventSource"/>), in the current appdomain. When a new EventListener is created /// it is logically attached to all eventSources in that appdomain. When the EventListener is Disposed, then /// it is disconnected from the event eventSources. Note that there is a internal list of STRONG references /// to EventListeners, which means that relying on the lack of references to EventListeners to clean up /// EventListeners will NOT work. You must call EventListener.Dispose explicitly when a dispatcher is no /// longer needed. /// <para> /// Once created, EventListeners can enable or disable on a per-eventSource basis using verbosity levels /// (<see cref="EventLevel"/>) and bitfields (<see cref="EventKeywords"/>) to further restrict the set of /// events to be sent to the dispatcher. The dispatcher can also send arbitrary commands to a particular /// eventSource using the 'SendCommand' method. The meaning of the commands are eventSource specific. /// </para><para> /// The Null Guid (that is (new Guid()) has special meaning as a wildcard for 'all current eventSources in /// the appdomain'. Thus it is relatively easy to turn on all events in the appdomain if desired. /// </para><para> /// It is possible for there to be many EventListener's defined in a single appdomain. Each dispatcher is /// logically independent of the other listeners. Thus when one dispatcher enables or disables events, it /// affects only that dispatcher (other listeners get the events they asked for). It is possible that /// commands sent with 'SendCommand' would do a semantic operation that would affect the other listeners /// (like doing a GC, or flushing data ...), but this is the exception rather than the rule. /// </para><para> /// Thus the model is that each EventSource keeps a list of EventListeners that it is sending events /// to. Associated with each EventSource-dispatcher pair is a set of filtering criteria that determine for /// that eventSource what events that dispatcher will receive. /// </para><para> /// Listeners receive the events on their 'OnEventWritten' method. Thus subclasses of EventListener must /// override this method to do something useful with the data. /// </para><para> /// In addition, when new eventSources are created, the 'OnEventSourceCreate' method is called. The /// invariant associated with this callback is that every eventSource gets exactly one /// 'OnEventSourceCreate' call for ever eventSource that can potentially send it log messages. In /// particular when a EventListener is created, typically a series of OnEventSourceCreate' calls are /// made to notify the new dispatcher of all the eventSources that existed before the EventListener was /// created. /// </para> /// </summary> public class EventListener : IDisposable { private event EventHandler<EventSourceCreatedEventArgs>? _EventSourceCreated; /// <summary> /// This event is raised whenever a new eventSource is 'attached' to the dispatcher. /// This can happen for all existing EventSources when the EventListener is created /// as well as for any EventSources that come into existence after the EventListener /// has been created. /// /// These 'catch up' events are called during the construction of the EventListener. /// Subclasses need to be prepared for that. /// /// In a multi-threaded environment, it is possible that 'EventSourceEventWrittenCallback' /// events for a particular eventSource to occur BEFORE the EventSourceCreatedCallback is issued. /// </summary> public event EventHandler<EventSourceCreatedEventArgs>? EventSourceCreated { add { CallBackForExistingEventSources(false, value); this._EventSourceCreated = (EventHandler<EventSourceCreatedEventArgs>?)Delegate.Combine(_EventSourceCreated, value); } remove { this._EventSourceCreated = (EventHandler<EventSourceCreatedEventArgs>?)Delegate.Remove(_EventSourceCreated, value); } } /// <summary> /// This event is raised whenever an event has been written by a EventSource for which /// the EventListener has enabled events. /// </summary> public event EventHandler<EventWrittenEventArgs>? EventWritten; static EventListener() { #if FEATURE_PERFTRACING // This allows NativeRuntimeEventSource to get initialized so that EventListeners can subscribe to the runtime events emitted from // native side. GC.KeepAlive(NativeRuntimeEventSource.Log); #endif } /// <summary> /// Create a new EventListener in which all events start off turned off (use EnableEvents to turn /// them on). /// </summary> public EventListener() { // This will cause the OnEventSourceCreated callback to fire. CallBackForExistingEventSources(true, (obj, args) => args.EventSource!.AddListener((EventListener)obj!)); } /// <summary> /// Dispose should be called when the EventListener no longer desires 'OnEvent*' callbacks. Because /// there is an internal list of strong references to all EventListeners, calling 'Dispose' directly /// is the only way to actually make the listen die. Thus it is important that users of EventListener /// call Dispose when they are done with their logging. /// </summary> public virtual void Dispose() { lock (EventListenersLock) { if (s_Listeners != null) { if (this == s_Listeners) { EventListener cur = s_Listeners; s_Listeners = this.m_Next; RemoveReferencesToListenerInEventSources(cur); } else { // Find 'this' from the s_Listeners linked list. EventListener prev = s_Listeners; while (true) { EventListener? cur = prev.m_Next; if (cur == null) break; if (cur == this) { // Found our Listener, remove references to it in the eventSources prev.m_Next = cur.m_Next; // Remove entry. RemoveReferencesToListenerInEventSources(cur); break; } prev = cur; } } } Validate(); } } // We don't expose a Dispose(bool), because the contract is that you don't have any non-syncronous // 'cleanup' associated with this object /// <summary> /// Enable all events from the eventSource identified by 'eventSource' to the current /// dispatcher that have a verbosity level of 'level' or lower. /// /// This call can have the effect of REDUCING the number of events sent to the /// dispatcher if 'level' indicates a less verbose level than was previously enabled. /// /// This call never has an effect on other EventListeners. /// /// </summary> public void EnableEvents(EventSource eventSource, EventLevel level) { EnableEvents(eventSource, level, EventKeywords.None); } /// <summary> /// Enable all events from the eventSource identified by 'eventSource' to the current /// dispatcher that have a verbosity level of 'level' or lower and have a event keyword /// matching any of the bits in 'matchAnyKeyword'. /// /// This call can have the effect of REDUCING the number of events sent to the /// dispatcher if 'level' indicates a less verbose level than was previously enabled or /// if 'matchAnyKeyword' has fewer keywords set than where previously set. /// /// This call never has an effect on other EventListeners. /// </summary> public void EnableEvents(EventSource eventSource, EventLevel level, EventKeywords matchAnyKeyword) { EnableEvents(eventSource, level, matchAnyKeyword, null); } /// <summary> /// Enable all events from the eventSource identified by 'eventSource' to the current /// dispatcher that have a verbosity level of 'level' or lower and have a event keyword /// matching any of the bits in 'matchAnyKeyword' as well as any (eventSource specific) /// effect passing additional 'key-value' arguments 'arguments' might have. /// /// This call can have the effect of REDUCING the number of events sent to the /// dispatcher if 'level' indicates a less verbose level than was previously enabled or /// if 'matchAnyKeyword' has fewer keywords set than where previously set. /// /// This call never has an effect on other EventListeners. /// </summary> public void EnableEvents(EventSource eventSource!!, EventLevel level, EventKeywords matchAnyKeyword, IDictionary<string, string?>? arguments) { eventSource.SendCommand(this, EventProviderType.None, 0, 0, EventCommand.Update, true, level, matchAnyKeyword, arguments); #if FEATURE_PERFTRACING if (eventSource.GetType() == typeof(NativeRuntimeEventSource)) { EventPipeEventDispatcher.Instance.SendCommand(this, EventCommand.Update, true, level, matchAnyKeyword); } #endif // FEATURE_PERFTRACING } /// <summary> /// Disables all events coming from eventSource identified by 'eventSource'. /// /// This call never has an effect on other EventListeners. /// </summary> public void DisableEvents(EventSource eventSource!!) { eventSource.SendCommand(this, EventProviderType.None, 0, 0, EventCommand.Update, false, EventLevel.LogAlways, EventKeywords.None, null); #if FEATURE_PERFTRACING if (eventSource.GetType() == typeof(NativeRuntimeEventSource)) { EventPipeEventDispatcher.Instance.SendCommand(this, EventCommand.Update, false, EventLevel.LogAlways, EventKeywords.None); } #endif // FEATURE_PERFTRACING } /// <summary> /// EventSourceIndex is small non-negative integer (suitable for indexing in an array) /// identifying EventSource. It is unique per-appdomain. Some EventListeners might find /// it useful to store additional information about each eventSource connected to it, /// and EventSourceIndex allows this extra information to be efficiently stored in a /// (growable) array (eg List(T)). /// </summary> public static int EventSourceIndex(EventSource eventSource) { return eventSource.m_id; } /// <summary> /// This method is called whenever a new eventSource is 'attached' to the dispatcher. /// This can happen for all existing EventSources when the EventListener is created /// as well as for any EventSources that come into existence after the EventListener /// has been created. /// /// These 'catch up' events are called during the construction of the EventListener. /// Subclasses need to be prepared for that. /// /// In a multi-threaded environment, it is possible that 'OnEventWritten' callbacks /// for a particular eventSource to occur BEFORE the OnEventSourceCreated is issued. /// </summary> /// <param name="eventSource"></param> protected internal virtual void OnEventSourceCreated(EventSource eventSource) { EventHandler<EventSourceCreatedEventArgs>? callBack = this._EventSourceCreated; if (callBack != null) { EventSourceCreatedEventArgs args = new EventSourceCreatedEventArgs(); args.EventSource = eventSource; callBack(this, args); } } /// <summary> /// This method is called whenever an event has been written by a EventSource for which /// the EventListener has enabled events. /// </summary> /// <param name="eventData"></param> protected internal virtual void OnEventWritten(EventWrittenEventArgs eventData) { this.EventWritten?.Invoke(this, eventData); } #region private /// <summary> /// This routine adds newEventSource to the global list of eventSources, it also assigns the /// ID to the eventSource (which is simply the ordinal in the global list). /// /// EventSources currently do not pro-actively remove themselves from this list. Instead /// when eventSources's are GCed, the weak handle in this list naturally gets nulled, and /// we will reuse the slot. Today this list never shrinks (but we do reuse entries /// that are in the list). This seems OK since the expectation is that EventSources /// tend to live for the lifetime of the appdomain anyway (they tend to be used in /// global variables). /// </summary> /// <param name="newEventSource"></param> internal static void AddEventSource(EventSource newEventSource) { lock (EventListenersLock) { Debug.Assert(s_EventSources != null); #if ES_BUILD_STANDALONE // netcoreapp build calls DisposeOnShutdown directly from AppContext.OnProcessExit if (!s_EventSourceShutdownRegistered) { s_EventSourceShutdownRegistered = true; AppDomain.CurrentDomain.ProcessExit += DisposeOnShutdown; AppDomain.CurrentDomain.DomainUnload += DisposeOnShutdown; } #endif // Periodically search the list for existing entries to reuse, this avoids // unbounded memory use if we keep recycling eventSources (an unlikely thing). int newIndex = -1; if (s_EventSources.Count % 64 == 63) // on every block of 64, fill up the block before continuing { int i = s_EventSources.Count; // Work from the top down. while (0 < i) { --i; WeakReference<EventSource> weakRef = s_EventSources[i]; if (!weakRef.TryGetTarget(out _)) { newIndex = i; weakRef.SetTarget(newEventSource); break; } } } if (newIndex < 0) { newIndex = s_EventSources.Count; s_EventSources.Add(new WeakReference<EventSource>(newEventSource)); } newEventSource.m_id = newIndex; #if DEBUG // Disable validation of EventSource/EventListener connections in case a call to EventSource.AddListener // causes a recursive call into this method. bool previousValue = s_ConnectingEventSourcesAndListener; s_ConnectingEventSourcesAndListener = true; try { #endif // Add every existing dispatcher to the new EventSource for (EventListener? listener = s_Listeners; listener != null; listener = listener.m_Next) newEventSource.AddListener(listener); #if DEBUG } finally { s_ConnectingEventSourcesAndListener = previousValue; } #endif Validate(); } } // Whenver we have async callbacks from native code, there is an ugly issue where // during .NET shutdown native code could be calling the callback, but the CLR // has already prohibited callbacks to managed code in the appdomain, causing the CLR // to throw a COMPLUS_BOOT_EXCEPTION. The guideline we give is that you must unregister // such callbacks on process shutdown or appdomain so that unmanaged code will never // do this. This is what this callback is for. // See bug 724140 for more #if ES_BUILD_STANDALONE private static void DisposeOnShutdown(object? sender, EventArgs e) #else internal static void DisposeOnShutdown() #endif { Debug.Assert(EventSource.IsSupported); List<EventSource> sourcesToDispose = new List<EventSource>(); lock (EventListenersLock) { Debug.Assert(s_EventSources != null); foreach (WeakReference<EventSource> esRef in s_EventSources) { if (esRef.TryGetTarget(out EventSource? es)) { sourcesToDispose.Add(es); } } } // Do not invoke Dispose under the lock as this can lead to a deadlock. // See https://github.com/dotnet/runtime/issues/48342 for details. Debug.Assert(!Monitor.IsEntered(EventListenersLock)); foreach (EventSource es in sourcesToDispose) { es.Dispose(); } } /// <summary> /// Helper used in code:Dispose that removes any references to 'listenerToRemove' in any of the /// eventSources in the appdomain. /// /// The EventListenersLock must be held before calling this routine. /// </summary> private static void RemoveReferencesToListenerInEventSources(EventListener listenerToRemove) { #if !ES_BUILD_STANDALONE Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif // Foreach existing EventSource in the appdomain Debug.Assert(s_EventSources != null); foreach (WeakReference<EventSource> eventSourceRef in s_EventSources) { if (eventSourceRef.TryGetTarget(out EventSource? eventSource)) { Debug.Assert(eventSource.m_Dispatchers != null); // Is the first output dispatcher the dispatcher we are removing? if (eventSource.m_Dispatchers.m_Listener == listenerToRemove) eventSource.m_Dispatchers = eventSource.m_Dispatchers.m_Next; else { // Remove 'listenerToRemove' from the eventSource.m_Dispatchers linked list. EventDispatcher? prev = eventSource.m_Dispatchers; while (true) { EventDispatcher? cur = prev.m_Next; if (cur == null) { Debug.Fail("EventSource did not have a registered EventListener!"); break; } if (cur.m_Listener == listenerToRemove) { prev.m_Next = cur.m_Next; // Remove entry. break; } prev = cur; } } } } #if FEATURE_PERFTRACING // Remove the listener from the EventPipe dispatcher. EventPipeEventDispatcher.Instance.RemoveEventListener(listenerToRemove); #endif // FEATURE_PERFTRACING } /// <summary> /// Checks internal consistency of EventSources/Listeners. /// </summary> [Conditional("DEBUG")] internal static void Validate() { #if DEBUG // Don't run validation code if we're in the middle of modifying the connections between EventSources and EventListeners. if (s_ConnectingEventSourcesAndListener) { return; } #endif lock (EventListenersLock) { Debug.Assert(s_EventSources != null); // Get all listeners Dictionary<EventListener, bool> allListeners = new Dictionary<EventListener, bool>(); EventListener? cur = s_Listeners; while (cur != null) { allListeners.Add(cur, true); cur = cur.m_Next; } // For all eventSources int id = -1; foreach (WeakReference<EventSource> eventSourceRef in s_EventSources) { id++; if (!eventSourceRef.TryGetTarget(out EventSource? eventSource)) continue; Debug.Assert(eventSource.m_id == id, "Unexpected event source ID."); // None listeners on eventSources exist in the dispatcher list. EventDispatcher? dispatcher = eventSource.m_Dispatchers; while (dispatcher != null) { Debug.Assert(allListeners.ContainsKey(dispatcher.m_Listener), "EventSource has a listener not on the global list."); dispatcher = dispatcher.m_Next; } // Every dispatcher is on Dispatcher List of every eventSource. foreach (EventListener listener in allListeners.Keys) { dispatcher = eventSource.m_Dispatchers; while (true) { Debug.Assert(dispatcher != null, "Listener is not on all eventSources."); if (dispatcher.m_Listener == listener) break; dispatcher = dispatcher.m_Next; } } } } } /// <summary> /// Gets a global lock that is intended to protect the code:s_Listeners linked list and the /// code:s_EventSources list. (We happen to use the s_EventSources list as the lock object) /// </summary> internal static object EventListenersLock { get { if (s_EventSources == null) Interlocked.CompareExchange(ref s_EventSources, new List<WeakReference<EventSource>>(2), null); return s_EventSources; } } private void CallBackForExistingEventSources(bool addToListenersList, EventHandler<EventSourceCreatedEventArgs>? callback) { lock (EventListenersLock) { Debug.Assert(s_EventSources != null); // Disallow creating EventListener reentrancy. if (s_CreatingListener) { throw new InvalidOperationException(SR.EventSource_ListenerCreatedInsideCallback); } try { s_CreatingListener = true; if (addToListenersList) { // Add to list of listeners in the system, do this BEFORE firing the 'OnEventSourceCreated' so that // Those added sources see this listener. this.m_Next = s_Listeners; s_Listeners = this; } if (callback != null) { // Find all existing eventSources call OnEventSourceCreated to 'catchup' // Note that we DO have reentrancy here because 'AddListener' calls out to user code (via OnEventSourceCreated callback) // We tolerate this by iterating over a copy of the list here. New event sources will take care of adding listeners themselves // EventSources are not guaranteed to be added at the end of the s_EventSource list -- We re-use slots when a new source // is created. WeakReference<EventSource>[] eventSourcesSnapshot = s_EventSources.ToArray(); #if DEBUG bool previousValue = s_ConnectingEventSourcesAndListener; s_ConnectingEventSourcesAndListener = true; try { #endif for (int i = 0; i < eventSourcesSnapshot.Length; i++) { WeakReference<EventSource> eventSourceRef = eventSourcesSnapshot[i]; if (eventSourceRef.TryGetTarget(out EventSource? eventSource)) { EventSourceCreatedEventArgs args = new EventSourceCreatedEventArgs(); args.EventSource = eventSource; callback(this, args); } } #if DEBUG } finally { s_ConnectingEventSourcesAndListener = previousValue; } #endif } Validate(); } finally { s_CreatingListener = false; } } } // Instance fields internal volatile EventListener? m_Next; // These form a linked list in s_Listeners // static fields /// <summary> /// The list of all listeners in the appdomain. Listeners must be explicitly disposed to remove themselves /// from this list. Note that EventSources point to their listener but NOT the reverse. /// </summary> internal static EventListener? s_Listeners; /// <summary> /// The list of all active eventSources in the appdomain. Note that eventSources do NOT /// remove themselves from this list this is a weak list and the GC that removes them may /// not have happened yet. Thus it can contain event sources that are dead (thus you have /// to filter those out. /// </summary> internal static List<WeakReference<EventSource>>? s_EventSources; /// <summary> /// Used to disallow reentrancy. /// </summary> private static bool s_CreatingListener; #if DEBUG /// <summary> /// Used to disable validation of EventSource and EventListener connectivity. /// This is needed when an EventListener is in the middle of being published to all EventSources /// and another EventSource is created as part of the process. /// </summary> [ThreadStatic] private static bool s_ConnectingEventSourcesAndListener; #endif #if ES_BUILD_STANDALONE /// <summary> /// Used to register AD/Process shutdown callbacks. /// </summary> private static bool s_EventSourceShutdownRegistered; #endif #endregion } /// <summary> /// Passed to the code:EventSource.OnEventCommand callback /// </summary> public class EventCommandEventArgs : EventArgs { /// <summary> /// Gets the command for the callback. /// </summary> public EventCommand Command { get; internal set; } /// <summary> /// Gets the arguments for the callback. /// </summary> public IDictionary<string, string?>? Arguments { get; internal set; } /// <summary> /// Enables the event that has the specified identifier. /// </summary> /// <param name="eventId">Event ID of event to be enabled</param> /// <returns>true if eventId is in range</returns> public bool EnableEvent(int eventId) { if (Command != EventCommand.Enable && Command != EventCommand.Disable) throw new InvalidOperationException(); return eventSource.EnableEventForDispatcher(dispatcher, eventProviderType, eventId, true); } /// <summary> /// Disables the event that have the specified identifier. /// </summary> /// <param name="eventId">Event ID of event to be disabled</param> /// <returns>true if eventId is in range</returns> public bool DisableEvent(int eventId) { if (Command != EventCommand.Enable && Command != EventCommand.Disable) throw new InvalidOperationException(); return eventSource.EnableEventForDispatcher(dispatcher, eventProviderType, eventId, false); } #region private internal EventCommandEventArgs(EventCommand command, IDictionary<string, string?>? arguments, EventSource eventSource, EventListener? listener, EventProviderType eventProviderType, int perEventSourceSessionId, int etwSessionId, bool enable, EventLevel level, EventKeywords matchAnyKeyword) { this.Command = command; this.Arguments = arguments; this.eventSource = eventSource; this.listener = listener; this.eventProviderType = eventProviderType; this.perEventSourceSessionId = perEventSourceSessionId; this.etwSessionId = etwSessionId; this.enable = enable; this.level = level; this.matchAnyKeyword = matchAnyKeyword; } internal EventSource eventSource; internal EventDispatcher? dispatcher; internal EventProviderType eventProviderType; // These are the arguments of sendCommand and are only used for deferring commands until after we are fully initialized. internal EventListener? listener; internal int perEventSourceSessionId; internal int etwSessionId; internal bool enable; internal EventLevel level; internal EventKeywords matchAnyKeyword; internal EventCommandEventArgs? nextCommand; // We form a linked list of these deferred commands. #endregion } /// <summary> /// EventSourceCreatedEventArgs is passed to <see cref="EventListener.EventSourceCreated"/> /// </summary> public class EventSourceCreatedEventArgs : EventArgs { /// <summary> /// The EventSource that is attaching to the listener. /// </summary> public EventSource? EventSource { get; internal set; } } /// <summary> /// EventWrittenEventArgs is passed to the user-provided override for /// <see cref="EventListener.OnEventWritten"/> when an event is fired. /// </summary> public class EventWrittenEventArgs : EventArgs { internal static readonly ReadOnlyCollection<object?> EmptyPayload = new(Array.Empty<object>()); private ref EventSource.EventMetadata Metadata => ref EventSource.m_eventData![EventId]; /// <summary> /// The name of the event. /// </summary> public string? EventName { get => _moreInfo?.EventName ?? (EventId <= 0 ? null : Metadata.Name); internal set => MoreInfo.EventName = value; } /// <summary> /// Gets the event ID for the event that was written. /// </summary> public int EventId { get; } private Guid _activityId; /// <summary> /// Gets the activity ID for the thread on which the event was written. /// </summary> public Guid ActivityId { get { if (_activityId == Guid.Empty) { _activityId = EventSource.CurrentThreadActivityId; } return _activityId; } } /// <summary> /// Gets the related activity ID if one was specified when the event was written. /// </summary> public Guid RelatedActivityId => _moreInfo?.RelatedActivityId ?? default; /// <summary> /// Gets the payload for the event. /// </summary> public ReadOnlyCollection<object?>? Payload { get; internal set; } /// <summary> /// Gets the payload argument names. /// </summary> public ReadOnlyCollection<string>? PayloadNames { get => _moreInfo?.PayloadNames ?? (EventId <= 0 ? null : Metadata.ParameterNames); internal set => MoreInfo.PayloadNames = value; } /// <summary> /// Gets the event source object. /// </summary> public EventSource EventSource { get; } /// <summary> /// Gets the keywords for the event. /// </summary> public EventKeywords Keywords { get => EventId <= 0 ? (_moreInfo?.Keywords ?? default) : (EventKeywords)Metadata.Descriptor.Keywords; internal set => MoreInfo.Keywords = value; } /// <summary> /// Gets the operation code for the event. /// </summary> public EventOpcode Opcode { get => EventId <= 0 ? (_moreInfo?.Opcode ?? default) : (EventOpcode)Metadata.Descriptor.Opcode; internal set => MoreInfo.Opcode = value; } /// <summary> /// Gets the task for the event. /// </summary> public EventTask Task => EventId <= 0 ? EventTask.None : (EventTask)Metadata.Descriptor.Task; /// <summary> /// Any provider/user defined options associated with the event. /// </summary> public EventTags Tags { get => EventId <= 0 ? (_moreInfo?.Tags ?? default) : Metadata.Tags; internal set => MoreInfo.Tags = value; } /// <summary> /// Gets the message for the event. If the message has {N} parameters they are NOT substituted. /// </summary> public string? Message { get => _moreInfo?.Message ?? (EventId <= 0 ? null : Metadata.Message); internal set => MoreInfo.Message = value; } #if FEATURE_MANAGED_ETW_CHANNELS /// <summary> /// Gets the channel for the event. /// </summary> public EventChannel Channel => EventId <= 0 ? EventChannel.None : (EventChannel)Metadata.Descriptor.Channel; #endif /// <summary> /// Gets the version of the event. /// </summary> public byte Version => EventId <= 0 ? (byte)0 : Metadata.Descriptor.Version; /// <summary> /// Gets the level for the event. /// </summary> public EventLevel Level { get => EventId <= 0 ? (_moreInfo?.Level ?? default) : (EventLevel)Metadata.Descriptor.Level; internal set => MoreInfo.Level = value; } /// <summary> /// Gets the identifier for the OS thread that wrote the event. /// </summary> public long OSThreadId { get { ref long? osThreadId = ref MoreInfo.OsThreadId; if (!osThreadId.HasValue) { #if ES_BUILD_STANDALONE osThreadId = (long)Interop.Kernel32.GetCurrentThreadId(); #else osThreadId = (long)Thread.CurrentOSThreadId; #endif } return osThreadId.Value; } internal set => MoreInfo.OsThreadId = value; } /// <summary> /// Gets a UTC DateTime that specifies when the event was written. /// </summary> public DateTime TimeStamp { get; internal set; } internal EventWrittenEventArgs(EventSource eventSource, int eventId) { EventSource = eventSource; EventId = eventId; TimeStamp = DateTime.UtcNow; } internal unsafe EventWrittenEventArgs(EventSource eventSource, int eventId, Guid* pActivityID, Guid* pChildActivityID) : this(eventSource, eventId) { if (pActivityID != null) { _activityId = *pActivityID; } if (pChildActivityID != null) { MoreInfo.RelatedActivityId = *pChildActivityID; } } private MoreEventInfo? _moreInfo; private MoreEventInfo MoreInfo => _moreInfo ??= new MoreEventInfo(); private sealed class MoreEventInfo { public string? Message; public string? EventName; public ReadOnlyCollection<string>? PayloadNames; public Guid RelatedActivityId; public long? OsThreadId; public EventTags Tags; public EventOpcode Opcode; public EventLevel Level; public EventKeywords Keywords; } } /// <summary> /// Allows customizing defaults and specifying localization support for the event source class to which it is applied. /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class EventSourceAttribute : Attribute { /// <summary> /// Overrides the ETW name of the event source (which defaults to the class name) /// </summary> public string? Name { get; set; } /// <summary> /// Overrides the default (calculated) Guid of an EventSource type. Explicitly defining a GUID is discouraged, /// except when upgrading existing ETW providers to using event sources. /// </summary> public string? Guid { get; set; } /// <summary> /// <para> /// EventSources support localization of events. The names used for events, opcodes, tasks, keywords and maps /// can be localized to several languages if desired. This works by creating a ResX style string table /// (by simply adding a 'Resource File' to your project). This resource file is given a name e.g. /// 'DefaultNameSpace.ResourceFileName' which can be passed to the ResourceManager constructor to read the /// resources. This name is the value of the LocalizationResources property. /// </para><para> /// If LocalizationResources property is non-null, then EventSource will look up the localized strings for events by /// using the following resource naming scheme /// </para> /// <para>* event_EVENTNAME</para> /// <para>* task_TASKNAME</para> /// <para>* keyword_KEYWORDNAME</para> /// <para>* map_MAPNAME</para> /// <para> /// where the capitalized name is the name of the event, task, keyword, or map value that should be localized. /// Note that the localized string for an event corresponds to the Message string, and can have {0} values /// which represent the payload values. /// </para> /// </summary> public string? LocalizationResources { get; set; } } /// <summary> /// Any instance methods in a class that subclasses <see cref="EventSource"/> and that return void are /// assumed by default to be methods that generate an ETW event. Enough information can be deduced from the /// name of the method and its signature to generate basic schema information for the event. The /// <see cref="EventAttribute"/> class allows you to specify additional event schema information for an event if /// desired. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class EventAttribute : Attribute { /// <summary>Construct an EventAttribute with specified eventId</summary> /// <param name="eventId">ID of the ETW event (an integer between 1 and 65535)</param> public EventAttribute(int eventId) { this.EventId = eventId; Level = EventLevel.Informational; } /// <summary>Event's ID</summary> public int EventId { get; private set; } /// <summary>Event's severity level: indicates the severity or verbosity of the event</summary> public EventLevel Level { get; set; } /// <summary>Event's keywords: allows classification of events by "categories"</summary> public EventKeywords Keywords { get; set; } /// <summary>Event's operation code: allows defining operations, generally used with Tasks</summary> public EventOpcode Opcode { get => m_opcode; set { this.m_opcode = value; this.m_opcodeSet = true; } } internal bool IsOpcodeSet => m_opcodeSet; /// <summary>Event's task: allows logical grouping of events</summary> public EventTask Task { get; set; } #if FEATURE_MANAGED_ETW_CHANNELS /// <summary>Event's channel: defines an event log as an additional destination for the event</summary> public EventChannel Channel { get; set; } #endif /// <summary>Event's version</summary> public byte Version { get; set; } /// <summary> /// This can be specified to enable formatting and localization of the event's payload. You can /// use standard .NET substitution operators (eg {1}) in the string and they will be replaced /// with the 'ToString()' of the corresponding part of the event payload. /// </summary> public string? Message { get; set; } /// <summary> /// User defined options associated with the event. These do not have meaning to the EventSource but /// are passed through to listeners which given them semantics. /// </summary> public EventTags Tags { get; set; } /// <summary> /// Allows fine control over the Activity IDs generated by start and stop events /// </summary> public EventActivityOptions ActivityOptions { get; set; } #region private private EventOpcode m_opcode; private bool m_opcodeSet; #endregion } /// <summary> /// By default all instance methods in a class that subclasses code:EventSource that and return /// void are assumed to be methods that generate an event. This default can be overridden by specifying /// the code:NonEventAttribute /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class NonEventAttribute : Attribute { /// <summary> /// Constructs a default NonEventAttribute /// </summary> public NonEventAttribute() { } } // FUTURE we may want to expose this at some point once we have a partner that can help us validate the design. #if FEATURE_MANAGED_ETW_CHANNELS /// <summary> /// EventChannelAttribute allows customizing channels supported by an EventSource. This attribute must be /// applied to an member of type EventChannel defined in a Channels class nested in the EventSource class: /// <code> /// public static class Channels /// { /// [Channel(Enabled = true, EventChannelType = EventChannelType.Admin)] /// public const EventChannel Admin = (EventChannel)16; /// /// [Channel(Enabled = false, EventChannelType = EventChannelType.Operational)] /// public const EventChannel Operational = (EventChannel)17; /// } /// </code> /// </summary> [AttributeUsage(AttributeTargets.Field)] #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS public #else internal #endif class EventChannelAttribute : Attribute { /// <summary> /// Specified whether the channel is enabled by default /// </summary> public bool Enabled { get; set; } /// <summary> /// Legal values are in EventChannelType /// </summary> public EventChannelType EventChannelType { get; set; } #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS /// <summary> /// Specifies the isolation for the channel /// </summary> public EventChannelIsolation Isolation { get; set; } /// <summary> /// Specifies an SDDL access descriptor that controls access to the log file that backs the channel. /// See MSDN (https://docs.microsoft.com/en-us/windows/desktop/WES/eventmanifestschema-channeltype-complextype) for details. /// </summary> public string? Access { get; set; } /// <summary> /// Allows importing channels defined in external manifests /// </summary> public string? ImportChannel { get; set; } #endif // TODO: there is a convention that the name is the Provider/Type Should we provide an override? // public string Name { get; set; } } /// <summary> /// Allowed channel types /// </summary> #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS public #else internal #endif enum EventChannelType { /// <summary>The admin channel</summary> Admin = 1, /// <summary>The operational channel</summary> Operational, /// <summary>The Analytic channel</summary> Analytic, /// <summary>The debug channel</summary> Debug, } #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS /// <summary> /// Allowed isolation levels. See MSDN (https://docs.microsoft.com/en-us/windows/desktop/WES/eventmanifestschema-channeltype-complextype) /// for the default permissions associated with each level. EventChannelIsolation and Access allows control over the /// access permissions for the channel and backing file. /// </summary> public enum EventChannelIsolation { /// <summary> /// This is the default isolation level. All channels that specify Application isolation use the same ETW session /// </summary> Application = 1, /// <summary> /// All channels that specify System isolation use the same ETW session /// </summary> System, /// <summary> /// Use sparingly! When specifying Custom isolation, a separate ETW session is created for the channel. /// Using Custom isolation lets you control the access permissions for the channel and backing file. /// Because there are only 64 ETW sessions available, you should limit your use of Custom isolation. /// </summary> Custom, } #endif #endif /// <summary> /// Describes the pre-defined command (EventCommandEventArgs.Command property) that is passed to the OnEventCommand callback. /// </summary> public enum EventCommand { /// <summary> /// Update EventSource state /// </summary> Update = 0, /// <summary> /// Request EventSource to generate and send its manifest /// </summary> SendManifest = -1, /// <summary> /// Enable event /// </summary> Enable = -2, /// <summary> /// Disable event /// </summary> Disable = -3 } #region private classes // holds a bitfield representing a session mask /// <summary> /// A SessionMask represents a set of (at most MAX) sessions as a bit mask. The perEventSourceSessionId /// is the index in the SessionMask of the bit that will be set. These can translate to /// EventSource's reserved keywords bits using the provided ToEventKeywords() and /// FromEventKeywords() methods. /// </summary> internal struct SessionMask { public SessionMask(SessionMask m) { m_mask = m.m_mask; } public SessionMask(uint mask = 0) { m_mask = mask & MASK; } public bool IsEqualOrSupersetOf(SessionMask m) { return (this.m_mask | m.m_mask) == this.m_mask; } public static SessionMask All => new SessionMask(MASK); public static SessionMask FromId(int perEventSourceSessionId) { Debug.Assert(perEventSourceSessionId < MAX); return new SessionMask((uint)1 << perEventSourceSessionId); } public ulong ToEventKeywords() { return (ulong)m_mask << SHIFT_SESSION_TO_KEYWORD; } public static SessionMask FromEventKeywords(ulong m) { return new SessionMask((uint)(m >> SHIFT_SESSION_TO_KEYWORD)); } public bool this[int perEventSourceSessionId] { get { Debug.Assert(perEventSourceSessionId < MAX); return (m_mask & (1 << perEventSourceSessionId)) != 0; } set { Debug.Assert(perEventSourceSessionId < MAX); if (value) m_mask |= ((uint)1 << perEventSourceSessionId); else m_mask &= ~((uint)1 << perEventSourceSessionId); } } public static SessionMask operator |(SessionMask m1, SessionMask m2) => new SessionMask(m1.m_mask | m2.m_mask); public static SessionMask operator &(SessionMask m1, SessionMask m2) => new SessionMask(m1.m_mask & m2.m_mask); public static SessionMask operator ^(SessionMask m1, SessionMask m2) => new SessionMask(m1.m_mask ^ m2.m_mask); public static SessionMask operator ~(SessionMask m) => new SessionMask(MASK & ~(m.m_mask)); public static explicit operator ulong(SessionMask m) => m.m_mask; public static explicit operator uint(SessionMask m) => m.m_mask; private uint m_mask; internal const int SHIFT_SESSION_TO_KEYWORD = 44; // bits 44-47 inclusive are reserved internal const uint MASK = 0x0fU; // the mask of 4 reserved bits internal const uint MAX = 4; // maximum number of simultaneous ETW sessions supported } /// <summary> /// code:EventDispatchers are a simple 'helper' structure that holds the filtering state /// (m_EventEnabled) for a particular EventSource X EventListener tuple /// /// Thus a single EventListener may have many EventDispatchers (one for every EventSource /// that EventListener has activate) and a Single EventSource may also have many /// event Dispatchers (one for every EventListener that has activated it). /// /// Logically a particular EventDispatcher belongs to exactly one EventSource and exactly /// one EventListener (although EventDispatcher does not 'remember' the EventSource it is /// associated with. /// </summary> internal sealed class EventDispatcher { internal EventDispatcher(EventDispatcher? next, bool[]? eventEnabled, EventListener listener) { m_Next = next; m_EventEnabled = eventEnabled; m_Listener = listener; } // Instance fields internal readonly EventListener m_Listener; // The dispatcher this entry is for internal bool[]? m_EventEnabled; // For every event in a the eventSource, is it enabled? // Only guaranteed to exist after a InsureInit() internal EventDispatcher? m_Next; // These form a linked list in code:EventSource.m_Dispatchers // Of all listeners for that eventSource. } /// <summary> /// Flags that can be used with EventSource.GenerateManifest to control how the ETW manifest for the EventSource is /// generated. /// </summary> [Flags] public enum EventManifestOptions { /// <summary> /// Only the resources associated with current UI culture are included in the manifest /// </summary> None = 0x0, /// <summary> /// Throw exceptions for any inconsistency encountered /// </summary> Strict = 0x1, /// <summary> /// Generate a "resources" node under "localization" for every satellite assembly provided /// </summary> AllCultures = 0x2, /// <summary> /// Generate the manifest only if the event source needs to be registered on the machine, /// otherwise return null (but still perform validation if Strict is specified) /// </summary> OnlyIfNeededForRegistration = 0x4, /// <summary> /// When generating the manifest do *not* enforce the rule that the current EventSource class /// must be the base class for the user-defined type passed in. This allows validation of .net /// event sources using the new validation code /// </summary> AllowEventSourceOverride = 0x8, } /// <summary> /// ManifestBuilder is designed to isolate the details of the message of the event from the /// rest of EventSource. This one happens to create XML. /// </summary> internal sealed class ManifestBuilder { /// <summary> /// Build a manifest for 'providerName' with the given GUID, which will be packaged into 'dllName'. /// 'resources, is a resource manager. If specified all messages are localized using that manager. /// </summary> public ManifestBuilder(string providerName, Guid providerGuid, string? dllName, ResourceManager? resources, EventManifestOptions flags) { #if FEATURE_MANAGED_ETW_CHANNELS this.providerName = providerName; #endif this.flags = flags; this.resources = resources; sb = new StringBuilder(); events = new StringBuilder(); templates = new StringBuilder(); opcodeTab = new Dictionary<int, string>(); stringTab = new Dictionary<string, string>(); errors = new List<string>(); perEventByteArrayArgIndices = new Dictionary<string, List<int>>(); sb.AppendLine("<instrumentationManifest xmlns=\"http://schemas.microsoft.com/win/2004/08/events\">"); sb.AppendLine(" <instrumentation xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:win=\"http://manifests.microsoft.com/win/2004/08/windows/events\">"); sb.AppendLine(" <events xmlns=\"http://schemas.microsoft.com/win/2004/08/events\">"); sb.Append($"<provider name=\"{providerName}\" guid=\"{{{providerGuid}}}\""); if (dllName != null) sb.Append($" resourceFileName=\"{dllName}\" messageFileName=\"{dllName}\""); string symbolsName = providerName.Replace("-", "").Replace('.', '_'); // Period and - are illegal replace them. sb.AppendLine($" symbol=\"{symbolsName}\">"); } public void AddOpcode(string name, int value) { if ((flags & EventManifestOptions.Strict) != 0) { if (value <= 10 || value >= 239) { ManifestError(SR.Format(SR.EventSource_IllegalOpcodeValue, name, value)); } if (opcodeTab.TryGetValue(value, out string? prevName) && !name.Equals(prevName, StringComparison.Ordinal)) { ManifestError(SR.Format(SR.EventSource_OpcodeCollision, name, prevName, value)); } } opcodeTab[value] = name; } public void AddTask(string name, int value) { if ((flags & EventManifestOptions.Strict) != 0) { if (value <= 0 || value >= 65535) { ManifestError(SR.Format(SR.EventSource_IllegalTaskValue, name, value)); } if (taskTab != null && taskTab.TryGetValue(value, out string? prevName) && !name.Equals(prevName, StringComparison.Ordinal)) { ManifestError(SR.Format(SR.EventSource_TaskCollision, name, prevName, value)); } } taskTab ??= new Dictionary<int, string>(); taskTab[value] = name; } public void AddKeyword(string name, ulong value) { if ((value & (value - 1)) != 0) // Is it a power of 2? { ManifestError(SR.Format(SR.EventSource_KeywordNeedPowerOfTwo, "0x" + value.ToString("x", CultureInfo.CurrentCulture), name), true); } if ((flags & EventManifestOptions.Strict) != 0) { if (value >= 0x0000100000000000UL && !name.StartsWith("Session", StringComparison.Ordinal)) { ManifestError(SR.Format(SR.EventSource_IllegalKeywordsValue, name, "0x" + value.ToString("x", CultureInfo.CurrentCulture))); } if (keywordTab != null && keywordTab.TryGetValue(value, out string? prevName) && !name.Equals(prevName, StringComparison.Ordinal)) { ManifestError(SR.Format(SR.EventSource_KeywordCollision, name, prevName, "0x" + value.ToString("x", CultureInfo.CurrentCulture))); } } keywordTab ??= new Dictionary<ulong, string>(); keywordTab[value] = name; } #if FEATURE_MANAGED_ETW_CHANNELS /// <summary> /// Add a channel. channelAttribute can be null /// </summary> public void AddChannel(string? name, int value, EventChannelAttribute? channelAttribute) { EventChannel chValue = (EventChannel)value; if (value < (int)EventChannel.Admin || value > 255) ManifestError(SR.Format(SR.EventSource_EventChannelOutOfRange, name, value)); else if (chValue >= EventChannel.Admin && chValue <= EventChannel.Debug && channelAttribute != null && EventChannelToChannelType(chValue) != channelAttribute.EventChannelType) { // we want to ensure developers do not define EventChannels that conflict with the builtin ones, // but we want to allow them to override the default ones... ManifestError(SR.Format(SR.EventSource_ChannelTypeDoesNotMatchEventChannelValue, name, ((EventChannel)value).ToString())); } // TODO: validate there are no conflicting manifest exposed names (generally following the format "provider/type") ulong kwd = GetChannelKeyword(chValue); channelTab ??= new Dictionary<int, ChannelInfo>(4); channelTab[value] = new ChannelInfo { Name = name, Keywords = kwd, Attribs = channelAttribute }; } private static EventChannelType EventChannelToChannelType(EventChannel channel) { #if !ES_BUILD_STANDALONE Debug.Assert(channel >= EventChannel.Admin && channel <= EventChannel.Debug); #endif return (EventChannelType)((int)channel - (int)EventChannel.Admin + (int)EventChannelType.Admin); } private static EventChannelAttribute GetDefaultChannelAttribute(EventChannel channel) { EventChannelAttribute attrib = new EventChannelAttribute(); attrib.EventChannelType = EventChannelToChannelType(channel); if (attrib.EventChannelType <= EventChannelType.Operational) attrib.Enabled = true; return attrib; } public ulong[] GetChannelData() { if (this.channelTab == null) { return Array.Empty<ulong>(); } // We create an array indexed by the channel id for fast look up. // E.g. channelMask[Admin] will give you the bit mask for Admin channel. int maxkey = -1; foreach (int item in this.channelTab.Keys) { if (item > maxkey) { maxkey = item; } } ulong[] channelMask = new ulong[maxkey + 1]; foreach (KeyValuePair<int, ChannelInfo> item in this.channelTab) { channelMask[item.Key] = item.Value.Keywords; } return channelMask; } #endif public void StartEvent(string eventName, EventAttribute eventAttribute) { Debug.Assert(numParams == 0); Debug.Assert(this.eventName == null); this.eventName = eventName; numParams = 0; byteArrArgIndices = null; events.Append(" <event value=\"").Append(eventAttribute.EventId). Append("\" version=\"").Append(eventAttribute.Version). Append("\" level=\""); AppendLevelName(events, eventAttribute.Level); events.Append("\" symbol=\"").Append(eventName).Append('"'); // at this point we add to the manifest's stringTab a message that is as-of-yet // "untranslated to manifest convention", b/c we don't have the number or position // of any byte[] args (which require string format index updates) WriteMessageAttrib(events, "event", eventName, eventAttribute.Message); if (eventAttribute.Keywords != 0) { events.Append(" keywords=\""); AppendKeywords(events, (ulong)eventAttribute.Keywords, eventName); events.Append('"'); } if (eventAttribute.Opcode != 0) { events.Append(" opcode=\"").Append(GetOpcodeName(eventAttribute.Opcode, eventName)).Append('"'); } if (eventAttribute.Task != 0) { events.Append(" task=\"").Append(GetTaskName(eventAttribute.Task, eventName)).Append('"'); } #if FEATURE_MANAGED_ETW_CHANNELS if (eventAttribute.Channel != 0) { events.Append(" channel=\"").Append(GetChannelName(eventAttribute.Channel, eventName, eventAttribute.Message)).Append('"'); } #endif } public void AddEventParameter(Type type, string name) { if (numParams == 0) templates.Append(" <template tid=\"").Append(eventName).AppendLine("Args\">"); if (type == typeof(byte[])) { // mark this index as "extraneous" (it has no parallel in the managed signature) // we use these values in TranslateToManifestConvention() byteArrArgIndices ??= new List<int>(4); byteArrArgIndices.Add(numParams); // add an extra field to the template representing the length of the binary blob numParams++; templates.Append(" <data name=\"").Append(name).AppendLine("Size\" inType=\"win:UInt32\"/>"); } numParams++; templates.Append(" <data name=\"").Append(name).Append("\" inType=\"").Append(GetTypeName(type)).Append('"'); // TODO: for 'byte*' types it assumes the user provided length is named using the same naming convention // as for 'byte[]' args (blob_arg_name + "Size") if ((type.IsArray || type.IsPointer) && type.GetElementType() == typeof(byte)) { // add "length" attribute to the "blob" field in the template (referencing the field added above) templates.Append(" length=\"").Append(name).Append("Size\""); } // ETW does not support 64-bit value maps, so we don't specify these as ETW maps if (type.IsEnum && Enum.GetUnderlyingType(type) != typeof(ulong) && Enum.GetUnderlyingType(type) != typeof(long)) { templates.Append(" map=\"").Append(type.Name).Append('"'); mapsTab ??= new Dictionary<string, Type>(); if (!mapsTab.ContainsKey(type.Name)) mapsTab.Add(type.Name, type); // Remember that we need to dump the type enumeration } templates.AppendLine("/>"); } public void EndEvent() { Debug.Assert(eventName != null); if (numParams > 0) { templates.AppendLine(" </template>"); events.Append(" template=\"").Append(eventName).Append("Args\""); } events.AppendLine("/>"); if (byteArrArgIndices != null) perEventByteArrayArgIndices[eventName] = byteArrArgIndices; // at this point we have all the information we need to translate the C# Message // to the manifest string we'll put in the stringTab string prefixedEventName = "event_" + eventName; if (stringTab.TryGetValue(prefixedEventName, out string? msg)) { msg = TranslateToManifestConvention(msg, eventName); stringTab[prefixedEventName] = msg; } eventName = null; numParams = 0; byteArrArgIndices = null; } #if FEATURE_MANAGED_ETW_CHANNELS // Channel keywords are generated one per channel to allow channel based filtering in event viewer. These keywords are autogenerated // by mc.exe for compiling a manifest and are based on the order of the channels (fields) in the Channels inner class (when advanced // channel support is enabled), or based on the order the predefined channels appear in the EventAttribute properties (for simple // support). The manifest generated *MUST* have the channels specified in the same order (that's how our computed keywords are mapped // to channels by the OS infrastructure). // If channelKeyworkds is present, and has keywords bits in the ValidPredefinedChannelKeywords then it is // assumed that the keyword for that channel should be that bit. // otherwise we allocate a channel bit for the channel. // explicit channel bits are only used by WCF to mimic an existing manifest, // so we don't dont do error checking. public ulong GetChannelKeyword(EventChannel channel, ulong channelKeyword = 0) { // strip off any non-channel keywords, since we are only interested in channels here. channelKeyword &= ValidPredefinedChannelKeywords; channelTab ??= new Dictionary<int, ChannelInfo>(4); if (channelTab.Count == MaxCountChannels) ManifestError(SR.EventSource_MaxChannelExceeded); if (!channelTab.TryGetValue((int)channel, out ChannelInfo? info)) { // If we were not given an explicit channel, allocate one. if (channelKeyword == 0) { channelKeyword = nextChannelKeywordBit; nextChannelKeywordBit >>= 1; } } else { channelKeyword = info.Keywords; } return channelKeyword; } #endif public byte[] CreateManifest() { string str = CreateManifestString(); return Encoding.UTF8.GetBytes(str); } public IList<string> Errors => errors; public bool HasResources => resources != null; /// <summary> /// When validating an event source it adds the error to the error collection. /// When not validating it throws an exception if runtimeCritical is "true". /// Otherwise the error is ignored. /// </summary> /// <param name="msg"></param> /// <param name="runtimeCritical"></param> public void ManifestError(string msg, bool runtimeCritical = false) { if ((flags & EventManifestOptions.Strict) != 0) errors.Add(msg); else if (runtimeCritical) throw new ArgumentException(msg); } private string CreateManifestString() { #if !ES_BUILD_STANDALONE Span<char> ulongHexScratch = stackalloc char[16]; // long enough for ulong.MaxValue formatted as hex #endif #if FEATURE_MANAGED_ETW_CHANNELS // Write out the channels if (channelTab != null) { sb.AppendLine(" <channels>"); var sortedChannels = new List<KeyValuePair<int, ChannelInfo>>(); foreach (KeyValuePair<int, ChannelInfo> p in channelTab) { sortedChannels.Add(p); } sortedChannels.Sort((p1, p2) => -Comparer<ulong>.Default.Compare(p1.Value.Keywords, p2.Value.Keywords)); foreach (KeyValuePair<int, ChannelInfo> kvpair in sortedChannels) { int channel = kvpair.Key; ChannelInfo channelInfo = kvpair.Value; string? channelType = null; bool enabled = false; string? fullName = null; #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS string? isolation = null; string? access = null; #endif if (channelInfo.Attribs != null) { EventChannelAttribute attribs = channelInfo.Attribs; if (Enum.IsDefined(typeof(EventChannelType), attribs.EventChannelType)) channelType = attribs.EventChannelType.ToString(); enabled = attribs.Enabled; #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS if (attribs.ImportChannel != null) { fullName = attribs.ImportChannel; elementName = "importChannel"; } if (Enum.IsDefined(typeof(EventChannelIsolation), attribs.Isolation)) isolation = attribs.Isolation.ToString(); access = attribs.Access; #endif } fullName ??= providerName + "/" + channelInfo.Name; sb.Append(" <channel chid=\"").Append(channelInfo.Name).Append("\" name=\"").Append(fullName).Append('"'); Debug.Assert(channelInfo.Name != null); WriteMessageAttrib(sb, "channel", channelInfo.Name, null); sb.Append(" value=\"").Append(channel).Append('"'); if (channelType != null) sb.Append(" type=\"").Append(channelType).Append('"'); sb.Append(" enabled=\"").Append(enabled ? "true" : "false").Append('"'); #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS if (access != null) sb.Append(" access=\"").Append(access).Append("\""); if (isolation != null) sb.Append(" isolation=\"").Append(isolation).Append("\""); #endif sb.AppendLine("/>"); } sb.AppendLine(" </channels>"); } #endif // Write out the tasks if (taskTab != null) { sb.AppendLine(" <tasks>"); var sortedTasks = new List<int>(taskTab.Keys); sortedTasks.Sort(); foreach (int task in sortedTasks) { sb.Append(" <task"); WriteNameAndMessageAttribs(sb, "task", taskTab[task]); sb.Append(" value=\"").Append(task).AppendLine("\"/>"); } sb.AppendLine(" </tasks>"); } // Write out the maps // Scoping the call to enum GetFields to a local function to limit the linker suppression #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "Trimmer does not trim enums")] #endif static FieldInfo[] GetEnumFields(Type localEnumType) { Debug.Assert(localEnumType.IsEnum); return localEnumType.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static); } if (mapsTab != null) { sb.AppendLine(" <maps>"); foreach (Type enumType in mapsTab.Values) { bool isbitmap = EventSource.IsCustomAttributeDefinedHelper(enumType, typeof(FlagsAttribute), flags); string mapKind = isbitmap ? "bitMap" : "valueMap"; sb.Append(" <").Append(mapKind).Append(" name=\"").Append(enumType.Name).AppendLine("\">"); // write out each enum value FieldInfo[] staticFields = GetEnumFields(enumType); bool anyValuesWritten = false; foreach (FieldInfo staticField in staticFields) { object? constantValObj = staticField.GetRawConstantValue(); if (constantValObj != null) { ulong hexValue; if (constantValObj is ulong) hexValue = (ulong)constantValObj; // This is the only integer type that can't be represented by a long. else hexValue = (ulong)Convert.ToInt64(constantValObj); // Handles all integer types except ulong. // ETW requires all bitmap values to be powers of 2. Skip the ones that are not. // TODO: Warn people about the dropping of values. if (isbitmap && ((hexValue & (hexValue - 1)) != 0 || hexValue == 0)) continue; #if ES_BUILD_STANDALONE string hexValueFormatted = hexValue.ToString("x", CultureInfo.InvariantCulture); #else hexValue.TryFormat(ulongHexScratch, out int charsWritten, "x"); Span<char> hexValueFormatted = ulongHexScratch.Slice(0, charsWritten); #endif sb.Append(" <map value=\"0x").Append(hexValueFormatted).Append('"'); WriteMessageAttrib(sb, "map", enumType.Name + "." + staticField.Name, staticField.Name); sb.AppendLine("/>"); anyValuesWritten = true; } } // the OS requires that bitmaps and valuemaps have at least one value or it reject the whole manifest. // To avoid that put a 'None' entry if there are no other values. if (!anyValuesWritten) { sb.Append(" <map value=\"0x0\""); WriteMessageAttrib(sb, "map", enumType.Name + ".None", "None"); sb.AppendLine("/>"); } sb.Append(" </").Append(mapKind).AppendLine(">"); } sb.AppendLine(" </maps>"); } // Write out the opcodes sb.AppendLine(" <opcodes>"); var sortedOpcodes = new List<int>(opcodeTab.Keys); sortedOpcodes.Sort(); foreach (int opcode in sortedOpcodes) { sb.Append(" <opcode"); WriteNameAndMessageAttribs(sb, "opcode", opcodeTab[opcode]); sb.Append(" value=\"").Append(opcode).AppendLine("\"/>"); } sb.AppendLine(" </opcodes>"); // Write out the keywords if (keywordTab != null) { sb.AppendLine(" <keywords>"); var sortedKeywords = new List<ulong>(keywordTab.Keys); sortedKeywords.Sort(); foreach (ulong keyword in sortedKeywords) { sb.Append(" <keyword"); WriteNameAndMessageAttribs(sb, "keyword", keywordTab[keyword]); #if ES_BUILD_STANDALONE string keywordFormatted = keyword.ToString("x", CultureInfo.InvariantCulture); #else keyword.TryFormat(ulongHexScratch, out int charsWritten, "x"); Span<char> keywordFormatted = ulongHexScratch.Slice(0, charsWritten); #endif sb.Append(" mask=\"0x").Append(keywordFormatted).AppendLine("\"/>"); } sb.AppendLine(" </keywords>"); } sb.AppendLine(" <events>"); sb.Append(events); sb.AppendLine(" </events>"); sb.AppendLine(" <templates>"); if (templates.Length > 0) { sb.Append(templates); } else { // Work around a cornercase ETW issue where a manifest with no templates causes // ETW events to not get sent to their associated channel. sb.AppendLine(" <template tid=\"_empty\"></template>"); } sb.AppendLine(" </templates>"); sb.AppendLine("</provider>"); sb.AppendLine("</events>"); sb.AppendLine("</instrumentation>"); // Output the localization information. sb.AppendLine("<localization>"); var sortedStrings = new string[stringTab.Keys.Count]; stringTab.Keys.CopyTo(sortedStrings, 0); Array.Sort<string>(sortedStrings, 0, sortedStrings.Length); CultureInfo ci = CultureInfo.CurrentUICulture; sb.Append(" <resources culture=\"").Append(ci.Name).AppendLine("\">"); sb.AppendLine(" <stringTable>"); foreach (string stringKey in sortedStrings) { string? val = GetLocalizedMessage(stringKey, ci, etwFormat: true); sb.Append(" <string id=\"").Append(stringKey).Append("\" value=\"").Append(val).AppendLine("\"/>"); } sb.AppendLine(" </stringTable>"); sb.AppendLine(" </resources>"); sb.AppendLine("</localization>"); sb.AppendLine("</instrumentationManifest>"); return sb.ToString(); } #region private private void WriteNameAndMessageAttribs(StringBuilder stringBuilder, string elementName, string name) { stringBuilder.Append(" name=\"").Append(name).Append('"'); WriteMessageAttrib(sb, elementName, name, name); } private void WriteMessageAttrib(StringBuilder stringBuilder, string elementName, string name, string? value) { string? key = null; // See if the user wants things localized. if (resources != null) { // resource fallback: strings in the neutral culture will take precedence over inline strings key = elementName + "_" + name; if (resources.GetString(key, CultureInfo.InvariantCulture) is string localizedString) value = localizedString; } if (value == null) return; key ??= elementName + "_" + name; stringBuilder.Append(" message=\"$(string.").Append(key).Append(")\""); if (stringTab.TryGetValue(key, out string? prevValue) && !prevValue.Equals(value)) { ManifestError(SR.Format(SR.EventSource_DuplicateStringKey, key), true); return; } stringTab[key] = value; } internal string? GetLocalizedMessage(string key, CultureInfo ci, bool etwFormat) { string? value = null; if (resources != null) { string? localizedString = resources.GetString(key, ci); if (localizedString != null) { value = localizedString; if (etwFormat && key.StartsWith("event_", StringComparison.Ordinal)) { string evtName = key.Substring("event_".Length); value = TranslateToManifestConvention(value, evtName); } } } if (etwFormat && value == null) stringTab.TryGetValue(key, out value); return value; } private static void AppendLevelName(StringBuilder sb, EventLevel level) { if ((int)level < 16) { sb.Append("win:"); } sb.Append(level switch // avoid boxing that comes from level.ToString() { EventLevel.LogAlways => nameof(EventLevel.LogAlways), EventLevel.Critical => nameof(EventLevel.Critical), EventLevel.Error => nameof(EventLevel.Error), EventLevel.Warning => nameof(EventLevel.Warning), EventLevel.Informational => nameof(EventLevel.Informational), EventLevel.Verbose => nameof(EventLevel.Verbose), _ => ((int)level).ToString() }); } #if FEATURE_MANAGED_ETW_CHANNELS private string? GetChannelName(EventChannel channel, string eventName, string? eventMessage) { if (channelTab == null || !channelTab.TryGetValue((int)channel, out ChannelInfo? info)) { if (channel < EventChannel.Admin) // || channel > EventChannel.Debug) ManifestError(SR.Format(SR.EventSource_UndefinedChannel, channel, eventName)); // allow channels to be auto-defined. The well known ones get their well known names, and the // rest get names Channel<N>. This allows users to modify the Manifest if they want more advanced features. channelTab ??= new Dictionary<int, ChannelInfo>(4); string channelName = channel.ToString(); // For well know channels this is a nice name, otherwise a number if (EventChannel.Debug < channel) channelName = "Channel" + channelName; // Add a 'Channel' prefix for numbers. AddChannel(channelName, (int)channel, GetDefaultChannelAttribute(channel)); if (!channelTab.TryGetValue((int)channel, out info)) ManifestError(SR.Format(SR.EventSource_UndefinedChannel, channel, eventName)); } // events that specify admin channels *must* have non-null "Message" attributes if (resources != null) eventMessage ??= resources.GetString("event_" + eventName, CultureInfo.InvariantCulture); Debug.Assert(info!.Attribs != null); if (info.Attribs.EventChannelType == EventChannelType.Admin && eventMessage == null) ManifestError(SR.Format(SR.EventSource_EventWithAdminChannelMustHaveMessage, eventName, info.Name)); return info.Name; } #endif private string GetTaskName(EventTask task, string eventName) { if (task == EventTask.None) return ""; taskTab ??= new Dictionary<int, string>(); if (!taskTab.TryGetValue((int)task, out string? ret)) ret = taskTab[(int)task] = eventName; return ret; } private string? GetOpcodeName(EventOpcode opcode, string eventName) { switch (opcode) { case EventOpcode.Info: return "win:Info"; case EventOpcode.Start: return "win:Start"; case EventOpcode.Stop: return "win:Stop"; case EventOpcode.DataCollectionStart: return "win:DC_Start"; case EventOpcode.DataCollectionStop: return "win:DC_Stop"; case EventOpcode.Extension: return "win:Extension"; case EventOpcode.Reply: return "win:Reply"; case EventOpcode.Resume: return "win:Resume"; case EventOpcode.Suspend: return "win:Suspend"; case EventOpcode.Send: return "win:Send"; case EventOpcode.Receive: return "win:Receive"; } if (opcodeTab == null || !opcodeTab.TryGetValue((int)opcode, out string? ret)) { ManifestError(SR.Format(SR.EventSource_UndefinedOpcode, opcode, eventName), true); ret = null; } return ret; } private void AppendKeywords(StringBuilder sb, ulong keywords, string eventName) { #if FEATURE_MANAGED_ETW_CHANNELS // ignore keywords associate with channels // See ValidPredefinedChannelKeywords def for more. keywords &= ~ValidPredefinedChannelKeywords; #endif bool appended = false; for (ulong bit = 1; bit != 0; bit <<= 1) { if ((keywords & bit) != 0) { string? keyword = null; if ((keywordTab == null || !keywordTab.TryGetValue(bit, out keyword)) && (bit >= (ulong)0x1000000000000)) { // do not report Windows reserved keywords in the manifest (this allows the code // to be resilient to potential renaming of these keywords) keyword = string.Empty; } if (keyword == null) { ManifestError(SR.Format(SR.EventSource_UndefinedKeyword, "0x" + bit.ToString("x", CultureInfo.CurrentCulture), eventName), true); keyword = string.Empty; } if (keyword.Length != 0) { if (appended) { sb.Append(' '); } sb.Append(keyword); appended = true; } } } } private string GetTypeName(Type type) { if (type.IsEnum) { string typeName = GetTypeName(type.GetEnumUnderlyingType()); return typeName.Replace("win:Int", "win:UInt"); // ETW requires enums to be unsigned. } switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: return "win:Boolean"; case TypeCode.Byte: return "win:UInt8"; case TypeCode.Char: case TypeCode.UInt16: return "win:UInt16"; case TypeCode.UInt32: return "win:UInt32"; case TypeCode.UInt64: return "win:UInt64"; case TypeCode.SByte: return "win:Int8"; case TypeCode.Int16: return "win:Int16"; case TypeCode.Int32: return "win:Int32"; case TypeCode.Int64: return "win:Int64"; case TypeCode.String: return "win:UnicodeString"; case TypeCode.Single: return "win:Float"; case TypeCode.Double: return "win:Double"; case TypeCode.DateTime: return "win:FILETIME"; default: if (type == typeof(Guid)) return "win:GUID"; else if (type == typeof(IntPtr)) return "win:Pointer"; else if ((type.IsArray || type.IsPointer) && type.GetElementType() == typeof(byte)) return "win:Binary"; ManifestError(SR.Format(SR.EventSource_UnsupportedEventTypeInManifest, type.Name), true); return string.Empty; } } private static void UpdateStringBuilder([NotNull] ref StringBuilder? stringBuilder, string eventMessage, int startIndex, int count) { stringBuilder ??= new StringBuilder(); stringBuilder.Append(eventMessage, startIndex, count); } private static readonly string[] s_escapes = { "&amp;", "&lt;", "&gt;", "&apos;", "&quot;", "%r", "%n", "%t" }; // Manifest messages use %N conventions for their message substitutions. Translate from // .NET conventions. We can't use RegEx for this (we are in mscorlib), so we do it 'by hand' private string TranslateToManifestConvention(string eventMessage, string evtName) { StringBuilder? stringBuilder = null; // We lazily create this int writtenSoFar = 0; for (int i = 0; ;) { if (i >= eventMessage.Length) { if (stringBuilder == null) return eventMessage; UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar); return stringBuilder.ToString(); } int chIdx; if (eventMessage[i] == '%') { // handle format message escaping character '%' by escaping it UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar); stringBuilder.Append("%%"); i++; writtenSoFar = i; } else if (i < eventMessage.Length - 1 && (eventMessage[i] == '{' && eventMessage[i + 1] == '{' || eventMessage[i] == '}' && eventMessage[i + 1] == '}')) { // handle C# escaped '{" and '}' UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar); stringBuilder.Append(eventMessage[i]); i++; i++; writtenSoFar = i; } else if (eventMessage[i] == '{') { int leftBracket = i; i++; int argNum = 0; while (i < eventMessage.Length && char.IsDigit(eventMessage[i])) { argNum = argNum * 10 + eventMessage[i] - '0'; i++; } if (i < eventMessage.Length && eventMessage[i] == '}') { i++; UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, leftBracket - writtenSoFar); int manIndex = TranslateIndexToManifestConvention(argNum, evtName); stringBuilder.Append('%').Append(manIndex); // An '!' after the insert specifier {n} will be interpreted as a literal. // We'll escape it so that mc.exe does not attempt to consider it the // beginning of a format string. if (i < eventMessage.Length && eventMessage[i] == '!') { i++; stringBuilder.Append("%!"); } writtenSoFar = i; } else { ManifestError(SR.Format(SR.EventSource_UnsupportedMessageProperty, evtName, eventMessage)); } } else if ((chIdx = "&<>'\"\r\n\t".IndexOf(eventMessage[i])) >= 0) { UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar); i++; stringBuilder.Append(s_escapes[chIdx]); writtenSoFar = i; } else i++; } } private int TranslateIndexToManifestConvention(int idx, string evtName) { if (perEventByteArrayArgIndices.TryGetValue(evtName, out List<int>? byteArrArgIndices)) { foreach (int byArrIdx in byteArrArgIndices) { if (idx >= byArrIdx) ++idx; else break; } } return idx + 1; } #if FEATURE_MANAGED_ETW_CHANNELS private sealed class ChannelInfo { public string? Name; public ulong Keywords; public EventChannelAttribute? Attribs; } #endif private readonly Dictionary<int, string> opcodeTab; private Dictionary<int, string>? taskTab; #if FEATURE_MANAGED_ETW_CHANNELS private Dictionary<int, ChannelInfo>? channelTab; #endif private Dictionary<ulong, string>? keywordTab; private Dictionary<string, Type>? mapsTab; private readonly Dictionary<string, string> stringTab; // Maps unlocalized strings to localized ones #if FEATURE_MANAGED_ETW_CHANNELS // WCF used EventSource to mimic a existing ETW manifest. To support this // in just their case, we allowed them to specify the keywords associated // with their channels explicitly. ValidPredefinedChannelKeywords is // this set of channel keywords that we allow to be explicitly set. You // can ignore these bits otherwise. internal const ulong ValidPredefinedChannelKeywords = 0xF000000000000000; private ulong nextChannelKeywordBit = 0x8000000000000000; // available Keyword bit to be used for next channel definition, grows down private const int MaxCountChannels = 8; // a manifest can defined at most 8 ETW channels #endif private readonly StringBuilder sb; // Holds the provider information. private readonly StringBuilder events; // Holds the events. private readonly StringBuilder templates; #if FEATURE_MANAGED_ETW_CHANNELS private readonly string providerName; #endif private readonly ResourceManager? resources; // Look up localized strings here. private readonly EventManifestOptions flags; private readonly IList<string> errors; // list of currently encountered errors private readonly Dictionary<string, List<int>> perEventByteArrayArgIndices; // "event_name" -> List_of_Indices_of_Byte[]_Arg // State we track between StartEvent and EndEvent. private string? eventName; // Name of the event currently being processed. private int numParams; // keeps track of the number of args the event has. private List<int>? byteArrArgIndices; // keeps track of the index of each byte[] argument #endregion } /// <summary> /// Used to send the m_rawManifest into the event dispatcher as a series of events. /// </summary> internal struct ManifestEnvelope { public const int MaxChunkSize = 0xFF00; public enum ManifestFormats : byte { SimpleXmlFormat = 1, // simply dump the XML manifest as UTF8 } #if FEATURE_MANAGED_ETW public ManifestFormats Format; public byte MajorVersion; public byte MinorVersion; public byte Magic; public ushort TotalChunks; public ushort ChunkNumber; #endif } #endregion }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/NetworkInterfaceBasicTest.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.Net.Sockets; using System.Net.Test.Common; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.NetworkInformation.Tests { public class NetworkInterfaceBasicTest { private readonly ITestOutputHelper _log; public NetworkInterfaceBasicTest(ITestOutputHelper output) { _log = output; } [Fact] public void BasicTest_GetNetworkInterfaces_AtLeastOne() { Assert.NotEqual<int>(0, NetworkInterface.GetAllNetworkInterfaces().Length); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX public void BasicTest_AccessInstanceProperties_NoExceptions() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); _log.WriteLine("Description: " + nic.Description); _log.WriteLine("ID: " + nic.Id); _log.WriteLine("IsReceiveOnly: " + nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); _log.WriteLine("Speed: " + nic.Speed); // Validate NIC speed overflow. // We've found that certain WiFi adapters will return speed of -1 when not connected. // We've found that Wi-Fi Direct Virtual Adapters return speed of -1 even when up. Assert.InRange(nic.Speed, -1, long.MaxValue); _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { Assert.Equal(6, nic.GetPhysicalAddress().GetAddressBytes().Length); } } } [Fact] [PlatformSpecific(TestPlatforms.Linux|TestPlatforms.Android)] // Some APIs are not supported on Linux and Android public void BasicTest_AccessInstanceProperties_NoExceptions_Linux() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); string description = nic.Description; Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty."); _log.WriteLine("Description: " + description); string id = nic.Id; Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty."); _log.WriteLine("ID: " + id); Assert.False(nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); try { _log.WriteLine("Speed: " + nic.Speed); Assert.InRange(nic.Speed, -1, long.MaxValue); } // We cannot guarantee this works on all devices. catch (PlatformNotSupportedException pnse) { _log.WriteLine(pnse.ToString()); } _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { Assert.Equal(6, nic.GetPhysicalAddress().GetAddressBytes().Length); } } } [Fact] [PlatformSpecific(TestPlatforms.OSX|TestPlatforms.FreeBSD)] public void BasicTest_AccessInstanceProperties_NoExceptions_Bsd() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); string description = nic.Description; Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty."); _log.WriteLine("Description: " + description); string id = nic.Id; Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty."); _log.WriteLine("ID: " + id); Assert.False(nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); _log.WriteLine("Speed: " + nic.Speed); Assert.InRange(nic.Speed, 0, long.MaxValue); _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); if (nic.Name.StartsWith("en") || nic.Name == "lo0") { // Ethernet, WIFI and loopback should have known status. Assert.True((nic.OperationalStatus == OperationalStatus.Up) || (nic.OperationalStatus == OperationalStatus.Down)); } if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { Assert.Equal(6, nic.GetPhysicalAddress().GetAddressBytes().Length); } } } [Fact] [Trait("IPv4", "true")] public void BasicTest_StaticLoopbackIndex_MatchesLoopbackNetworkInterface() { Assert.True(Capability.IPv4Support()); _log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses) { if (unicast.Address.Equals(IPAddress.Loopback)) { Assert.Equal<int>(nic.GetIPProperties().GetIPv4Properties().Index, NetworkInterface.LoopbackInterfaceIndex); Assert.True(nic.NetworkInterfaceType == NetworkInterfaceType.Loopback); return; // Only check IPv4 loopback } } } } [Fact] [Trait("IPv4", "true")] public void BasicTest_StaticLoopbackIndex_ExceptionIfV4NotSupported() { Assert.True(Capability.IPv4Support()); _log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex); } [Fact] [Trait("IPv6", "true")] public void BasicTest_StaticIPv6LoopbackIndex_MatchesLoopbackNetworkInterface() { Assert.True(Capability.IPv6Support()); _log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses) { if (unicast.Address.Equals(IPAddress.IPv6Loopback)) { Assert.Equal<int>( nic.GetIPProperties().GetIPv6Properties().Index, NetworkInterface.IPv6LoopbackInterfaceIndex); return; // Only check IPv6 loopback. } } } } [Fact] [Trait("IPv6", "true")] public void BasicTest_StaticIPv6LoopbackIndex_ExceptionIfV6NotSupported() { Assert.True(Capability.IPv6Support()); _log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX public void BasicTest_GetIPInterfaceStatistics_Success() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); _log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); _log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent); _log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [Fact] [PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux public void BasicTest_GetIPInterfaceStatistics_Success_Linux() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); Assert.Throws<PlatformNotSupportedException>(() => stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); Assert.Throws<PlatformNotSupportedException>(() => stats.NonUnicastPacketsSent); _log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [Fact] [PlatformSpecific(TestPlatforms.OSX|TestPlatforms.FreeBSD)] public void BasicTest_GetIPInterfaceStatistics_Success_Bsd() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); _log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); _log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent); Assert.Throws<PlatformNotSupportedException>(() => stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [Fact] public void BasicTest_GetIsNetworkAvailable_Success() { Assert.True(NetworkInterface.GetIsNetworkAvailable()); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/34690", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] [SkipOnPlatform(TestPlatforms.OSX | TestPlatforms.FreeBSD, "Expected behavior is different on OSX or FreeBSD")] [SkipOnPlatform(TestPlatforms.iOS | TestPlatforms.MacCatalyst | TestPlatforms.tvOS, "Not supported on Browser, iOS, MacCatalyst, or tvOS.")] [InlineData(false)] [InlineData(true)] public async Task NetworkInterface_LoopbackInterfaceIndex_MatchesReceivedPackets(bool ipv6) { using (var client = new Socket(SocketType.Dgram, ProtocolType.Udp)) using (var server = new Socket(SocketType.Dgram, ProtocolType.Udp)) { server.Bind(new IPEndPoint(ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0)); var serverEndPoint = (IPEndPoint)server.LocalEndPoint; Task<SocketReceiveMessageFromResult> receivedTask = server.ReceiveMessageFromAsync(new ArraySegment<byte>(new byte[1]), SocketFlags.None, serverEndPoint); while (!receivedTask.IsCompleted) { client.SendTo(new byte[] { 42 }, serverEndPoint); await Task.Delay(1); } Assert.Equal( (await receivedTask).PacketInformation.Interface, ipv6 ? NetworkInterface.IPv6LoopbackInterfaceIndex : NetworkInterface.LoopbackInterfaceIndex); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net.Sockets; using System.Net.Test.Common; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.NetworkInformation.Tests { public class NetworkInterfaceBasicTest { private readonly ITestOutputHelper _log; public NetworkInterfaceBasicTest(ITestOutputHelper output) { _log = output; } [Fact] public void BasicTest_GetNetworkInterfaces_AtLeastOne() { Assert.NotEqual<int>(0, NetworkInterface.GetAllNetworkInterfaces().Length); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX public void BasicTest_AccessInstanceProperties_NoExceptions() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); _log.WriteLine("Description: " + nic.Description); _log.WriteLine("ID: " + nic.Id); _log.WriteLine("IsReceiveOnly: " + nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); _log.WriteLine("Speed: " + nic.Speed); // Validate NIC speed overflow. // We've found that certain WiFi adapters will return speed of -1 when not connected. // We've found that Wi-Fi Direct Virtual Adapters return speed of -1 even when up. Assert.InRange(nic.Speed, -1, long.MaxValue); _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { Assert.Equal(6, nic.GetPhysicalAddress().GetAddressBytes().Length); } } } [Fact] [PlatformSpecific(TestPlatforms.Linux|TestPlatforms.Android)] // Some APIs are not supported on Linux and Android public void BasicTest_AccessInstanceProperties_NoExceptions_Linux() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); string description = nic.Description; Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty."); _log.WriteLine("Description: " + description); string id = nic.Id; Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty."); _log.WriteLine("ID: " + id); Assert.False(nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); try { _log.WriteLine("Speed: " + nic.Speed); Assert.InRange(nic.Speed, -1, long.MaxValue); } // We cannot guarantee this works on all devices. catch (PlatformNotSupportedException pnse) { _log.WriteLine(pnse.ToString()); } _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { Assert.Equal(6, nic.GetPhysicalAddress().GetAddressBytes().Length); } } } [Fact] [PlatformSpecific(TestPlatforms.OSX|TestPlatforms.FreeBSD)] public void BasicTest_AccessInstanceProperties_NoExceptions_Bsd() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); string description = nic.Description; Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty."); _log.WriteLine("Description: " + description); string id = nic.Id; Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty."); _log.WriteLine("ID: " + id); Assert.False(nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); _log.WriteLine("Speed: " + nic.Speed); Assert.InRange(nic.Speed, 0, long.MaxValue); _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); if (nic.Name.StartsWith("en") || nic.Name == "lo0") { // Ethernet, WIFI and loopback should have known status. Assert.True((nic.OperationalStatus == OperationalStatus.Up) || (nic.OperationalStatus == OperationalStatus.Down)); } if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { Assert.Equal(6, nic.GetPhysicalAddress().GetAddressBytes().Length); } } } [Fact] [Trait("IPv4", "true")] public void BasicTest_StaticLoopbackIndex_MatchesLoopbackNetworkInterface() { Assert.True(Capability.IPv4Support()); _log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses) { if (unicast.Address.Equals(IPAddress.Loopback)) { Assert.Equal<int>(nic.GetIPProperties().GetIPv4Properties().Index, NetworkInterface.LoopbackInterfaceIndex); Assert.True(nic.NetworkInterfaceType == NetworkInterfaceType.Loopback); return; // Only check IPv4 loopback } } } } [Fact] [Trait("IPv4", "true")] public void BasicTest_StaticLoopbackIndex_ExceptionIfV4NotSupported() { Assert.True(Capability.IPv4Support()); _log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex); } [Fact] [Trait("IPv6", "true")] public void BasicTest_StaticIPv6LoopbackIndex_MatchesLoopbackNetworkInterface() { Assert.True(Capability.IPv6Support()); _log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses) { if (unicast.Address.Equals(IPAddress.IPv6Loopback)) { Assert.Equal<int>( nic.GetIPProperties().GetIPv6Properties().Index, NetworkInterface.IPv6LoopbackInterfaceIndex); return; // Only check IPv6 loopback. } } } } [Fact] [Trait("IPv6", "true")] public void BasicTest_StaticIPv6LoopbackIndex_ExceptionIfV6NotSupported() { Assert.True(Capability.IPv6Support()); _log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX public void BasicTest_GetIPInterfaceStatistics_Success() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); _log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); _log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent); _log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [Fact] [PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux public void BasicTest_GetIPInterfaceStatistics_Success_Linux() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); Assert.Throws<PlatformNotSupportedException>(() => stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); Assert.Throws<PlatformNotSupportedException>(() => stats.NonUnicastPacketsSent); _log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [Fact] [PlatformSpecific(TestPlatforms.OSX|TestPlatforms.FreeBSD)] public void BasicTest_GetIPInterfaceStatistics_Success_Bsd() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); _log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); _log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent); Assert.Throws<PlatformNotSupportedException>(() => stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [Fact] public void BasicTest_GetIsNetworkAvailable_Success() { Assert.True(NetworkInterface.GetIsNetworkAvailable()); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/34690", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] [SkipOnPlatform(TestPlatforms.OSX | TestPlatforms.FreeBSD, "Expected behavior is different on OSX or FreeBSD")] [SkipOnPlatform(TestPlatforms.iOS | TestPlatforms.MacCatalyst | TestPlatforms.tvOS, "Not supported on Browser, iOS, MacCatalyst, or tvOS.")] [InlineData(false)] [InlineData(true)] public async Task NetworkInterface_LoopbackInterfaceIndex_MatchesReceivedPackets(bool ipv6) { using (var client = new Socket(SocketType.Dgram, ProtocolType.Udp)) using (var server = new Socket(SocketType.Dgram, ProtocolType.Udp)) { server.Bind(new IPEndPoint(ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0)); var serverEndPoint = (IPEndPoint)server.LocalEndPoint; Task<SocketReceiveMessageFromResult> receivedTask = server.ReceiveMessageFromAsync(new ArraySegment<byte>(new byte[1]), SocketFlags.None, serverEndPoint); while (!receivedTask.IsCompleted) { client.SendTo(new byte[] { 42 }, serverEndPoint); await Task.Delay(1); } Assert.Equal( (await receivedTask).PacketInformation.Interface, ipv6 ? NetworkInterface.IPv6LoopbackInterfaceIndex : NetworkInterface.LoopbackInterfaceIndex); } } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Data.Common/tests/System/Data/RowNotInTableExceptionTest.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 RowNotInTableExceptionTest { [Fact] public void Generate() { var ds = new DataSet(); ds.Tables.Add(DataProvider.CreateParentDataTable()); ds.Tables.Add(DataProvider.CreateChildDataTable()); ds.Relations.Add(new DataRelation("myRelation", ds.Tables[0].Columns[0], ds.Tables[1].Columns[0])); DataRow drParent = ds.Tables[0].Rows[0]; DataRow drChild = ds.Tables[1].Rows[0]; drParent.Delete(); drChild.Delete(); ds.AcceptChanges(); // RowNotInTableException - AcceptChanges Assert.Throws<RowNotInTableException>(() => { drParent.AcceptChanges(); }); // RowNotInTableException - GetChildRows Assert.Throws<RowNotInTableException>(() => { drParent.GetChildRows("myRelation"); }); // RowNotInTableException - ItemArray Assert.Throws<RowNotInTableException>(() => drParent.ItemArray); // RowNotInTableException - GetParentRows Assert.Throws<RowNotInTableException>(() => drChild.GetParentRows("myRelation")); // RowNotInTableException - RejectChanges Assert.Throws<RowNotInTableException>(() => drParent.RejectChanges()); // RowNotInTableException - SetParentRow Assert.Throws<RowNotInTableException>(() => drChild.SetParentRow(ds.Tables[0].Rows[1])); } } }
// 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 RowNotInTableExceptionTest { [Fact] public void Generate() { var ds = new DataSet(); ds.Tables.Add(DataProvider.CreateParentDataTable()); ds.Tables.Add(DataProvider.CreateChildDataTable()); ds.Relations.Add(new DataRelation("myRelation", ds.Tables[0].Columns[0], ds.Tables[1].Columns[0])); DataRow drParent = ds.Tables[0].Rows[0]; DataRow drChild = ds.Tables[1].Rows[0]; drParent.Delete(); drChild.Delete(); ds.AcceptChanges(); // RowNotInTableException - AcceptChanges Assert.Throws<RowNotInTableException>(() => { drParent.AcceptChanges(); }); // RowNotInTableException - GetChildRows Assert.Throws<RowNotInTableException>(() => { drParent.GetChildRows("myRelation"); }); // RowNotInTableException - ItemArray Assert.Throws<RowNotInTableException>(() => drParent.ItemArray); // RowNotInTableException - GetParentRows Assert.Throws<RowNotInTableException>(() => drChild.GetParentRows("myRelation")); // RowNotInTableException - RejectChanges Assert.Throws<RowNotInTableException>(() => drParent.RejectChanges()); // RowNotInTableException - SetParentRow Assert.Throws<RowNotInTableException>(() => drChild.SetParentRow(ds.Tables[0].Rows[1])); } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/coreclr/tools/Common/Compiler/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; using System.Collections.Generic; using System.Reflection.Metadata; using System.IO; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using ILCompiler.Logging; using ILLink.Shared; using ILSequencePoint = Internal.IL.ILSequencePoint; using MethodIL = Internal.IL.MethodIL; namespace ILCompiler { public class Logger { private readonly HashSet<int> _suppressedWarnings; private readonly bool _isSingleWarn; private readonly HashSet<string> _singleWarnEnabledAssemblies; private readonly HashSet<string> _singleWarnDisabledAssemblies; private readonly HashSet<string> _trimWarnedAssemblies = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private readonly HashSet<string> _aotWarnedAssemblies = new HashSet<string>(StringComparer.OrdinalIgnoreCase); public static Logger Null = new Logger(TextWriter.Null, false); public TextWriter Writer { get; } public bool IsVerbose { get; } public Logger(TextWriter writer, bool isVerbose, IEnumerable<int> suppressedWarnings, bool singleWarn, IEnumerable<string> singleWarnEnabledModules, IEnumerable<string> singleWarnDisabledModules) { Writer = TextWriter.Synchronized(writer); IsVerbose = isVerbose; _suppressedWarnings = new HashSet<int>(suppressedWarnings); _isSingleWarn = singleWarn; _singleWarnEnabledAssemblies = new HashSet<string>(singleWarnEnabledModules, StringComparer.OrdinalIgnoreCase); _singleWarnDisabledAssemblies = new HashSet<string>(singleWarnDisabledModules, StringComparer.OrdinalIgnoreCase); } public Logger(TextWriter writer, bool isVerbose) : this(writer, isVerbose, Array.Empty<int>(), singleWarn: false, Array.Empty<string>(), Array.Empty<string>()) { } public void LogMessage(string message) { MessageContainer? messageContainer = MessageContainer.CreateInfoMessage(message); if(messageContainer.HasValue) Writer.WriteLine(messageContainer.Value.ToMSBuildString()); } public void LogWarning(string text, int code, MessageOrigin origin, string subcategory = MessageSubCategory.None) { MessageContainer? warning = MessageContainer.CreateWarningMessage(this, text, code, origin, subcategory); if (warning.HasValue) Writer.WriteLine(warning.Value.ToMSBuildString()); } public void LogWarning(MessageOrigin origin, DiagnosticId id, params string[] args) { MessageContainer? warning = MessageContainer.CreateWarningMessage(this, origin, id, args); if (warning.HasValue) Writer.WriteLine(warning.Value.ToMSBuildString()); } public void LogWarning(string text, int code, TypeSystemEntity origin, string subcategory = MessageSubCategory.None) => LogWarning(text, code, new MessageOrigin(origin), subcategory); public void LogWarning(TypeSystemEntity origin, DiagnosticId id, params string[] args) => LogWarning(new MessageOrigin(origin), id, args); public void LogWarning(string text, int code, MethodIL origin, int ilOffset, string subcategory = MessageSubCategory.None) { string document = null; int? lineNumber = null; IEnumerable<ILSequencePoint> sequencePoints = origin.GetDebugInfo()?.GetSequencePoints(); if (sequencePoints != null) { foreach (var sequencePoint in sequencePoints) { if (sequencePoint.Offset <= ilOffset) { document = sequencePoint.Document; lineNumber = sequencePoint.LineNumber; } } } MethodDesc warnedMethod = CompilerGeneratedState.GetUserDefinedMethodForCompilerGeneratedMember(origin.OwningMethod) ?? origin.OwningMethod; MessageOrigin messageOrigin = new MessageOrigin(warnedMethod, document, lineNumber, null); LogWarning(text, code, messageOrigin, subcategory); } public void LogWarning(MethodIL origin, int ilOffset, DiagnosticId id, params string[] args) { string document = null; int? lineNumber = null; IEnumerable<ILSequencePoint> sequencePoints = origin.GetDebugInfo()?.GetSequencePoints(); if (sequencePoints != null) { foreach (var sequencePoint in sequencePoints) { if (sequencePoint.Offset <= ilOffset) { document = sequencePoint.Document; lineNumber = sequencePoint.LineNumber; } } } MethodDesc warnedMethod = CompilerGeneratedState.GetUserDefinedMethodForCompilerGeneratedMember(origin.OwningMethod) ?? origin.OwningMethod; MessageOrigin messageOrigin = new MessageOrigin(warnedMethod, document, lineNumber, null); LogWarning(messageOrigin, id, args); } public void LogWarning(string text, int code, string origin, string subcategory = MessageSubCategory.None) { MessageOrigin _origin = new MessageOrigin(origin); LogWarning(text, code, _origin, subcategory); } public void LogWarning(string origin, DiagnosticId id, params string[] args) { MessageOrigin _origin = new MessageOrigin(origin); LogWarning(_origin, id, args); } public void LogError(string text, int code, string subcategory = MessageSubCategory.None, MessageOrigin? origin = null) { MessageContainer? error = MessageContainer.CreateErrorMessage(text, code, subcategory, origin); if (error.HasValue) Writer.WriteLine(error.Value.ToMSBuildString()); } public void LogError(MessageOrigin? origin, DiagnosticId id, params string[] args) { MessageContainer? error = MessageContainer.CreateErrorMessage(origin, id, args); if (error.HasValue) Writer.WriteLine(error.Value.ToMSBuildString()); } public void LogError(string text, int code, TypeSystemEntity origin, string subcategory = MessageSubCategory.None) => LogError(text, code, subcategory, new MessageOrigin(origin)); public void LogError(TypeSystemEntity origin, DiagnosticId id, params string[] args) => LogError(new MessageOrigin(origin), id, args); internal bool IsWarningSuppressed(int code, MessageOrigin origin) { // This is causing too much noise // https://github.com/dotnet/runtimelab/issues/1591 if (code == 2110 || code == 2111 || code == 2113 || code == 2115) return true; if (_suppressedWarnings.Contains(code)) return true; IEnumerable<CustomAttributeValue<TypeDesc>> suppressions = null; // TODO: Suppressions with different scopes if (origin.MemberDefinition is TypeDesc type) { var ecmaType = type.GetTypeDefinition() as EcmaType; suppressions = ecmaType?.GetDecodedCustomAttributes("System.Diagnostics.CodeAnalysis", "UnconditionalSuppressMessageAttribute"); } if (origin.MemberDefinition is MethodDesc method) { method = CompilerGeneratedState.GetUserDefinedMethodForCompilerGeneratedMember(method) ?? method; var ecmaMethod = method.GetTypicalMethodDefinition() as EcmaMethod; suppressions = ecmaMethod?.GetDecodedCustomAttributes("System.Diagnostics.CodeAnalysis", "UnconditionalSuppressMessageAttribute"); } if (suppressions != null) { foreach (CustomAttributeValue<TypeDesc> suppression in suppressions) { if (suppression.FixedArguments.Length != 2 || suppression.FixedArguments[1].Value is not string warningId || warningId.Length < 6 || !warningId.StartsWith("IL") || (warningId.Length > 6 && warningId[6] != ':') || !int.TryParse(warningId.Substring(2, 4), out int suppressedCode)) { continue; } if (code == suppressedCode) { return true; } } } return false; } internal bool IsWarningAsError(int code) { // TODO: warnaserror return false; } internal bool IsSingleWarn(ModuleDesc owningModule, string messageSubcategory) { string assemblyName = owningModule.Assembly.GetName().Name; bool result = false; if ((_isSingleWarn || _singleWarnEnabledAssemblies.Contains(assemblyName)) && !_singleWarnDisabledAssemblies.Contains(assemblyName)) { result = true; if (messageSubcategory == MessageSubCategory.TrimAnalysis) { lock (_trimWarnedAssemblies) { if (_trimWarnedAssemblies.Add(assemblyName)) { LogWarning(GetModuleFileName(owningModule), DiagnosticId.AssemblyProducedTrimWarnings, assemblyName); } } } else if (messageSubcategory == MessageSubCategory.AotAnalysis) { lock (_aotWarnedAssemblies) { if (_aotWarnedAssemblies.Add(assemblyName)) { LogWarning(GetModuleFileName(owningModule), DiagnosticId.AssemblyProducedAOTWarnings, assemblyName); } } } } return result; } private static string GetModuleFileName(ModuleDesc module) { string assemblyName = module.Assembly.GetName().Name; var context = (CompilerTypeSystemContext)module.Context; if (context.ReferenceFilePaths.TryGetValue(assemblyName, out string result) || context.InputFilePaths.TryGetValue(assemblyName, out result)) { return result; } return assemblyName; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Reflection.Metadata; using System.IO; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using ILCompiler.Logging; using ILLink.Shared; using ILSequencePoint = Internal.IL.ILSequencePoint; using MethodIL = Internal.IL.MethodIL; namespace ILCompiler { public class Logger { private readonly HashSet<int> _suppressedWarnings; private readonly bool _isSingleWarn; private readonly HashSet<string> _singleWarnEnabledAssemblies; private readonly HashSet<string> _singleWarnDisabledAssemblies; private readonly HashSet<string> _trimWarnedAssemblies = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private readonly HashSet<string> _aotWarnedAssemblies = new HashSet<string>(StringComparer.OrdinalIgnoreCase); public static Logger Null = new Logger(TextWriter.Null, false); public TextWriter Writer { get; } public bool IsVerbose { get; } public Logger(TextWriter writer, bool isVerbose, IEnumerable<int> suppressedWarnings, bool singleWarn, IEnumerable<string> singleWarnEnabledModules, IEnumerable<string> singleWarnDisabledModules) { Writer = TextWriter.Synchronized(writer); IsVerbose = isVerbose; _suppressedWarnings = new HashSet<int>(suppressedWarnings); _isSingleWarn = singleWarn; _singleWarnEnabledAssemblies = new HashSet<string>(singleWarnEnabledModules, StringComparer.OrdinalIgnoreCase); _singleWarnDisabledAssemblies = new HashSet<string>(singleWarnDisabledModules, StringComparer.OrdinalIgnoreCase); } public Logger(TextWriter writer, bool isVerbose) : this(writer, isVerbose, Array.Empty<int>(), singleWarn: false, Array.Empty<string>(), Array.Empty<string>()) { } public void LogMessage(string message) { MessageContainer? messageContainer = MessageContainer.CreateInfoMessage(message); if(messageContainer.HasValue) Writer.WriteLine(messageContainer.Value.ToMSBuildString()); } public void LogWarning(string text, int code, MessageOrigin origin, string subcategory = MessageSubCategory.None) { MessageContainer? warning = MessageContainer.CreateWarningMessage(this, text, code, origin, subcategory); if (warning.HasValue) Writer.WriteLine(warning.Value.ToMSBuildString()); } public void LogWarning(MessageOrigin origin, DiagnosticId id, params string[] args) { MessageContainer? warning = MessageContainer.CreateWarningMessage(this, origin, id, args); if (warning.HasValue) Writer.WriteLine(warning.Value.ToMSBuildString()); } public void LogWarning(string text, int code, TypeSystemEntity origin, string subcategory = MessageSubCategory.None) => LogWarning(text, code, new MessageOrigin(origin), subcategory); public void LogWarning(TypeSystemEntity origin, DiagnosticId id, params string[] args) => LogWarning(new MessageOrigin(origin), id, args); public void LogWarning(string text, int code, MethodIL origin, int ilOffset, string subcategory = MessageSubCategory.None) { string document = null; int? lineNumber = null; IEnumerable<ILSequencePoint> sequencePoints = origin.GetDebugInfo()?.GetSequencePoints(); if (sequencePoints != null) { foreach (var sequencePoint in sequencePoints) { if (sequencePoint.Offset <= ilOffset) { document = sequencePoint.Document; lineNumber = sequencePoint.LineNumber; } } } MethodDesc warnedMethod = CompilerGeneratedState.GetUserDefinedMethodForCompilerGeneratedMember(origin.OwningMethod) ?? origin.OwningMethod; MessageOrigin messageOrigin = new MessageOrigin(warnedMethod, document, lineNumber, null); LogWarning(text, code, messageOrigin, subcategory); } public void LogWarning(MethodIL origin, int ilOffset, DiagnosticId id, params string[] args) { string document = null; int? lineNumber = null; IEnumerable<ILSequencePoint> sequencePoints = origin.GetDebugInfo()?.GetSequencePoints(); if (sequencePoints != null) { foreach (var sequencePoint in sequencePoints) { if (sequencePoint.Offset <= ilOffset) { document = sequencePoint.Document; lineNumber = sequencePoint.LineNumber; } } } MethodDesc warnedMethod = CompilerGeneratedState.GetUserDefinedMethodForCompilerGeneratedMember(origin.OwningMethod) ?? origin.OwningMethod; MessageOrigin messageOrigin = new MessageOrigin(warnedMethod, document, lineNumber, null); LogWarning(messageOrigin, id, args); } public void LogWarning(string text, int code, string origin, string subcategory = MessageSubCategory.None) { MessageOrigin _origin = new MessageOrigin(origin); LogWarning(text, code, _origin, subcategory); } public void LogWarning(string origin, DiagnosticId id, params string[] args) { MessageOrigin _origin = new MessageOrigin(origin); LogWarning(_origin, id, args); } public void LogError(string text, int code, string subcategory = MessageSubCategory.None, MessageOrigin? origin = null) { MessageContainer? error = MessageContainer.CreateErrorMessage(text, code, subcategory, origin); if (error.HasValue) Writer.WriteLine(error.Value.ToMSBuildString()); } public void LogError(MessageOrigin? origin, DiagnosticId id, params string[] args) { MessageContainer? error = MessageContainer.CreateErrorMessage(origin, id, args); if (error.HasValue) Writer.WriteLine(error.Value.ToMSBuildString()); } public void LogError(string text, int code, TypeSystemEntity origin, string subcategory = MessageSubCategory.None) => LogError(text, code, subcategory, new MessageOrigin(origin)); public void LogError(TypeSystemEntity origin, DiagnosticId id, params string[] args) => LogError(new MessageOrigin(origin), id, args); internal bool IsWarningSuppressed(int code, MessageOrigin origin) { // This is causing too much noise // https://github.com/dotnet/runtimelab/issues/1591 if (code == 2110 || code == 2111 || code == 2113 || code == 2115) return true; if (_suppressedWarnings.Contains(code)) return true; IEnumerable<CustomAttributeValue<TypeDesc>> suppressions = null; // TODO: Suppressions with different scopes if (origin.MemberDefinition is TypeDesc type) { var ecmaType = type.GetTypeDefinition() as EcmaType; suppressions = ecmaType?.GetDecodedCustomAttributes("System.Diagnostics.CodeAnalysis", "UnconditionalSuppressMessageAttribute"); } if (origin.MemberDefinition is MethodDesc method) { method = CompilerGeneratedState.GetUserDefinedMethodForCompilerGeneratedMember(method) ?? method; var ecmaMethod = method.GetTypicalMethodDefinition() as EcmaMethod; suppressions = ecmaMethod?.GetDecodedCustomAttributes("System.Diagnostics.CodeAnalysis", "UnconditionalSuppressMessageAttribute"); } if (suppressions != null) { foreach (CustomAttributeValue<TypeDesc> suppression in suppressions) { if (suppression.FixedArguments.Length != 2 || suppression.FixedArguments[1].Value is not string warningId || warningId.Length < 6 || !warningId.StartsWith("IL") || (warningId.Length > 6 && warningId[6] != ':') || !int.TryParse(warningId.Substring(2, 4), out int suppressedCode)) { continue; } if (code == suppressedCode) { return true; } } } return false; } internal bool IsWarningAsError(int code) { // TODO: warnaserror return false; } internal bool IsSingleWarn(ModuleDesc owningModule, string messageSubcategory) { string assemblyName = owningModule.Assembly.GetName().Name; bool result = false; if ((_isSingleWarn || _singleWarnEnabledAssemblies.Contains(assemblyName)) && !_singleWarnDisabledAssemblies.Contains(assemblyName)) { result = true; if (messageSubcategory == MessageSubCategory.TrimAnalysis) { lock (_trimWarnedAssemblies) { if (_trimWarnedAssemblies.Add(assemblyName)) { LogWarning(GetModuleFileName(owningModule), DiagnosticId.AssemblyProducedTrimWarnings, assemblyName); } } } else if (messageSubcategory == MessageSubCategory.AotAnalysis) { lock (_aotWarnedAssemblies) { if (_aotWarnedAssemblies.Add(assemblyName)) { LogWarning(GetModuleFileName(owningModule), DiagnosticId.AssemblyProducedAOTWarnings, assemblyName); } } } } return result; } private static string GetModuleFileName(ModuleDesc module) { string assemblyName = module.Assembly.GetName().Name; var context = (CompilerTypeSystemContext)module.Context; if (context.ReferenceFilePaths.TryGetValue(assemblyName, out string result) || context.InputFilePaths.TryGetValue(assemblyName, out result)) { return result; } return assemblyName; } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./eng/pipelines/coreclr/gc-standalone.yml
trigger: none schedules: - cron: "0 5 * * *" displayName: Mon through Sun at 9:00 PM (UTC-8:00) branches: include: - main always: true jobs: - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/build-coreclr-and-libraries-job.yml buildConfig: checked platforms: - Linux_arm64 - windows_arm64 - windows_x64 - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 jobParameters: testGroup: gc-standalone - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/build-test-job.yml buildConfig: checked platforms: - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 jobParameters: testGroup: gc-standalone - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml buildConfig: checked platforms: - Linux_arm64 - Linux_x64 - windows_arm64 - windows_x64 helixQueueGroup: ci helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml jobParameters: testGroup: gc-standalone displayNameArgs: GCStandAlone liveLibrariesBuildConfig: Release - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml buildConfig: checked platforms: - Linux_arm64 - Linux_x64 - windows_arm64 - windows_x64 helixQueueGroup: ci helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml jobParameters: testGroup: gc-standalone-server displayNameArgs: GCStandAloneServer liveLibrariesBuildConfig: Release
trigger: none schedules: - cron: "0 5 * * *" displayName: Mon through Sun at 9:00 PM (UTC-8:00) branches: include: - main always: true jobs: - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/build-coreclr-and-libraries-job.yml buildConfig: checked platforms: - Linux_arm64 - windows_arm64 - windows_x64 - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 jobParameters: testGroup: gc-standalone - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/build-test-job.yml buildConfig: checked platforms: - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 jobParameters: testGroup: gc-standalone - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml buildConfig: checked platforms: - Linux_arm64 - Linux_x64 - windows_arm64 - windows_x64 helixQueueGroup: ci helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml jobParameters: testGroup: gc-standalone displayNameArgs: GCStandAlone liveLibrariesBuildConfig: Release - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml buildConfig: checked platforms: - Linux_arm64 - Linux_x64 - windows_arm64 - windows_x64 helixQueueGroup: ci helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml jobParameters: testGroup: gc-standalone-server displayNameArgs: GCStandAloneServer liveLibrariesBuildConfig: Release
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/tests/JIT/Generics/Exceptions/specific_class_instance02.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; public struct ValX0 { } public struct ValY0 { } public struct ValX1<T> { } public struct ValY1<T> { } public struct ValX2<T, U> { } public struct ValY2<T, U> { } public struct ValX3<T, U, V> { } public struct ValY3<T, U, V> { } public class RefX0 { } public class RefY0 { } public class RefX1<T> { } public class RefY1<T> { } public class RefX2<T, U> { } public class RefY2<T, U> { } public class RefX3<T, U, V> { } public class RefY3<T, U, V> { } public class GenException<T> : Exception { } public class Gen<T> { public bool ExceptionTest(bool throwException) { if (throwException) { throw new GenException<T>(); } else { return true; } } } public class Test_specific_class_instance02 { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } counter++; } public static int Main() { int cLabel = 0; while (cLabel < 50) { try { switch (cLabel) { case 0: cLabel++; new Gen<int>().ExceptionTest(true); break; case 1: cLabel++; new Gen<double>().ExceptionTest(true); break; case 2: cLabel++; new Gen<string>().ExceptionTest(true); break; case 3: cLabel++; new Gen<object>().ExceptionTest(true); break; case 4: cLabel++; new Gen<Guid>().ExceptionTest(true); break; case 5: cLabel++; new Gen<int[]>().ExceptionTest(true); break; case 6: cLabel++; new Gen<double[,]>().ExceptionTest(true); break; case 7: cLabel++; new Gen<string[][][]>().ExceptionTest(true); break; case 8: cLabel++; new Gen<object[, , ,]>().ExceptionTest(true); break; case 9: cLabel++; new Gen<Guid[][, , ,][]>().ExceptionTest(true); break; case 10: cLabel++; new Gen<RefX1<int>[]>().ExceptionTest(true); break; case 11: cLabel++; new Gen<RefX1<double>[,]>().ExceptionTest(true); break; case 12: cLabel++; new Gen<RefX1<string>[][][]>().ExceptionTest(true); break; case 13: cLabel++; new Gen<RefX1<object>[, , ,]>().ExceptionTest(true); break; case 14: cLabel++; new Gen<RefX1<Guid>[][, , ,][]>().ExceptionTest(true); break; case 15: cLabel++; new Gen<RefX2<int, int>[]>().ExceptionTest(true); break; case 16: cLabel++; new Gen<RefX2<double, double>[,]>().ExceptionTest(true); break; case 17: cLabel++; new Gen<RefX2<string, string>[][][]>().ExceptionTest(true); break; case 18: cLabel++; new Gen<RefX2<object, object>[, , ,]>().ExceptionTest(true); break; case 19: cLabel++; new Gen<RefX2<Guid, Guid>[][, , ,][]>().ExceptionTest(true); break; case 20: cLabel++; new Gen<ValX1<int>[]>().ExceptionTest(true); break; case 21: cLabel++; new Gen<ValX1<double>[,]>().ExceptionTest(true); break; case 22: cLabel++; new Gen<ValX1<string>[][][]>().ExceptionTest(true); break; case 23: cLabel++; new Gen<ValX1<object>[, , ,]>().ExceptionTest(true); break; case 24: cLabel++; new Gen<ValX1<Guid>[][, , ,][]>().ExceptionTest(true); break; case 25: cLabel++; new Gen<ValX2<int, int>[]>().ExceptionTest(true); break; case 26: cLabel++; new Gen<ValX2<double, double>[,]>().ExceptionTest(true); break; case 27: cLabel++; new Gen<ValX2<string, string>[][][]>().ExceptionTest(true); break; case 28: cLabel++; new Gen<ValX2<object, object>[, , ,]>().ExceptionTest(true); break; case 29: cLabel++; new Gen<ValX2<Guid, Guid>[][, , ,][]>().ExceptionTest(true); break; case 30: cLabel++; new Gen<RefX1<int>>().ExceptionTest(true); break; case 31: cLabel++; new Gen<RefX1<ValX1<int>>>().ExceptionTest(true); break; case 32: cLabel++; new Gen<RefX2<int, string>>().ExceptionTest(true); break; case 33: cLabel++; new Gen<RefX3<int, string, Guid>>().ExceptionTest(true); break; case 34: cLabel++; new Gen<RefX1<RefX1<int>>>().ExceptionTest(true); break; case 35: cLabel++; new Gen<RefX1<RefX1<RefX1<string>>>>().ExceptionTest(true); break; case 36: cLabel++; new Gen<RefX1<RefX1<RefX1<RefX1<Guid>>>>>().ExceptionTest(true); break; case 37: cLabel++; new Gen<RefX1<RefX2<int, string>>>().ExceptionTest(true); break; case 38: cLabel++; new Gen<RefX2<RefX2<RefX1<int>, RefX3<int, string, RefX1<RefX2<int, string>>>>, RefX2<RefX1<int>, RefX3<int, string, RefX1<RefX2<int, string>>>>>>().ExceptionTest(true); break; case 39: cLabel++; new Gen<RefX3<RefX1<int[][, , ,]>, RefX2<object[, , ,][][], Guid[][][]>, RefX3<double[, , , , , , , , , ,], Guid[][][][, , , ,][, , , ,][][][], string[][][][][][][][][][][]>>>().ExceptionTest(true); break; case 40: cLabel++; new Gen<ValX1<int>>().ExceptionTest(true); break; case 41: cLabel++; new Gen<ValX1<RefX1<int>>>().ExceptionTest(true); break; case 42: cLabel++; new Gen<ValX2<int, string>>().ExceptionTest(true); break; case 43: cLabel++; new Gen<ValX3<int, string, Guid>>().ExceptionTest(true); break; case 44: cLabel++; new Gen<ValX1<ValX1<int>>>().ExceptionTest(true); break; case 45: cLabel++; new Gen<ValX1<ValX1<ValX1<string>>>>().ExceptionTest(true); break; case 46: cLabel++; new Gen<ValX1<ValX1<ValX1<ValX1<Guid>>>>>().ExceptionTest(true); break; case 47: cLabel++; new Gen<ValX1<ValX2<int, string>>>().ExceptionTest(true); break; case 48: cLabel++; new Gen<ValX2<ValX2<ValX1<int>, ValX3<int, string, ValX1<ValX2<int, string>>>>, ValX2<ValX1<int>, ValX3<int, string, ValX1<ValX2<int, string>>>>>>().ExceptionTest(true); break; case 49: cLabel++; new Gen<ValX3<ValX1<int[][, , ,]>, ValX2<object[, , ,][][], Guid[][][]>, ValX3<double[, , , , , , , , , ,], Guid[][][][, , , ,][, , , ,][][][], string[][][][][][][][][][][]>>>().ExceptionTest(true); break; } } catch (GenException<int>) { Eval(cLabel == 1); } catch (GenException<double>) { Eval(cLabel == 2); } catch (GenException<string>) { Eval(cLabel == 3); } catch (GenException<object>) { Eval(cLabel == 4); } catch (GenException<Guid>) { Eval(cLabel == 5); } catch (GenException<int[]>) { Eval(cLabel == 6); } catch (GenException<double[,]>) { Eval(cLabel == 7); } catch (GenException<string[][][]>) { Eval(cLabel == 8); } catch (GenException<object[, , ,]>) { Eval(cLabel == 9); } catch (GenException<Guid[][, , ,][]>) { Eval(cLabel == 10); } catch (GenException<RefX1<int>[]>) { Eval(cLabel == 11); } catch (GenException<RefX1<double>[,]>) { Eval(cLabel == 12); } catch (GenException<RefX1<string>[][][]>) { Eval(cLabel == 13); } catch (GenException<RefX1<object>[, , ,]>) { Eval(cLabel == 14); } catch (GenException<RefX1<Guid>[][, , ,][]>) { Eval(cLabel == 15); } catch (GenException<RefX2<int, int>[]>) { Eval(cLabel == 16); } catch (GenException<RefX2<double, double>[,]>) { Eval(cLabel == 17); } catch (GenException<RefX2<string, string>[][][]>) { Eval(cLabel == 18); } catch (GenException<RefX2<object, object>[, , ,]>) { Eval(cLabel == 19); } catch (GenException<RefX2<Guid, Guid>[][, , ,][]>) { Eval(cLabel == 20); } catch (GenException<ValX1<int>[]>) { Eval(cLabel == 21); } catch (GenException<ValX1<double>[,]>) { Eval(cLabel == 22); } catch (GenException<ValX1<string>[][][]>) { Eval(cLabel == 23); } catch (GenException<ValX1<object>[, , ,]>) { Eval(cLabel == 24); } catch (GenException<ValX1<Guid>[][, , ,][]>) { Eval(cLabel == 25); } catch (GenException<ValX2<int, int>[]>) { Eval(cLabel == 26); } catch (GenException<ValX2<double, double>[,]>) { Eval(cLabel == 27); } catch (GenException<ValX2<string, string>[][][]>) { Eval(cLabel == 28); } catch (GenException<ValX2<object, object>[, , ,]>) { Eval(cLabel == 29); } catch (GenException<ValX2<Guid, Guid>[][, , ,][]>) { Eval(cLabel == 30); } catch (GenException<RefX1<int>>) { Eval(cLabel == 31); } catch (GenException<RefX1<ValX1<int>>>) { Eval(cLabel == 32); } catch (GenException<RefX2<int, string>>) { Eval(cLabel == 33); } catch (GenException<RefX3<int, string, Guid>>) { Eval(cLabel == 34); } catch (GenException<RefX1<RefX1<int>>>) { Eval(cLabel == 35); } catch (GenException<RefX1<RefX1<RefX1<string>>>>) { Eval(cLabel == 36); } catch (GenException<RefX1<RefX1<RefX1<RefX1<Guid>>>>>) { Eval(cLabel == 37); } catch (GenException<RefX1<RefX2<int, string>>>) { Eval(cLabel == 38); } catch (GenException<RefX2<RefX2<RefX1<int>, RefX3<int, string, RefX1<RefX2<int, string>>>>, RefX2<RefX1<int>, RefX3<int, string, RefX1<RefX2<int, string>>>>>>) { Eval(cLabel == 39); } catch (GenException<RefX3<RefX1<int[][, , ,]>, RefX2<object[, , ,][][], Guid[][][]>, RefX3<double[, , , , , , , , , ,], Guid[][][][, , , ,][, , , ,][][][], string[][][][][][][][][][][]>>>) { Eval(cLabel == 40); } catch (GenException<ValX1<int>>) { Eval(cLabel == 41); } catch (GenException<ValX1<RefX1<int>>>) { Eval(cLabel == 42); } catch (GenException<ValX2<int, string>>) { Eval(cLabel == 43); } catch (GenException<ValX3<int, string, Guid>>) { Eval(cLabel == 44); } catch (GenException<ValX1<ValX1<int>>>) { Eval(cLabel == 45); } catch (GenException<ValX1<ValX1<ValX1<string>>>>) { Eval(cLabel == 46); } catch (GenException<ValX1<ValX1<ValX1<ValX1<Guid>>>>>) { Eval(cLabel == 47); } catch (GenException<ValX1<ValX2<int, string>>>) { Eval(cLabel == 48); } catch (GenException<ValX2<ValX2<ValX1<int>, ValX3<int, string, ValX1<ValX2<int, string>>>>, ValX2<ValX1<int>, ValX3<int, string, ValX1<ValX2<int, string>>>>>>) { Eval(cLabel == 49); } catch (GenException<ValX3<ValX1<int[][, , ,]>, ValX2<object[, , ,][][], Guid[][][]>, ValX3<double[, , , , , , , , , ,], Guid[][][][, , , ,][, , , ,][][][], string[][][][][][][][][][][]>>>) { Eval(cLabel == 50); } } if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; public struct ValX0 { } public struct ValY0 { } public struct ValX1<T> { } public struct ValY1<T> { } public struct ValX2<T, U> { } public struct ValY2<T, U> { } public struct ValX3<T, U, V> { } public struct ValY3<T, U, V> { } public class RefX0 { } public class RefY0 { } public class RefX1<T> { } public class RefY1<T> { } public class RefX2<T, U> { } public class RefY2<T, U> { } public class RefX3<T, U, V> { } public class RefY3<T, U, V> { } public class GenException<T> : Exception { } public class Gen<T> { public bool ExceptionTest(bool throwException) { if (throwException) { throw new GenException<T>(); } else { return true; } } } public class Test_specific_class_instance02 { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } counter++; } public static int Main() { int cLabel = 0; while (cLabel < 50) { try { switch (cLabel) { case 0: cLabel++; new Gen<int>().ExceptionTest(true); break; case 1: cLabel++; new Gen<double>().ExceptionTest(true); break; case 2: cLabel++; new Gen<string>().ExceptionTest(true); break; case 3: cLabel++; new Gen<object>().ExceptionTest(true); break; case 4: cLabel++; new Gen<Guid>().ExceptionTest(true); break; case 5: cLabel++; new Gen<int[]>().ExceptionTest(true); break; case 6: cLabel++; new Gen<double[,]>().ExceptionTest(true); break; case 7: cLabel++; new Gen<string[][][]>().ExceptionTest(true); break; case 8: cLabel++; new Gen<object[, , ,]>().ExceptionTest(true); break; case 9: cLabel++; new Gen<Guid[][, , ,][]>().ExceptionTest(true); break; case 10: cLabel++; new Gen<RefX1<int>[]>().ExceptionTest(true); break; case 11: cLabel++; new Gen<RefX1<double>[,]>().ExceptionTest(true); break; case 12: cLabel++; new Gen<RefX1<string>[][][]>().ExceptionTest(true); break; case 13: cLabel++; new Gen<RefX1<object>[, , ,]>().ExceptionTest(true); break; case 14: cLabel++; new Gen<RefX1<Guid>[][, , ,][]>().ExceptionTest(true); break; case 15: cLabel++; new Gen<RefX2<int, int>[]>().ExceptionTest(true); break; case 16: cLabel++; new Gen<RefX2<double, double>[,]>().ExceptionTest(true); break; case 17: cLabel++; new Gen<RefX2<string, string>[][][]>().ExceptionTest(true); break; case 18: cLabel++; new Gen<RefX2<object, object>[, , ,]>().ExceptionTest(true); break; case 19: cLabel++; new Gen<RefX2<Guid, Guid>[][, , ,][]>().ExceptionTest(true); break; case 20: cLabel++; new Gen<ValX1<int>[]>().ExceptionTest(true); break; case 21: cLabel++; new Gen<ValX1<double>[,]>().ExceptionTest(true); break; case 22: cLabel++; new Gen<ValX1<string>[][][]>().ExceptionTest(true); break; case 23: cLabel++; new Gen<ValX1<object>[, , ,]>().ExceptionTest(true); break; case 24: cLabel++; new Gen<ValX1<Guid>[][, , ,][]>().ExceptionTest(true); break; case 25: cLabel++; new Gen<ValX2<int, int>[]>().ExceptionTest(true); break; case 26: cLabel++; new Gen<ValX2<double, double>[,]>().ExceptionTest(true); break; case 27: cLabel++; new Gen<ValX2<string, string>[][][]>().ExceptionTest(true); break; case 28: cLabel++; new Gen<ValX2<object, object>[, , ,]>().ExceptionTest(true); break; case 29: cLabel++; new Gen<ValX2<Guid, Guid>[][, , ,][]>().ExceptionTest(true); break; case 30: cLabel++; new Gen<RefX1<int>>().ExceptionTest(true); break; case 31: cLabel++; new Gen<RefX1<ValX1<int>>>().ExceptionTest(true); break; case 32: cLabel++; new Gen<RefX2<int, string>>().ExceptionTest(true); break; case 33: cLabel++; new Gen<RefX3<int, string, Guid>>().ExceptionTest(true); break; case 34: cLabel++; new Gen<RefX1<RefX1<int>>>().ExceptionTest(true); break; case 35: cLabel++; new Gen<RefX1<RefX1<RefX1<string>>>>().ExceptionTest(true); break; case 36: cLabel++; new Gen<RefX1<RefX1<RefX1<RefX1<Guid>>>>>().ExceptionTest(true); break; case 37: cLabel++; new Gen<RefX1<RefX2<int, string>>>().ExceptionTest(true); break; case 38: cLabel++; new Gen<RefX2<RefX2<RefX1<int>, RefX3<int, string, RefX1<RefX2<int, string>>>>, RefX2<RefX1<int>, RefX3<int, string, RefX1<RefX2<int, string>>>>>>().ExceptionTest(true); break; case 39: cLabel++; new Gen<RefX3<RefX1<int[][, , ,]>, RefX2<object[, , ,][][], Guid[][][]>, RefX3<double[, , , , , , , , , ,], Guid[][][][, , , ,][, , , ,][][][], string[][][][][][][][][][][]>>>().ExceptionTest(true); break; case 40: cLabel++; new Gen<ValX1<int>>().ExceptionTest(true); break; case 41: cLabel++; new Gen<ValX1<RefX1<int>>>().ExceptionTest(true); break; case 42: cLabel++; new Gen<ValX2<int, string>>().ExceptionTest(true); break; case 43: cLabel++; new Gen<ValX3<int, string, Guid>>().ExceptionTest(true); break; case 44: cLabel++; new Gen<ValX1<ValX1<int>>>().ExceptionTest(true); break; case 45: cLabel++; new Gen<ValX1<ValX1<ValX1<string>>>>().ExceptionTest(true); break; case 46: cLabel++; new Gen<ValX1<ValX1<ValX1<ValX1<Guid>>>>>().ExceptionTest(true); break; case 47: cLabel++; new Gen<ValX1<ValX2<int, string>>>().ExceptionTest(true); break; case 48: cLabel++; new Gen<ValX2<ValX2<ValX1<int>, ValX3<int, string, ValX1<ValX2<int, string>>>>, ValX2<ValX1<int>, ValX3<int, string, ValX1<ValX2<int, string>>>>>>().ExceptionTest(true); break; case 49: cLabel++; new Gen<ValX3<ValX1<int[][, , ,]>, ValX2<object[, , ,][][], Guid[][][]>, ValX3<double[, , , , , , , , , ,], Guid[][][][, , , ,][, , , ,][][][], string[][][][][][][][][][][]>>>().ExceptionTest(true); break; } } catch (GenException<int>) { Eval(cLabel == 1); } catch (GenException<double>) { Eval(cLabel == 2); } catch (GenException<string>) { Eval(cLabel == 3); } catch (GenException<object>) { Eval(cLabel == 4); } catch (GenException<Guid>) { Eval(cLabel == 5); } catch (GenException<int[]>) { Eval(cLabel == 6); } catch (GenException<double[,]>) { Eval(cLabel == 7); } catch (GenException<string[][][]>) { Eval(cLabel == 8); } catch (GenException<object[, , ,]>) { Eval(cLabel == 9); } catch (GenException<Guid[][, , ,][]>) { Eval(cLabel == 10); } catch (GenException<RefX1<int>[]>) { Eval(cLabel == 11); } catch (GenException<RefX1<double>[,]>) { Eval(cLabel == 12); } catch (GenException<RefX1<string>[][][]>) { Eval(cLabel == 13); } catch (GenException<RefX1<object>[, , ,]>) { Eval(cLabel == 14); } catch (GenException<RefX1<Guid>[][, , ,][]>) { Eval(cLabel == 15); } catch (GenException<RefX2<int, int>[]>) { Eval(cLabel == 16); } catch (GenException<RefX2<double, double>[,]>) { Eval(cLabel == 17); } catch (GenException<RefX2<string, string>[][][]>) { Eval(cLabel == 18); } catch (GenException<RefX2<object, object>[, , ,]>) { Eval(cLabel == 19); } catch (GenException<RefX2<Guid, Guid>[][, , ,][]>) { Eval(cLabel == 20); } catch (GenException<ValX1<int>[]>) { Eval(cLabel == 21); } catch (GenException<ValX1<double>[,]>) { Eval(cLabel == 22); } catch (GenException<ValX1<string>[][][]>) { Eval(cLabel == 23); } catch (GenException<ValX1<object>[, , ,]>) { Eval(cLabel == 24); } catch (GenException<ValX1<Guid>[][, , ,][]>) { Eval(cLabel == 25); } catch (GenException<ValX2<int, int>[]>) { Eval(cLabel == 26); } catch (GenException<ValX2<double, double>[,]>) { Eval(cLabel == 27); } catch (GenException<ValX2<string, string>[][][]>) { Eval(cLabel == 28); } catch (GenException<ValX2<object, object>[, , ,]>) { Eval(cLabel == 29); } catch (GenException<ValX2<Guid, Guid>[][, , ,][]>) { Eval(cLabel == 30); } catch (GenException<RefX1<int>>) { Eval(cLabel == 31); } catch (GenException<RefX1<ValX1<int>>>) { Eval(cLabel == 32); } catch (GenException<RefX2<int, string>>) { Eval(cLabel == 33); } catch (GenException<RefX3<int, string, Guid>>) { Eval(cLabel == 34); } catch (GenException<RefX1<RefX1<int>>>) { Eval(cLabel == 35); } catch (GenException<RefX1<RefX1<RefX1<string>>>>) { Eval(cLabel == 36); } catch (GenException<RefX1<RefX1<RefX1<RefX1<Guid>>>>>) { Eval(cLabel == 37); } catch (GenException<RefX1<RefX2<int, string>>>) { Eval(cLabel == 38); } catch (GenException<RefX2<RefX2<RefX1<int>, RefX3<int, string, RefX1<RefX2<int, string>>>>, RefX2<RefX1<int>, RefX3<int, string, RefX1<RefX2<int, string>>>>>>) { Eval(cLabel == 39); } catch (GenException<RefX3<RefX1<int[][, , ,]>, RefX2<object[, , ,][][], Guid[][][]>, RefX3<double[, , , , , , , , , ,], Guid[][][][, , , ,][, , , ,][][][], string[][][][][][][][][][][]>>>) { Eval(cLabel == 40); } catch (GenException<ValX1<int>>) { Eval(cLabel == 41); } catch (GenException<ValX1<RefX1<int>>>) { Eval(cLabel == 42); } catch (GenException<ValX2<int, string>>) { Eval(cLabel == 43); } catch (GenException<ValX3<int, string, Guid>>) { Eval(cLabel == 44); } catch (GenException<ValX1<ValX1<int>>>) { Eval(cLabel == 45); } catch (GenException<ValX1<ValX1<ValX1<string>>>>) { Eval(cLabel == 46); } catch (GenException<ValX1<ValX1<ValX1<ValX1<Guid>>>>>) { Eval(cLabel == 47); } catch (GenException<ValX1<ValX2<int, string>>>) { Eval(cLabel == 48); } catch (GenException<ValX2<ValX2<ValX1<int>, ValX3<int, string, ValX1<ValX2<int, string>>>>, ValX2<ValX1<int>, ValX3<int, string, ValX1<ValX2<int, string>>>>>>) { Eval(cLabel == 49); } catch (GenException<ValX3<ValX1<int[][, , ,]>, ValX2<object[, , ,][][], Guid[][][]>, ValX3<double[, , , , , , , , , ,], Guid[][][][, , , ,][, , , ,][][][], string[][][][][][][][][][][]>>>) { Eval(cLabel == 50); } } if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/tests/Loader/classloader/regressions/vsw188290/vsw188290.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 System.Console { } .assembly extern xunit.core {} // Microsoft (R) .NET Framework IL Disassembler. Version 2.0.31013.0 // Copyright (C) Microsoft Corporation 1998-2003. All rights reserved. // Metadata version: v2.0.31013 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .hash = (0B D1 C7 0E 65 8B 67 F1 ED 21 D0 6D D4 DD 89 7A // ....e.g..!.m...z 37 E9 11 BE ) // 7... .ver 2:0:3600:0 } .assembly 'vsw188290' { // --- The following custom attribute is added automatically, do not uncomment ------- // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(bool, // bool) = ( 01 00 00 01 00 00 ) .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } // MVID: {31E86D7D-808F-4F1C-A755-94B3084C6466} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x03FA0000 // =============== CLASS MEMBERS DECLARATION =================== .class sealed private auto ansi beforefieldinit C<([mscorlib]System.Object) T> extends [mscorlib]System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 75 (0x4b) .maxstack 4 IL_0006: ldc.i4.1 IL_0007: stsfld bool Test_vsw188290::run IL_000c: ldtoken !0 IL_0011: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_0016: ldsfld class [mscorlib]System.Type Test_vsw188290::t IL_001b: beq.s IL_004a IL_001d: ldstr "C.typeof, typeof(T) = " IL_0022: ldtoken !0 IL_0027: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_002c: callvirt instance string [mscorlib]System.Object::ToString() IL_0031: ldstr ", Test.t = " IL_0036: ldsfld class [mscorlib]System.Type Test_vsw188290::t IL_003b: callvirt instance string [mscorlib]System.Object::ToString() IL_0040: call string [mscorlib]System.String::Concat(string, string, string, string) IL_0045: call void Test_vsw188290::fail(string) IL_004a: ret } // end of method C::.ctor } // end of valuetype C .class private auto ansi beforefieldinit Test_vsw188290 extends [mscorlib]System.Object { .field public static class [mscorlib]System.Type t .field public static bool run .field private static int32 failures .method public hidebysig static void fail(string msg) cil managed { // Code size 24 (0x18) .maxstack 8 IL_0000: ldstr "Failure: {0}" IL_0005: ldarg.0 IL_0006: call void [System.Console]System.Console::WriteLine(string, object) IL_000b: ldsfld int32 Test_vsw188290::failures IL_0010: ldc.i4.1 IL_0011: add IL_0012: stsfld int32 Test_vsw188290::failures IL_0017: ret } // end of method Test::fail .method private hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint // Code size 247 (0xf7) .maxstack 5 .locals init (valuetype C<int32>[] V_0, valuetype C<string>[] V_1, valuetype C<string[]>[] V_2, valuetype C<object>[] V_3, int32 V_4) IL_0000: ldc.i4.0 IL_0001: stsfld bool Test_vsw188290::run IL_0006: ldtoken [mscorlib]System.Int32 IL_000b: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_0010: stsfld class [mscorlib]System.Type Test_vsw188290::t IL_0015: ldc.i4.1 IL_0016: newarr valuetype C<int32> IL_001b: stloc.0 IL_001c: ldloc.0 IL_001d: callvirt instance void [mscorlib]System.Array::Initialize() IL_0022: ldsfld bool Test_vsw188290::run IL_0027: brtrue.s IL_0033 IL_0029: ldstr "contructor not run" IL_002e: call void Test_vsw188290::fail(string) IL_0033: ldstr "C<int> passed" call void [System.Console]System.Console::WriteLine(string) ldc.i4.0 IL_0034: stsfld bool Test_vsw188290::run IL_0039: ldtoken [mscorlib]System.String IL_003e: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_0043: stsfld class [mscorlib]System.Type Test_vsw188290::t IL_0048: ldc.i4.1 IL_0049: newarr valuetype C<string> IL_004e: stloc.1 IL_004f: ldloc.1 IL_0050: callvirt instance void [mscorlib]System.Array::Initialize() IL_0055: ldsfld bool Test_vsw188290::run IL_005a: brtrue.s IL_0066 IL_005c: ldstr "contructor not run" IL_0061: call void Test_vsw188290::fail(string) IL_0066: ldstr "C<string> passed" call void [System.Console]System.Console::WriteLine(string) ldc.i4.0 IL_0067: stsfld bool Test_vsw188290::run IL_006c: ldtoken string[] IL_0071: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_0076: stsfld class [mscorlib]System.Type Test_vsw188290::t IL_007b: ldc.i4.1 IL_007c: newarr valuetype C<string[]> IL_0081: stloc.2 IL_0082: ldloc.2 IL_0083: callvirt instance void [mscorlib]System.Array::Initialize() IL_0088: ldsfld bool Test_vsw188290::run IL_008d: brtrue.s IL_0099 IL_008f: ldstr "contructor not run" IL_0094: call void Test_vsw188290::fail(string) IL_0099: ldstr "C<string[]> passed" call void [System.Console]System.Console::WriteLine(string) ldc.i4.0 IL_009a: stsfld bool Test_vsw188290::run IL_009f: ldtoken [mscorlib]System.Object IL_00a4: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_00a9: stsfld class [mscorlib]System.Type Test_vsw188290::t IL_00ae: ldc.i4.1 IL_00af: newarr valuetype C<object> IL_00b4: stloc.3 IL_00b5: ldloc.3 IL_00b6: callvirt instance void [mscorlib]System.Array::Initialize() IL_00bb: ldsfld bool Test_vsw188290::run IL_00c0: brtrue.s IL_00cc IL_00c2: ldstr "contructor not run" IL_00c7: call void Test_vsw188290::fail(string) IL_00cc: ldstr "C<object> passed" call void [System.Console]System.Console::WriteLine(string) ldsfld int32 Test_vsw188290::failures IL_00d1: ldc.i4.0 IL_00d2: ble.s IL_00e4 IL_00d4: ldstr "Test Failed" IL_00d9: call void [System.Console]System.Console::WriteLine(string) IL_00de: ldc.i4.s 99 IL_00e0: stloc.s V_4 IL_00e2: br.s IL_00f4 IL_00e4: ldstr "Test Passed" IL_00e9: call void [System.Console]System.Console::WriteLine(string) IL_00ee: ldc.i4.s 100 IL_00f0: stloc.s V_4 IL_00f2: br.s IL_00f4 IL_00f4: ldloc.s V_4 IL_00f6: ret } // end of method Test::Main .method private hidebysig specialname rtspecialname static void .cctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldc.i4.0 IL_0001: stsfld int32 Test_vsw188290::failures IL_0006: ret } // end of method Test::.cctor .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Test::.ctor } // end of class Test // ============================================================= //*********** DISASSEMBLY COMPLETE *********************** // WARNING: Created Win32 resource file initialize-struct.res
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern System.Console { } .assembly extern xunit.core {} // Microsoft (R) .NET Framework IL Disassembler. Version 2.0.31013.0 // Copyright (C) Microsoft Corporation 1998-2003. All rights reserved. // Metadata version: v2.0.31013 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .hash = (0B D1 C7 0E 65 8B 67 F1 ED 21 D0 6D D4 DD 89 7A // ....e.g..!.m...z 37 E9 11 BE ) // 7... .ver 2:0:3600:0 } .assembly 'vsw188290' { // --- The following custom attribute is added automatically, do not uncomment ------- // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(bool, // bool) = ( 01 00 00 01 00 00 ) .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } // MVID: {31E86D7D-808F-4F1C-A755-94B3084C6466} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x03FA0000 // =============== CLASS MEMBERS DECLARATION =================== .class sealed private auto ansi beforefieldinit C<([mscorlib]System.Object) T> extends [mscorlib]System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 75 (0x4b) .maxstack 4 IL_0006: ldc.i4.1 IL_0007: stsfld bool Test_vsw188290::run IL_000c: ldtoken !0 IL_0011: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_0016: ldsfld class [mscorlib]System.Type Test_vsw188290::t IL_001b: beq.s IL_004a IL_001d: ldstr "C.typeof, typeof(T) = " IL_0022: ldtoken !0 IL_0027: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_002c: callvirt instance string [mscorlib]System.Object::ToString() IL_0031: ldstr ", Test.t = " IL_0036: ldsfld class [mscorlib]System.Type Test_vsw188290::t IL_003b: callvirt instance string [mscorlib]System.Object::ToString() IL_0040: call string [mscorlib]System.String::Concat(string, string, string, string) IL_0045: call void Test_vsw188290::fail(string) IL_004a: ret } // end of method C::.ctor } // end of valuetype C .class private auto ansi beforefieldinit Test_vsw188290 extends [mscorlib]System.Object { .field public static class [mscorlib]System.Type t .field public static bool run .field private static int32 failures .method public hidebysig static void fail(string msg) cil managed { // Code size 24 (0x18) .maxstack 8 IL_0000: ldstr "Failure: {0}" IL_0005: ldarg.0 IL_0006: call void [System.Console]System.Console::WriteLine(string, object) IL_000b: ldsfld int32 Test_vsw188290::failures IL_0010: ldc.i4.1 IL_0011: add IL_0012: stsfld int32 Test_vsw188290::failures IL_0017: ret } // end of method Test::fail .method private hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint // Code size 247 (0xf7) .maxstack 5 .locals init (valuetype C<int32>[] V_0, valuetype C<string>[] V_1, valuetype C<string[]>[] V_2, valuetype C<object>[] V_3, int32 V_4) IL_0000: ldc.i4.0 IL_0001: stsfld bool Test_vsw188290::run IL_0006: ldtoken [mscorlib]System.Int32 IL_000b: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_0010: stsfld class [mscorlib]System.Type Test_vsw188290::t IL_0015: ldc.i4.1 IL_0016: newarr valuetype C<int32> IL_001b: stloc.0 IL_001c: ldloc.0 IL_001d: callvirt instance void [mscorlib]System.Array::Initialize() IL_0022: ldsfld bool Test_vsw188290::run IL_0027: brtrue.s IL_0033 IL_0029: ldstr "contructor not run" IL_002e: call void Test_vsw188290::fail(string) IL_0033: ldstr "C<int> passed" call void [System.Console]System.Console::WriteLine(string) ldc.i4.0 IL_0034: stsfld bool Test_vsw188290::run IL_0039: ldtoken [mscorlib]System.String IL_003e: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_0043: stsfld class [mscorlib]System.Type Test_vsw188290::t IL_0048: ldc.i4.1 IL_0049: newarr valuetype C<string> IL_004e: stloc.1 IL_004f: ldloc.1 IL_0050: callvirt instance void [mscorlib]System.Array::Initialize() IL_0055: ldsfld bool Test_vsw188290::run IL_005a: brtrue.s IL_0066 IL_005c: ldstr "contructor not run" IL_0061: call void Test_vsw188290::fail(string) IL_0066: ldstr "C<string> passed" call void [System.Console]System.Console::WriteLine(string) ldc.i4.0 IL_0067: stsfld bool Test_vsw188290::run IL_006c: ldtoken string[] IL_0071: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_0076: stsfld class [mscorlib]System.Type Test_vsw188290::t IL_007b: ldc.i4.1 IL_007c: newarr valuetype C<string[]> IL_0081: stloc.2 IL_0082: ldloc.2 IL_0083: callvirt instance void [mscorlib]System.Array::Initialize() IL_0088: ldsfld bool Test_vsw188290::run IL_008d: brtrue.s IL_0099 IL_008f: ldstr "contructor not run" IL_0094: call void Test_vsw188290::fail(string) IL_0099: ldstr "C<string[]> passed" call void [System.Console]System.Console::WriteLine(string) ldc.i4.0 IL_009a: stsfld bool Test_vsw188290::run IL_009f: ldtoken [mscorlib]System.Object IL_00a4: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_00a9: stsfld class [mscorlib]System.Type Test_vsw188290::t IL_00ae: ldc.i4.1 IL_00af: newarr valuetype C<object> IL_00b4: stloc.3 IL_00b5: ldloc.3 IL_00b6: callvirt instance void [mscorlib]System.Array::Initialize() IL_00bb: ldsfld bool Test_vsw188290::run IL_00c0: brtrue.s IL_00cc IL_00c2: ldstr "contructor not run" IL_00c7: call void Test_vsw188290::fail(string) IL_00cc: ldstr "C<object> passed" call void [System.Console]System.Console::WriteLine(string) ldsfld int32 Test_vsw188290::failures IL_00d1: ldc.i4.0 IL_00d2: ble.s IL_00e4 IL_00d4: ldstr "Test Failed" IL_00d9: call void [System.Console]System.Console::WriteLine(string) IL_00de: ldc.i4.s 99 IL_00e0: stloc.s V_4 IL_00e2: br.s IL_00f4 IL_00e4: ldstr "Test Passed" IL_00e9: call void [System.Console]System.Console::WriteLine(string) IL_00ee: ldc.i4.s 100 IL_00f0: stloc.s V_4 IL_00f2: br.s IL_00f4 IL_00f4: ldloc.s V_4 IL_00f6: ret } // end of method Test::Main .method private hidebysig specialname rtspecialname static void .cctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldc.i4.0 IL_0001: stsfld int32 Test_vsw188290::failures IL_0006: ret } // end of method Test::.cctor .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Test::.ctor } // end of class Test // ============================================================= //*********** DISASSEMBLY COMPLETE *********************** // WARNING: Created Win32 resource file initialize-struct.res
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/coreclr/md/inc/mdlog.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //***************************************************************************** // MDLog.h - Meta data logging helper. // // //***************************************************************************** #ifndef __MDLog_h__ #define __MDLog_h__ #if defined(_DEBUG) && !defined(DACCESS_COMPILE) #define LOGGING #endif #include <log.h> #define LOGMD LF_METADATA, LL_INFO10000 #define LOG_MDCALL(func) LOG((LF_METADATA, LL_INFO10000, "MD: %s\n", #func)) #define MDSTR(str) ((str) ? str : W("<null>")) #define MDSTRA(str) ((str) ? str : "<null>") #endif // __MDLog_h__
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //***************************************************************************** // MDLog.h - Meta data logging helper. // // //***************************************************************************** #ifndef __MDLog_h__ #define __MDLog_h__ #if defined(_DEBUG) && !defined(DACCESS_COMPILE) #define LOGGING #endif #include <log.h> #define LOGMD LF_METADATA, LL_INFO10000 #define LOG_MDCALL(func) LOG((LF_METADATA, LL_INFO10000, "MD: %s\n", #func)) #define MDSTR(str) ((str) ? str : W("<null>")) #define MDSTRA(str) ((str) ? str : "<null>") #endif // __MDLog_h__
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Private.Xml/tests/XmlSchema/XmlSchemaSet/TC_SchemaSet_EnableUpaCheck.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; using Xunit.Abstractions; using System.IO; using System.Xml.Schema; namespace System.Xml.Tests { //[TestCase(Name = "TC_SchemaSet_EnableUpaCheck", Desc = "")] public class TC_SchemaSet_EnableUpaCheck : TC_SchemaSetBase { private ITestOutputHelper _output; public TC_SchemaSet_EnableUpaCheck(ITestOutputHelper output) { _output = output; } public bool bWarningCallback; public bool bErrorCallback; public int errorCount; public int[] errorLineNumbers; public string testData = null; private void Initialize() { this.testData = Path.Combine(TestData._Root, "EnableUpaCheck"); bWarningCallback = bErrorCallback = false; errorCount = 0; errorLineNumbers = new int[10]; } //Hook up validaton callback private void ValidationCallback(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Error) { _output.WriteLine("ERROR: "); bErrorCallback = true; XmlSchemaException se = args.Exception as XmlSchemaException; errorLineNumbers[errorCount] = se.LineNumber; errorCount++; _output.WriteLine("Exception Message:" + se.Message + "\n"); if (se.InnerException != null) { _output.WriteLine("InnerException Message:" + se.InnerException.Message + "\n"); } else _output.WriteLine("Inner Exception is NULL\n"); } } public XmlReader CreateReader(string xmlFile, XmlSchemaSet ss, bool UpaCheck) { XmlReaderSettings settings = new XmlReaderSettings(); settings.Schemas = new XmlSchemaSet(); settings.Schemas.CompilationSettings.EnableUpaCheck = UpaCheck; settings.Schemas.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); settings.Schemas.Add(ss); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ReportValidationWarnings; settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlReader vr = XmlReader.Create(xmlFile, settings); return vr; } /* a choice containing a wildcard and element declaraions */ //[Variation(Desc = "v6-2- a choice containing a wildcard and element declaraions(2)", Priority = 1, id = 25, Params = new object[] { "v6-2.xml", "v6-2.xsd", 0 })] [InlineData("v6-2.xml", "v6-2.xsd", 0, new int[] { })] //[Variation(Desc = "v6-1- a choice containing a wildcard and element declaraions(1)", Priority = 1, id = 24, Params = new object[] { "v6-1.xml", "v6-1.xsd", 0 })] [InlineData("v6-1.xml", "v6-1.xsd", 0, new int[] { })] /* Sequence having 3 sequences each having an optional wildcard and two elements of same name */ //[Variation(Desc = "v5-2- Sequence having 3 sequences each having an optional wildcard and two elements of same name(2)", Priority = 1, id = 23, Params = new object[] { "v5-2.xml", "v5-2.xsd", 1, 15 })] [InlineData("v5-2.xml", "v5-2.xsd", 1, new int[] { 15 })] //[Variation(Desc = "v5-1- Sequence having 3 sequences each having an optional wildcard and two elements of same name(1)", Priority = 1, id = 22, Params = new object[] { "v5-1.xml", "v5-1.xsd", 1, 23 })] [InlineData("v5-1.xml", "v5-1.xsd", 1, new int[] { 23 })] /* Optional wildcards before two element declarations*/ //[Variation(Desc = "v4.5- Optional wildcards before two element declarations(5)", Priority = 1, id = 21, Params = new object[] { "v4-5.xml", "v4-2.xsd", 1, 16 })] [InlineData("v4-5.xml", "v4-2.xsd", 1, new int[] { 16 })] //[Variation(Desc = "v4.4- Optional wildcards before two element declarations(4)", Priority = 1, id = 20, Params = new object[] { "v4-4.xml", "v4-2.xsd", 1, 11 })] [InlineData("v4-4.xml", "v4-2.xsd", 1, new int[] { 11 })] //[Variation(Desc = "v4.3- Optional wildcards before two element declarations(3)", Priority = 1, id = 19, Params = new object[] { "v4-3.xml", "v4-1.xsd", 1, 11 })] [InlineData("v4-3.xml", "v4-1.xsd", 1, new int[] { 11 })] //[Variation(Desc = "v4.2- Optional wildcards before two element declarations(2)", Priority = 1, id = 18, Params = new object[] { "v4-2.xml", "v4-1.xsd", 1, 11 })] [InlineData("v4-2.xml", "v4-1.xsd", 1, new int[] { 11 })] //[Variation(Desc = "v4.1- Optional wildcards before two element declarations(1)", Priority = 1, id = 17, Params = new object[] { "v4-1.xml", "v4-1.xsd", 0 })] [InlineData("v4-1.xml", "v4-1.xsd", 0, new int[] { })] /* Optional wildcards between two element declarations*/ //[Variation(Desc = "v3.6- Optional wildcards between two element declarations(6)", Priority = 1, id = 16, Params = new object[] { "v3-6.xml", "v3.xsd", 1, 76 })] [InlineData("v3-6.xml", "v3.xsd", 1, new int[] { 76 })] //[Variation(Desc = "v3.5- Optional wildcards between two element declarations(5)", Priority = 1, id = 15, Params = new object[] { "v3-5.xml", "v3.xsd", 2, 13, 62 })] [InlineData("v3-5.xml", "v3.xsd", 2, new int[] { 13, 62 })] //[Variation(Desc = "v3.4- Optional wildcards between two element declarations(4)", Priority = 1, id = 14, Params = new object[] { "v3-4.xml", "v3.xsd", 2, 13, 16 })] [InlineData("v3-4.xml", "v3.xsd", 2, new int[] { 13, 16 })] //[Variation(Desc = "v3.3- Optional wildcards between two element declarations(3)", Priority = 1, id = 13, Params = new object[] { "v3-3.xml", "v3.xsd", 1, 11 })] [InlineData("v3-3.xml", "v3.xsd", 1, new int[] { 11 })] //[Variation(Desc = "v3.2- Optional wildcards between two element declarations(2)", Priority = 1, id = 12, Params = new object[] { "v3-2.xml", "v3.xsd", 1, 15 })] [InlineData("v3-2.xml", "v3.xsd", 1, new int[] { 15 })] //[Variation(Desc = "v3.1- Optional wildcards between two element declarations(1)", Priority = 1, id = 11, Params = new object[] { "v3-1.xml", "v3.xsd", 1, 11 })] [InlineData("v3-1.xml", "v3.xsd", 1, new int[] { 11 })] /* Sequence of choices having same element name and same type */ //[Variation(Desc = "v2.7- Sequence of choices with same element name,one which doesnt match fixed value in schema(7)", Priority = 1, id = 10, Params = new object[] { "v2-7.xml", "v2-7.xsd", 0 })] [InlineData("v2-7.xml", "v2-7.xsd", 0, new int[] { })] //[Variation(Desc = "v2.6- Sequence of choices with same element name,one which doesnt match fixed value in schema(6)", Priority = 1, id = 9, Params = new object[] { "v2-6.xml", "v2-6.xsd", 3, 2, 5, 10 })] [InlineData("v2-6.xml", "v2-6.xsd", 3, new int[] { 2, 5, 10 })] //[Variation(Desc = "v2.5- Sequence of choices with same element name,one which doesnt match fixed value in schema(5)", Priority = 1, id = 8, Params = new object[] { "v2-5.xml", "v2-5.xsd", 2, 5, 10 })] [InlineData("v2-5.xml", "v2-5.xsd", 2, new int[] { 5, 10 })] //[Variation(Desc = "v2.4- Sequence of choices with same element name,one which doesnt match fixed value in schema(4)", Priority = 1, id = 7, Params = new object[] { "v2-4.xml", "v2-4.xsd", 2, 5, 7 })] [InlineData("v2-4.xml", "v2-4.xsd", 2, new int[] { 5, 7 })] //[Variation(Desc = "v2.3- Sequence of choices with same element name,one which doesnt match fixed value in schema(3)", Priority = 1, id = 6, Params = new object[] { "v2-3.xml", "v2-3.xsd", 1, 3 })] [InlineData("v2-3.xml", "v2-3.xsd", 1, new int[] { 3 })] //[Variation(Desc = "v2.2- Sequence of choices with same element name,one which doesnt match fixed value in schema(2)", Priority = 1, id = 5, Params = new object[] { "v2-2.xml", "v2-2.xsd", 1, 3 })] [InlineData("v2-2.xml", "v2-2.xsd", 1, new int[] { 3 })] //[Variation(Desc = "v2.1- Sequence of choices with same element name, one which doesnt match fixed value in schema(1)", Priority = 1, id = 4, Params = new object[] { "v2-1.xml", "v2-1.xsd", 3, 3, 4, 5 })] [InlineData("v2-1.xml", "v2-1.xsd", 3, new int[] { 3, 4, 5 })] /* Sequence with same element name and same type */ //[Variation(Desc = "v1.3- Sequence on element with same name and type, one has fixed value, instance has violation of fixed", Priority = 1, id = 3, Params = new object[] { "v1-3.xml", "v1-3.xsd", 1, 2 })] [InlineData("v1-3.xml", "v1-3.xsd", 1, new int[] { 2 })] //[Variation(Desc = "v1.2- Sequence on element with same name and type, one has default value", Priority = 1, id = 2, Params = new object[] { "v1-2.xml", "v1-2.xsd", 0 })] [InlineData("v1-2.xml", "v1-2.xsd", 0, new int[] { })] //[Variation(Desc = "v1.1- Sequence on element with same name and type", Priority = 1, id = 1, Params = new object[] { "v1-1.xml", "v1.xsd", 0 })] [InlineData("v1-1.xml", "v1.xsd", 0, new int[] { })] [Theory] public void v1(object param0, object param1, object param2, int[] expectedErrorLineNumbers) { string xmlFile = param0.ToString(); string xsdFile = param1.ToString(); int expectedErrorCount = (int)param2; Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); xss.Add(null, Path.Combine(testData, xsdFile)); XmlReader vr = CreateReader(Path.Combine(testData, xmlFile), xss, false); while (vr.Read()) ; CError.Compare(errorCount, expectedErrorCount, "Error Count mismatch"); if (errorCount > 0) //compare only if there is an error { for (int i = 0; i < errorCount; i++) { CError.Compare(errorLineNumbers[i], expectedErrorLineNumbers[i], "Error Line Number is different"); } } return; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; using Xunit.Abstractions; using System.IO; using System.Xml.Schema; namespace System.Xml.Tests { //[TestCase(Name = "TC_SchemaSet_EnableUpaCheck", Desc = "")] public class TC_SchemaSet_EnableUpaCheck : TC_SchemaSetBase { private ITestOutputHelper _output; public TC_SchemaSet_EnableUpaCheck(ITestOutputHelper output) { _output = output; } public bool bWarningCallback; public bool bErrorCallback; public int errorCount; public int[] errorLineNumbers; public string testData = null; private void Initialize() { this.testData = Path.Combine(TestData._Root, "EnableUpaCheck"); bWarningCallback = bErrorCallback = false; errorCount = 0; errorLineNumbers = new int[10]; } //Hook up validaton callback private void ValidationCallback(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Error) { _output.WriteLine("ERROR: "); bErrorCallback = true; XmlSchemaException se = args.Exception as XmlSchemaException; errorLineNumbers[errorCount] = se.LineNumber; errorCount++; _output.WriteLine("Exception Message:" + se.Message + "\n"); if (se.InnerException != null) { _output.WriteLine("InnerException Message:" + se.InnerException.Message + "\n"); } else _output.WriteLine("Inner Exception is NULL\n"); } } public XmlReader CreateReader(string xmlFile, XmlSchemaSet ss, bool UpaCheck) { XmlReaderSettings settings = new XmlReaderSettings(); settings.Schemas = new XmlSchemaSet(); settings.Schemas.CompilationSettings.EnableUpaCheck = UpaCheck; settings.Schemas.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); settings.Schemas.Add(ss); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ReportValidationWarnings; settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlReader vr = XmlReader.Create(xmlFile, settings); return vr; } /* a choice containing a wildcard and element declaraions */ //[Variation(Desc = "v6-2- a choice containing a wildcard and element declaraions(2)", Priority = 1, id = 25, Params = new object[] { "v6-2.xml", "v6-2.xsd", 0 })] [InlineData("v6-2.xml", "v6-2.xsd", 0, new int[] { })] //[Variation(Desc = "v6-1- a choice containing a wildcard and element declaraions(1)", Priority = 1, id = 24, Params = new object[] { "v6-1.xml", "v6-1.xsd", 0 })] [InlineData("v6-1.xml", "v6-1.xsd", 0, new int[] { })] /* Sequence having 3 sequences each having an optional wildcard and two elements of same name */ //[Variation(Desc = "v5-2- Sequence having 3 sequences each having an optional wildcard and two elements of same name(2)", Priority = 1, id = 23, Params = new object[] { "v5-2.xml", "v5-2.xsd", 1, 15 })] [InlineData("v5-2.xml", "v5-2.xsd", 1, new int[] { 15 })] //[Variation(Desc = "v5-1- Sequence having 3 sequences each having an optional wildcard and two elements of same name(1)", Priority = 1, id = 22, Params = new object[] { "v5-1.xml", "v5-1.xsd", 1, 23 })] [InlineData("v5-1.xml", "v5-1.xsd", 1, new int[] { 23 })] /* Optional wildcards before two element declarations*/ //[Variation(Desc = "v4.5- Optional wildcards before two element declarations(5)", Priority = 1, id = 21, Params = new object[] { "v4-5.xml", "v4-2.xsd", 1, 16 })] [InlineData("v4-5.xml", "v4-2.xsd", 1, new int[] { 16 })] //[Variation(Desc = "v4.4- Optional wildcards before two element declarations(4)", Priority = 1, id = 20, Params = new object[] { "v4-4.xml", "v4-2.xsd", 1, 11 })] [InlineData("v4-4.xml", "v4-2.xsd", 1, new int[] { 11 })] //[Variation(Desc = "v4.3- Optional wildcards before two element declarations(3)", Priority = 1, id = 19, Params = new object[] { "v4-3.xml", "v4-1.xsd", 1, 11 })] [InlineData("v4-3.xml", "v4-1.xsd", 1, new int[] { 11 })] //[Variation(Desc = "v4.2- Optional wildcards before two element declarations(2)", Priority = 1, id = 18, Params = new object[] { "v4-2.xml", "v4-1.xsd", 1, 11 })] [InlineData("v4-2.xml", "v4-1.xsd", 1, new int[] { 11 })] //[Variation(Desc = "v4.1- Optional wildcards before two element declarations(1)", Priority = 1, id = 17, Params = new object[] { "v4-1.xml", "v4-1.xsd", 0 })] [InlineData("v4-1.xml", "v4-1.xsd", 0, new int[] { })] /* Optional wildcards between two element declarations*/ //[Variation(Desc = "v3.6- Optional wildcards between two element declarations(6)", Priority = 1, id = 16, Params = new object[] { "v3-6.xml", "v3.xsd", 1, 76 })] [InlineData("v3-6.xml", "v3.xsd", 1, new int[] { 76 })] //[Variation(Desc = "v3.5- Optional wildcards between two element declarations(5)", Priority = 1, id = 15, Params = new object[] { "v3-5.xml", "v3.xsd", 2, 13, 62 })] [InlineData("v3-5.xml", "v3.xsd", 2, new int[] { 13, 62 })] //[Variation(Desc = "v3.4- Optional wildcards between two element declarations(4)", Priority = 1, id = 14, Params = new object[] { "v3-4.xml", "v3.xsd", 2, 13, 16 })] [InlineData("v3-4.xml", "v3.xsd", 2, new int[] { 13, 16 })] //[Variation(Desc = "v3.3- Optional wildcards between two element declarations(3)", Priority = 1, id = 13, Params = new object[] { "v3-3.xml", "v3.xsd", 1, 11 })] [InlineData("v3-3.xml", "v3.xsd", 1, new int[] { 11 })] //[Variation(Desc = "v3.2- Optional wildcards between two element declarations(2)", Priority = 1, id = 12, Params = new object[] { "v3-2.xml", "v3.xsd", 1, 15 })] [InlineData("v3-2.xml", "v3.xsd", 1, new int[] { 15 })] //[Variation(Desc = "v3.1- Optional wildcards between two element declarations(1)", Priority = 1, id = 11, Params = new object[] { "v3-1.xml", "v3.xsd", 1, 11 })] [InlineData("v3-1.xml", "v3.xsd", 1, new int[] { 11 })] /* Sequence of choices having same element name and same type */ //[Variation(Desc = "v2.7- Sequence of choices with same element name,one which doesnt match fixed value in schema(7)", Priority = 1, id = 10, Params = new object[] { "v2-7.xml", "v2-7.xsd", 0 })] [InlineData("v2-7.xml", "v2-7.xsd", 0, new int[] { })] //[Variation(Desc = "v2.6- Sequence of choices with same element name,one which doesnt match fixed value in schema(6)", Priority = 1, id = 9, Params = new object[] { "v2-6.xml", "v2-6.xsd", 3, 2, 5, 10 })] [InlineData("v2-6.xml", "v2-6.xsd", 3, new int[] { 2, 5, 10 })] //[Variation(Desc = "v2.5- Sequence of choices with same element name,one which doesnt match fixed value in schema(5)", Priority = 1, id = 8, Params = new object[] { "v2-5.xml", "v2-5.xsd", 2, 5, 10 })] [InlineData("v2-5.xml", "v2-5.xsd", 2, new int[] { 5, 10 })] //[Variation(Desc = "v2.4- Sequence of choices with same element name,one which doesnt match fixed value in schema(4)", Priority = 1, id = 7, Params = new object[] { "v2-4.xml", "v2-4.xsd", 2, 5, 7 })] [InlineData("v2-4.xml", "v2-4.xsd", 2, new int[] { 5, 7 })] //[Variation(Desc = "v2.3- Sequence of choices with same element name,one which doesnt match fixed value in schema(3)", Priority = 1, id = 6, Params = new object[] { "v2-3.xml", "v2-3.xsd", 1, 3 })] [InlineData("v2-3.xml", "v2-3.xsd", 1, new int[] { 3 })] //[Variation(Desc = "v2.2- Sequence of choices with same element name,one which doesnt match fixed value in schema(2)", Priority = 1, id = 5, Params = new object[] { "v2-2.xml", "v2-2.xsd", 1, 3 })] [InlineData("v2-2.xml", "v2-2.xsd", 1, new int[] { 3 })] //[Variation(Desc = "v2.1- Sequence of choices with same element name, one which doesnt match fixed value in schema(1)", Priority = 1, id = 4, Params = new object[] { "v2-1.xml", "v2-1.xsd", 3, 3, 4, 5 })] [InlineData("v2-1.xml", "v2-1.xsd", 3, new int[] { 3, 4, 5 })] /* Sequence with same element name and same type */ //[Variation(Desc = "v1.3- Sequence on element with same name and type, one has fixed value, instance has violation of fixed", Priority = 1, id = 3, Params = new object[] { "v1-3.xml", "v1-3.xsd", 1, 2 })] [InlineData("v1-3.xml", "v1-3.xsd", 1, new int[] { 2 })] //[Variation(Desc = "v1.2- Sequence on element with same name and type, one has default value", Priority = 1, id = 2, Params = new object[] { "v1-2.xml", "v1-2.xsd", 0 })] [InlineData("v1-2.xml", "v1-2.xsd", 0, new int[] { })] //[Variation(Desc = "v1.1- Sequence on element with same name and type", Priority = 1, id = 1, Params = new object[] { "v1-1.xml", "v1.xsd", 0 })] [InlineData("v1-1.xml", "v1.xsd", 0, new int[] { })] [Theory] public void v1(object param0, object param1, object param2, int[] expectedErrorLineNumbers) { string xmlFile = param0.ToString(); string xsdFile = param1.ToString(); int expectedErrorCount = (int)param2; Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); xss.Add(null, Path.Combine(testData, xsdFile)); XmlReader vr = CreateReader(Path.Combine(testData, xmlFile), xss, false); while (vr.Read()) ; CError.Compare(errorCount, expectedErrorCount, "Error Count mismatch"); if (errorCount > 0) //compare only if there is an error { for (int i = 0; i < errorCount; i++) { CError.Compare(errorLineNumbers[i], expectedErrorLineNumbers[i], "Error Line Number is different"); } } return; } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/coreclr/jit/hwintrinsic.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "jitpch.h" #include "hwintrinsic.h" #ifdef FEATURE_HW_INTRINSICS static const HWIntrinsicInfo hwIntrinsicInfoArray[] = { // clang-format off #if defined(TARGET_XARCH) #define HARDWARE_INTRINSIC(isa, name, size, numarg, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, category, flag) \ {NI_##isa##_##name, #name, InstructionSet_##isa, size, numarg, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, category, static_cast<HWIntrinsicFlag>(flag)}, #include "hwintrinsiclistxarch.h" #elif defined (TARGET_ARM64) #define HARDWARE_INTRINSIC(isa, name, size, numarg, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, category, flag) \ {NI_##isa##_##name, #name, InstructionSet_##isa, size, numarg, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, category, static_cast<HWIntrinsicFlag>(flag)}, #include "hwintrinsiclistarm64.h" #else #error Unsupported platform #endif // clang-format on }; //------------------------------------------------------------------------ // lookup: Gets the HWIntrinsicInfo associated with a given NamedIntrinsic // // Arguments: // id -- The NamedIntrinsic associated with the HWIntrinsic to lookup // // Return Value: // The HWIntrinsicInfo associated with id const HWIntrinsicInfo& HWIntrinsicInfo::lookup(NamedIntrinsic id) { assert(id != NI_Illegal); assert(id > NI_HW_INTRINSIC_START); assert(id < NI_HW_INTRINSIC_END); return hwIntrinsicInfoArray[id - NI_HW_INTRINSIC_START - 1]; } //------------------------------------------------------------------------ // getBaseJitTypeFromArgIfNeeded: Get simdBaseJitType of intrinsic from 1st or 2nd argument depending on the flag // // Arguments: // intrinsic -- id of the intrinsic function. // clsHnd -- class handle containing the intrinsic function. // method -- method handle of the intrinsic function. // sig -- signature of the intrinsic call. // simdBaseJitType -- Predetermined simdBaseJitType, could be CORINFO_TYPE_UNDEF // // Return Value: // The basetype of intrinsic of it can be fetched from 1st or 2nd argument, else return baseType unmodified. // CorInfoType Compiler::getBaseJitTypeFromArgIfNeeded(NamedIntrinsic intrinsic, CORINFO_CLASS_HANDLE clsHnd, CORINFO_SIG_INFO* sig, CorInfoType simdBaseJitType) { if (HWIntrinsicInfo::BaseTypeFromSecondArg(intrinsic) || HWIntrinsicInfo::BaseTypeFromFirstArg(intrinsic)) { CORINFO_ARG_LIST_HANDLE arg = sig->args; if (HWIntrinsicInfo::BaseTypeFromSecondArg(intrinsic)) { arg = info.compCompHnd->getArgNext(arg); } CORINFO_CLASS_HANDLE argClass = info.compCompHnd->getArgClass(sig, arg); simdBaseJitType = getBaseJitTypeAndSizeOfSIMDType(argClass); if (simdBaseJitType == CORINFO_TYPE_UNDEF) // the argument is not a vector { CORINFO_CLASS_HANDLE tmpClass; simdBaseJitType = strip(info.compCompHnd->getArgType(sig, arg, &tmpClass)); if (simdBaseJitType == CORINFO_TYPE_PTR) { simdBaseJitType = info.compCompHnd->getChildType(argClass, &tmpClass); } } assert(simdBaseJitType != CORINFO_TYPE_UNDEF); } return simdBaseJitType; } CORINFO_CLASS_HANDLE Compiler::gtGetStructHandleForHWSIMD(var_types simdType, CorInfoType simdBaseJitType) { if (m_simdHandleCache == nullptr) { return NO_CLASS_HANDLE; } if (simdType == TYP_SIMD16) { switch (simdBaseJitType) { case CORINFO_TYPE_FLOAT: return m_simdHandleCache->Vector128FloatHandle; case CORINFO_TYPE_DOUBLE: return m_simdHandleCache->Vector128DoubleHandle; case CORINFO_TYPE_INT: return m_simdHandleCache->Vector128IntHandle; case CORINFO_TYPE_USHORT: return m_simdHandleCache->Vector128UShortHandle; case CORINFO_TYPE_UBYTE: return m_simdHandleCache->Vector128UByteHandle; case CORINFO_TYPE_SHORT: return m_simdHandleCache->Vector128ShortHandle; case CORINFO_TYPE_BYTE: return m_simdHandleCache->Vector128ByteHandle; case CORINFO_TYPE_LONG: return m_simdHandleCache->Vector128LongHandle; case CORINFO_TYPE_UINT: return m_simdHandleCache->Vector128UIntHandle; case CORINFO_TYPE_ULONG: return m_simdHandleCache->Vector128ULongHandle; case CORINFO_TYPE_NATIVEINT: return m_simdHandleCache->Vector128NIntHandle; case CORINFO_TYPE_NATIVEUINT: return m_simdHandleCache->Vector128NUIntHandle; default: assert(!"Didn't find a class handle for simdType"); } } #ifdef TARGET_XARCH else if (simdType == TYP_SIMD32) { switch (simdBaseJitType) { case CORINFO_TYPE_FLOAT: return m_simdHandleCache->Vector256FloatHandle; case CORINFO_TYPE_DOUBLE: return m_simdHandleCache->Vector256DoubleHandle; case CORINFO_TYPE_INT: return m_simdHandleCache->Vector256IntHandle; case CORINFO_TYPE_USHORT: return m_simdHandleCache->Vector256UShortHandle; case CORINFO_TYPE_UBYTE: return m_simdHandleCache->Vector256UByteHandle; case CORINFO_TYPE_SHORT: return m_simdHandleCache->Vector256ShortHandle; case CORINFO_TYPE_BYTE: return m_simdHandleCache->Vector256ByteHandle; case CORINFO_TYPE_LONG: return m_simdHandleCache->Vector256LongHandle; case CORINFO_TYPE_UINT: return m_simdHandleCache->Vector256UIntHandle; case CORINFO_TYPE_ULONG: return m_simdHandleCache->Vector256ULongHandle; case CORINFO_TYPE_NATIVEINT: return m_simdHandleCache->Vector256NIntHandle; case CORINFO_TYPE_NATIVEUINT: return m_simdHandleCache->Vector256NUIntHandle; default: assert(!"Didn't find a class handle for simdType"); } } #endif // TARGET_XARCH #ifdef TARGET_ARM64 else if (simdType == TYP_SIMD8) { switch (simdBaseJitType) { case CORINFO_TYPE_FLOAT: return m_simdHandleCache->Vector64FloatHandle; case CORINFO_TYPE_DOUBLE: return m_simdHandleCache->Vector64DoubleHandle; case CORINFO_TYPE_INT: return m_simdHandleCache->Vector64IntHandle; case CORINFO_TYPE_USHORT: return m_simdHandleCache->Vector64UShortHandle; case CORINFO_TYPE_UBYTE: return m_simdHandleCache->Vector64UByteHandle; case CORINFO_TYPE_SHORT: return m_simdHandleCache->Vector64ShortHandle; case CORINFO_TYPE_BYTE: return m_simdHandleCache->Vector64ByteHandle; case CORINFO_TYPE_UINT: return m_simdHandleCache->Vector64UIntHandle; case CORINFO_TYPE_LONG: return m_simdHandleCache->Vector64LongHandle; case CORINFO_TYPE_ULONG: return m_simdHandleCache->Vector64ULongHandle; case CORINFO_TYPE_NATIVEINT: return m_simdHandleCache->Vector64NIntHandle; case CORINFO_TYPE_NATIVEUINT: return m_simdHandleCache->Vector64NUIntHandle; default: assert(!"Didn't find a class handle for simdType"); } } #endif // TARGET_ARM64 return NO_CLASS_HANDLE; } //------------------------------------------------------------------------ // vnEncodesResultTypeForHWIntrinsic(NamedIntrinsic hwIntrinsicID): // // Arguments: // hwIntrinsicID -- The id for the HW intrinsic // // Return Value: // Returns true if this intrinsic requires value numbering to add an // extra SimdType argument that encodes the resulting type. // If we don't do this overloaded versions can return the same VN // leading to incorrect CSE subsitutions. // /* static */ bool Compiler::vnEncodesResultTypeForHWIntrinsic(NamedIntrinsic hwIntrinsicID) { int numArgs = HWIntrinsicInfo::lookupNumArgs(hwIntrinsicID); // HW Intrinsic's with -1 for numArgs have a varying number of args, so we currently // give themm a unique value number them, and don't add an extra argument. // if (numArgs == -1) { return false; } // We iterate over all of the different baseType's for this intrinsic in the HWIntrinsicInfo table // We set diffInsCount to the number of instructions that can execute differently. // unsigned diffInsCount = 0; #ifdef TARGET_XARCH instruction lastIns = INS_invalid; #endif for (var_types baseType = TYP_BYTE; (baseType <= TYP_DOUBLE); baseType = (var_types)(baseType + 1)) { instruction curIns = HWIntrinsicInfo::lookupIns(hwIntrinsicID, baseType); if (curIns != INS_invalid) { #ifdef TARGET_XARCH if (curIns != lastIns) { diffInsCount++; // remember the last valid instruction that we saw lastIns = curIns; } #elif defined(TARGET_ARM64) // On ARM64 we use the same instruction and specify an insOpt arrangement // so we always consider the instruction operation to be different // diffInsCount++; #endif // TARGET if (diffInsCount >= 2) { // We can early exit the loop now break; } } } // If we see two (or more) different instructions we need the extra VNF_SimdType arg return (diffInsCount >= 2); } //------------------------------------------------------------------------ // lookupId: Gets the NamedIntrinsic for a given method name and InstructionSet // // Arguments: // comp -- The compiler // sig -- The signature of the intrinsic // className -- The name of the class associated with the HWIntrinsic to lookup // methodName -- The name of the method associated with the HWIntrinsic to lookup // enclosingClassName -- The name of the enclosing class of X64 classes // // Return Value: // The NamedIntrinsic associated with methodName and isa NamedIntrinsic HWIntrinsicInfo::lookupId(Compiler* comp, CORINFO_SIG_INFO* sig, const char* className, const char* methodName, const char* enclosingClassName) { // TODO-Throughput: replace sequential search by binary search CORINFO_InstructionSet isa = lookupIsa(className, enclosingClassName); if (isa == InstructionSet_ILLEGAL) { return NI_Illegal; } bool isIsaSupported = comp->compSupportsHWIntrinsic(isa); bool isHardwareAcceleratedProp = (strcmp(methodName, "get_IsHardwareAccelerated") == 0); #ifdef TARGET_XARCH if (isHardwareAcceleratedProp) { // Special case: Some of Vector128/256 APIs are hardware accelerated with Sse1 and Avx1, // but we want IsHardwareAccelerated to return true only when all of them are (there are // still can be cases where e.g. Sse41 might give an additional boost for Vector128, but it's // not important enough to bump the minimal Sse version here) if (strcmp(className, "Vector128") == 0) { isa = InstructionSet_SSE2; } else if (strcmp(className, "Vector256") == 0) { isa = InstructionSet_AVX2; } } #endif if ((strcmp(methodName, "get_IsSupported") == 0) || isHardwareAcceleratedProp) { return isIsaSupported ? (comp->compExactlyDependsOn(isa) ? NI_IsSupported_True : NI_IsSupported_Dynamic) : NI_IsSupported_False; } else if (!isIsaSupported) { return NI_Throw_PlatformNotSupportedException; } for (int i = 0; i < (NI_HW_INTRINSIC_END - NI_HW_INTRINSIC_START - 1); i++) { const HWIntrinsicInfo& intrinsicInfo = hwIntrinsicInfoArray[i]; if (isa != hwIntrinsicInfoArray[i].isa) { continue; } int numArgs = static_cast<unsigned>(intrinsicInfo.numArgs); if ((numArgs != -1) && (sig->numArgs != static_cast<unsigned>(intrinsicInfo.numArgs))) { continue; } if (strcmp(methodName, intrinsicInfo.name) == 0) { return intrinsicInfo.id; } } // There are several helper intrinsics that are implemented in managed code // Those intrinsics will hit this code path and need to return NI_Illegal return NI_Illegal; } //------------------------------------------------------------------------ // lookupSimdSize: Gets the SimdSize for a given HWIntrinsic and signature // // Arguments: // id -- The ID associated with the HWIntrinsic to lookup // sig -- The signature of the HWIntrinsic to lookup // // Return Value: // The SIMD size for the HWIntrinsic associated with id and sig // // Remarks: // This function is only used by the importer. After importation, we can // get the SIMD size from the GenTreeHWIntrinsic node. unsigned HWIntrinsicInfo::lookupSimdSize(Compiler* comp, NamedIntrinsic id, CORINFO_SIG_INFO* sig) { unsigned simdSize = 0; if (tryLookupSimdSize(id, &simdSize)) { return simdSize; } CORINFO_CLASS_HANDLE typeHnd = nullptr; if (HWIntrinsicInfo::BaseTypeFromFirstArg(id)) { typeHnd = comp->info.compCompHnd->getArgClass(sig, sig->args); } else if (HWIntrinsicInfo::BaseTypeFromSecondArg(id)) { CORINFO_ARG_LIST_HANDLE secondArg = comp->info.compCompHnd->getArgNext(sig->args); typeHnd = comp->info.compCompHnd->getArgClass(sig, secondArg); } else { assert(JITtype2varType(sig->retType) == TYP_STRUCT); typeHnd = sig->retTypeSigClass; } CorInfoType simdBaseJitType = comp->getBaseJitTypeAndSizeOfSIMDType(typeHnd, &simdSize); assert((simdSize > 0) && (simdBaseJitType != CORINFO_TYPE_UNDEF)); return simdSize; } //------------------------------------------------------------------------ // isImmOp: Checks whether the HWIntrinsic node has an imm operand // // Arguments: // id -- The NamedIntrinsic associated with the HWIntrinsic to lookup // op -- The operand to check // // Return Value: // true if the node has an imm operand; otherwise, false bool HWIntrinsicInfo::isImmOp(NamedIntrinsic id, const GenTree* op) { #ifdef TARGET_XARCH if (HWIntrinsicInfo::lookupCategory(id) != HW_Category_IMM) { return false; } if (!HWIntrinsicInfo::MaybeImm(id)) { return true; } #elif defined(TARGET_ARM64) if (!HWIntrinsicInfo::HasImmediateOperand(id)) { return false; } #else #error Unsupported platform #endif if (genActualType(op->TypeGet()) != TYP_INT) { return false; } return true; } //------------------------------------------------------------------------ // getArgForHWIntrinsic: pop an argument from the stack and validate its type // // Arguments: // argType -- the required type of argument // argClass -- the class handle of argType // expectAddr -- if true indicates we are expecting type stack entry to be a TYP_BYREF. // newobjThis -- For CEE_NEWOBJ, this is the temp grabbed for the allocated uninitalized object. // // Return Value: // the validated argument // GenTree* Compiler::getArgForHWIntrinsic(var_types argType, CORINFO_CLASS_HANDLE argClass, bool expectAddr, GenTree* newobjThis) { GenTree* arg = nullptr; if (varTypeIsStruct(argType)) { if (!varTypeIsSIMD(argType)) { unsigned int argSizeBytes; (void)getBaseJitTypeAndSizeOfSIMDType(argClass, &argSizeBytes); argType = getSIMDTypeForSize(argSizeBytes); } assert(varTypeIsSIMD(argType)); if (newobjThis == nullptr) { arg = impSIMDPopStack(argType, expectAddr); assert(varTypeIsSIMD(arg->TypeGet())); } else { assert((newobjThis->gtOper == GT_ADDR) && (newobjThis->AsOp()->gtOp1->gtOper == GT_LCL_VAR)); arg = newobjThis; // push newobj result on type stack unsigned tmp = arg->AsOp()->gtOp1->AsLclVarCommon()->GetLclNum(); impPushOnStack(gtNewLclvNode(tmp, lvaGetRealType(tmp)), verMakeTypeInfo(argClass).NormaliseForStack()); } } else { assert(varTypeIsArithmetic(argType)); arg = impPopStack().val; assert(varTypeIsArithmetic(arg->TypeGet())); assert(genActualType(arg->gtType) == genActualType(argType)); } return arg; } //------------------------------------------------------------------------ // addRangeCheckIfNeeded: add a GT_BOUNDS_CHECK node for non-full-range imm-intrinsic // // Arguments: // intrinsic -- intrinsic ID // immOp -- the immediate operand of the intrinsic // mustExpand -- true if the compiler is compiling the fallback(GT_CALL) of this intrinsics // immLowerBound -- lower incl. bound for a value of the immediate operand (for a non-full-range imm-intrinsic) // immUpperBound -- upper incl. bound for a value of the immediate operand (for a non-full-range imm-intrinsic) // // Return Value: // add a GT_BOUNDS_CHECK node for non-full-range imm-intrinsic, which would throw ArgumentOutOfRangeException // when the imm-argument is not in the valid range // GenTree* Compiler::addRangeCheckIfNeeded( NamedIntrinsic intrinsic, GenTree* immOp, bool mustExpand, int immLowerBound, int immUpperBound) { assert(immOp != nullptr); // Full-range imm-intrinsics do not need the range-check // because the imm-parameter of the intrinsic method is a byte. // AVX2 Gather intrinsics no not need the range-check // because their imm-parameter have discrete valid values that are handle by managed code if (mustExpand && HWIntrinsicInfo::isImmOp(intrinsic, immOp) #ifdef TARGET_XARCH && !HWIntrinsicInfo::isAVX2GatherIntrinsic(intrinsic) && !HWIntrinsicInfo::HasFullRangeImm(intrinsic) #endif ) { assert(!immOp->IsCnsIntOrI()); assert(varTypeIsUnsigned(immOp)); return addRangeCheckForHWIntrinsic(immOp, immLowerBound, immUpperBound); } else { return immOp; } } //------------------------------------------------------------------------ // addRangeCheckForHWIntrinsic: add a GT_BOUNDS_CHECK node for an intrinsic // // Arguments: // immOp -- the immediate operand of the intrinsic // immLowerBound -- lower incl. bound for a value of the immediate operand (for a non-full-range imm-intrinsic) // immUpperBound -- upper incl. bound for a value of the immediate operand (for a non-full-range imm-intrinsic) // // Return Value: // add a GT_BOUNDS_CHECK node for non-full-range imm-intrinsic, which would throw ArgumentOutOfRangeException // when the imm-argument is not in the valid range // GenTree* Compiler::addRangeCheckForHWIntrinsic(GenTree* immOp, int immLowerBound, int immUpperBound) { // Bounds check for value of an immediate operand // (immLowerBound <= immOp) && (immOp <= immUpperBound) // // implemented as a single comparison in the form of // // if ((immOp - immLowerBound) >= (immUpperBound - immLowerBound + 1)) // { // throw new ArgumentOutOfRangeException(); // } // // The value of (immUpperBound - immLowerBound + 1) is denoted as adjustedUpperBound. const ssize_t adjustedUpperBound = (ssize_t)immUpperBound - immLowerBound + 1; GenTree* adjustedUpperBoundNode = gtNewIconNode(adjustedUpperBound, TYP_INT); GenTree* immOpDup = nullptr; immOp = impCloneExpr(immOp, &immOpDup, NO_CLASS_HANDLE, (unsigned)CHECK_SPILL_ALL, nullptr DEBUGARG("Clone an immediate operand for immediate value bounds check")); if (immLowerBound != 0) { immOpDup = gtNewOperNode(GT_SUB, TYP_INT, immOpDup, gtNewIconNode(immLowerBound, TYP_INT)); } GenTreeBoundsChk* hwIntrinsicChk = new (this, GT_BOUNDS_CHECK) GenTreeBoundsChk(immOpDup, adjustedUpperBoundNode, SCK_ARG_RNG_EXCPN); return gtNewOperNode(GT_COMMA, immOp->TypeGet(), hwIntrinsicChk, immOp); } //------------------------------------------------------------------------ // compSupportsHWIntrinsic: check whether a given instruction is enabled via configuration // // Arguments: // isa - Instruction set // // Return Value: // true iff the given instruction set is enabled via configuration (environment variables, etc.). bool Compiler::compSupportsHWIntrinsic(CORINFO_InstructionSet isa) { return compHWIntrinsicDependsOn(isa) && (featureSIMD || HWIntrinsicInfo::isScalarIsa(isa)) && ( #ifdef DEBUG JitConfig.EnableIncompleteISAClass() || #endif HWIntrinsicInfo::isFullyImplementedIsa(isa)); } //------------------------------------------------------------------------ // impIsTableDrivenHWIntrinsic: // // Arguments: // intrinsicId - HW intrinsic id // category - category of a HW intrinsic // // Return Value: // returns true if this category can be table-driven in the importer // static bool impIsTableDrivenHWIntrinsic(NamedIntrinsic intrinsicId, HWIntrinsicCategory category) { return (category != HW_Category_Special) && HWIntrinsicInfo::RequiresCodegen(intrinsicId) && !HWIntrinsicInfo::HasSpecialImport(intrinsicId); } //------------------------------------------------------------------------ // isSupportedBaseType // // Arguments: // intrinsicId - HW intrinsic id // baseJitType - Base JIT type of the intrinsic. // // Return Value: // returns true if the baseType is supported for given intrinsic. // static bool isSupportedBaseType(NamedIntrinsic intrinsic, CorInfoType baseJitType) { if (baseJitType == CORINFO_TYPE_UNDEF) { return false; } var_types baseType = JitType2PreciseVarType(baseJitType); // We don't actually check the intrinsic outside of the false case as we expect // the exposed managed signatures are either generic and support all types // or they are explicit and support the type indicated. if (varTypeIsArithmetic(baseType)) { return true; } #ifdef TARGET_XARCH assert((intrinsic == NI_Vector128_As) || (intrinsic == NI_Vector128_AsByte) || (intrinsic == NI_Vector128_AsDouble) || (intrinsic == NI_Vector128_AsInt16) || (intrinsic == NI_Vector128_AsInt32) || (intrinsic == NI_Vector128_AsInt64) || (intrinsic == NI_Vector128_AsSByte) || (intrinsic == NI_Vector128_AsSingle) || (intrinsic == NI_Vector128_AsUInt16) || (intrinsic == NI_Vector128_AsUInt32) || (intrinsic == NI_Vector128_AsUInt64) || (intrinsic == NI_Vector128_get_AllBitsSet) || (intrinsic == NI_Vector128_get_Count) || (intrinsic == NI_Vector128_get_Zero) || (intrinsic == NI_Vector128_GetElement) || (intrinsic == NI_Vector128_WithElement) || (intrinsic == NI_Vector128_ToScalar) || (intrinsic == NI_Vector128_ToVector256) || (intrinsic == NI_Vector128_ToVector256Unsafe) || (intrinsic == NI_Vector256_As) || (intrinsic == NI_Vector256_AsByte) || (intrinsic == NI_Vector256_AsDouble) || (intrinsic == NI_Vector256_AsInt16) || (intrinsic == NI_Vector256_AsInt32) || (intrinsic == NI_Vector256_AsInt64) || (intrinsic == NI_Vector256_AsSByte) || (intrinsic == NI_Vector256_AsSingle) || (intrinsic == NI_Vector256_AsUInt16) || (intrinsic == NI_Vector256_AsUInt32) || (intrinsic == NI_Vector256_AsUInt64) || (intrinsic == NI_Vector256_get_AllBitsSet) || (intrinsic == NI_Vector256_get_Count) || (intrinsic == NI_Vector256_get_Zero) || (intrinsic == NI_Vector256_GetElement) || (intrinsic == NI_Vector256_WithElement) || (intrinsic == NI_Vector256_GetLower) || (intrinsic == NI_Vector256_ToScalar)); #endif // TARGET_XARCH #ifdef TARGET_ARM64 assert((intrinsic == NI_Vector64_As) || (intrinsic == NI_Vector64_AsByte) || (intrinsic == NI_Vector64_AsDouble) || (intrinsic == NI_Vector64_AsInt16) || (intrinsic == NI_Vector64_AsInt32) || (intrinsic == NI_Vector64_AsInt64) || (intrinsic == NI_Vector64_AsSByte) || (intrinsic == NI_Vector64_AsSingle) || (intrinsic == NI_Vector64_AsUInt16) || (intrinsic == NI_Vector64_AsUInt32) || (intrinsic == NI_Vector64_AsUInt64) || (intrinsic == NI_Vector64_get_AllBitsSet) || (intrinsic == NI_Vector64_get_Count) || (intrinsic == NI_Vector64_get_Zero) || (intrinsic == NI_Vector64_GetElement) || (intrinsic == NI_Vector64_ToScalar) || (intrinsic == NI_Vector64_ToVector128) || (intrinsic == NI_Vector64_ToVector128Unsafe) || (intrinsic == NI_Vector64_WithElement) || (intrinsic == NI_Vector128_As) || (intrinsic == NI_Vector128_AsByte) || (intrinsic == NI_Vector128_AsDouble) || (intrinsic == NI_Vector128_AsInt16) || (intrinsic == NI_Vector128_AsInt32) || (intrinsic == NI_Vector128_AsInt64) || (intrinsic == NI_Vector128_AsSByte) || (intrinsic == NI_Vector128_AsSingle) || (intrinsic == NI_Vector128_AsUInt16) || (intrinsic == NI_Vector128_AsUInt32) || (intrinsic == NI_Vector128_AsUInt64) || (intrinsic == NI_Vector128_get_AllBitsSet) || (intrinsic == NI_Vector128_get_Count) || (intrinsic == NI_Vector128_get_Zero) || (intrinsic == NI_Vector128_GetElement) || (intrinsic == NI_Vector128_GetLower) || (intrinsic == NI_Vector128_GetUpper) || (intrinsic == NI_Vector128_ToScalar) || (intrinsic == NI_Vector128_WithElement)); #endif // TARGET_ARM64 return false; } // HWIntrinsicSignatureReader: a helper class that "reads" a list of hardware intrinsic arguments and stores // the corresponding argument type descriptors as the fields of the class instance. // struct HWIntrinsicSignatureReader final { // Read: enumerates the list of arguments of a hardware intrinsic and stores the CORINFO_CLASS_HANDLE // and var_types values of each operand into the corresponding fields of the class instance. // // Arguments: // compHnd -- an instance of COMP_HANDLE class. // sig -- a hardware intrinsic signature. // void Read(COMP_HANDLE compHnd, CORINFO_SIG_INFO* sig) { CORINFO_ARG_LIST_HANDLE args = sig->args; if (sig->numArgs > 0) { op1JitType = strip(compHnd->getArgType(sig, args, &op1ClsHnd)); if (sig->numArgs > 1) { args = compHnd->getArgNext(args); op2JitType = strip(compHnd->getArgType(sig, args, &op2ClsHnd)); } if (sig->numArgs > 2) { args = compHnd->getArgNext(args); op3JitType = strip(compHnd->getArgType(sig, args, &op3ClsHnd)); } if (sig->numArgs > 3) { args = compHnd->getArgNext(args); op4JitType = strip(compHnd->getArgType(sig, args, &op4ClsHnd)); } } } CORINFO_CLASS_HANDLE op1ClsHnd; CORINFO_CLASS_HANDLE op2ClsHnd; CORINFO_CLASS_HANDLE op3ClsHnd; CORINFO_CLASS_HANDLE op4ClsHnd; CorInfoType op1JitType; CorInfoType op2JitType; CorInfoType op3JitType; CorInfoType op4JitType; var_types GetOp1Type() const { return JITtype2varType(op1JitType); } var_types GetOp2Type() const { return JITtype2varType(op2JitType); } var_types GetOp3Type() const { return JITtype2varType(op3JitType); } var_types GetOp4Type() const { return JITtype2varType(op4JitType); } }; //------------------------------------------------------------------------ // impHWIntrinsic: Import a hardware intrinsic as a GT_HWINTRINSIC node if possible // // Arguments: // intrinsic -- id of the intrinsic function. // clsHnd -- class handle containing the intrinsic function. // method -- method handle of the intrinsic function. // sig -- signature of the intrinsic call // mustExpand -- true if the intrinsic must return a GenTree*; otherwise, false // Return Value: // The GT_HWINTRINSIC node, or nullptr if not a supported intrinsic // GenTree* Compiler::impHWIntrinsic(NamedIntrinsic intrinsic, CORINFO_CLASS_HANDLE clsHnd, CORINFO_METHOD_HANDLE method, CORINFO_SIG_INFO* sig, bool mustExpand) { HWIntrinsicCategory category = HWIntrinsicInfo::lookupCategory(intrinsic); CORINFO_InstructionSet isa = HWIntrinsicInfo::lookupIsa(intrinsic); int numArgs = sig->numArgs; var_types retType = JITtype2varType(sig->retType); CorInfoType simdBaseJitType = CORINFO_TYPE_UNDEF; if ((retType == TYP_STRUCT) && featureSIMD) { unsigned int sizeBytes; simdBaseJitType = getBaseJitTypeAndSizeOfSIMDType(sig->retTypeSigClass, &sizeBytes); if (HWIntrinsicInfo::IsMultiReg(intrinsic)) { assert(sizeBytes == 0); } else { assert(sizeBytes != 0); // We want to return early here for cases where retType was TYP_STRUCT as per method signature and // rather than deferring the decision after getting the simdBaseJitType of arg. if (!isSupportedBaseType(intrinsic, simdBaseJitType)) { return nullptr; } retType = getSIMDTypeForSize(sizeBytes); } } simdBaseJitType = getBaseJitTypeFromArgIfNeeded(intrinsic, clsHnd, sig, simdBaseJitType); if (simdBaseJitType == CORINFO_TYPE_UNDEF) { if ((category == HW_Category_Scalar) || HWIntrinsicInfo::isScalarIsa(isa)) { simdBaseJitType = sig->retType; if (simdBaseJitType == CORINFO_TYPE_VOID) { simdBaseJitType = CORINFO_TYPE_UNDEF; } } else { assert(featureSIMD); unsigned int sizeBytes; simdBaseJitType = getBaseJitTypeAndSizeOfSIMDType(clsHnd, &sizeBytes); assert((category == HW_Category_Special) || (category == HW_Category_Helper) || (sizeBytes != 0)); } } // Immediately return if the category is other than scalar/special and this is not a supported base type. if ((category != HW_Category_Special) && (category != HW_Category_Scalar) && !HWIntrinsicInfo::isScalarIsa(isa) && !isSupportedBaseType(intrinsic, simdBaseJitType)) { return nullptr; } var_types simdBaseType = TYP_UNKNOWN; GenTree* immOp = nullptr; if (simdBaseJitType != CORINFO_TYPE_UNDEF) { simdBaseType = JitType2PreciseVarType(simdBaseJitType); } HWIntrinsicSignatureReader sigReader; sigReader.Read(info.compCompHnd, sig); #ifdef TARGET_ARM64 if ((intrinsic == NI_AdvSimd_Insert) || (intrinsic == NI_AdvSimd_InsertScalar) || (intrinsic == NI_AdvSimd_LoadAndInsertScalar)) { assert(sig->numArgs == 3); immOp = impStackTop(1).val; assert(HWIntrinsicInfo::isImmOp(intrinsic, immOp)); } else if (intrinsic == NI_AdvSimd_Arm64_InsertSelectedScalar) { // InsertSelectedScalar intrinsic has two immediate operands. // Since all the remaining intrinsics on both platforms have only one immediate // operand, in order to not complicate the shared logic even further we ensure here that // 1) The second immediate operand immOp2 is constant and // 2) its value belongs to [0, sizeof(op3) / sizeof(op3.BaseType)). // If either is false, we should fallback to the managed implementation Insert(dst, dstIdx, Extract(src, // srcIdx)). // The check for the first immediate operand immOp will use the same logic as other intrinsics that have an // immediate operand. GenTree* immOp2 = nullptr; assert(sig->numArgs == 4); immOp = impStackTop(2).val; immOp2 = impStackTop().val; assert(HWIntrinsicInfo::isImmOp(intrinsic, immOp)); assert(HWIntrinsicInfo::isImmOp(intrinsic, immOp2)); if (!immOp2->IsCnsIntOrI()) { assert(HWIntrinsicInfo::NoJmpTableImm(intrinsic)); return impNonConstFallback(intrinsic, retType, simdBaseJitType); } unsigned int otherSimdSize = 0; CorInfoType otherBaseJitType = getBaseJitTypeAndSizeOfSIMDType(sigReader.op3ClsHnd, &otherSimdSize); var_types otherBaseType = JitType2PreciseVarType(otherBaseJitType); assert(otherBaseJitType == simdBaseJitType); int immLowerBound2 = 0; int immUpperBound2 = 0; HWIntrinsicInfo::lookupImmBounds(intrinsic, otherSimdSize, otherBaseType, &immLowerBound2, &immUpperBound2); const int immVal2 = (int)immOp2->AsIntCon()->IconValue(); if ((immVal2 < immLowerBound2) || (immVal2 > immUpperBound2)) { assert(!mustExpand); return nullptr; } } else #endif if ((sig->numArgs > 0) && HWIntrinsicInfo::isImmOp(intrinsic, impStackTop().val)) { // NOTE: The following code assumes that for all intrinsics // taking an immediate operand, that operand will be last. immOp = impStackTop().val; } const unsigned simdSize = HWIntrinsicInfo::lookupSimdSize(this, intrinsic, sig); int immLowerBound = 0; int immUpperBound = 0; bool hasFullRangeImm = false; if (immOp != nullptr) { #ifdef TARGET_XARCH immUpperBound = HWIntrinsicInfo::lookupImmUpperBound(intrinsic); hasFullRangeImm = HWIntrinsicInfo::HasFullRangeImm(intrinsic); #elif defined(TARGET_ARM64) if (category == HW_Category_SIMDByIndexedElement) { CorInfoType indexedElementBaseJitType; var_types indexedElementBaseType; unsigned int indexedElementSimdSize = 0; if (numArgs == 3) { indexedElementBaseJitType = getBaseJitTypeAndSizeOfSIMDType(sigReader.op2ClsHnd, &indexedElementSimdSize); indexedElementBaseType = JitType2PreciseVarType(indexedElementBaseJitType); } else { assert(numArgs == 4); indexedElementBaseJitType = getBaseJitTypeAndSizeOfSIMDType(sigReader.op3ClsHnd, &indexedElementSimdSize); indexedElementBaseType = JitType2PreciseVarType(indexedElementBaseJitType); if (intrinsic == NI_Dp_DotProductBySelectedQuadruplet) { assert(((simdBaseType == TYP_INT) && (indexedElementBaseType == TYP_BYTE)) || ((simdBaseType == TYP_UINT) && (indexedElementBaseType == TYP_UBYTE))); // The second source operand of sdot, udot instructions is an indexed 32-bit element. indexedElementBaseJitType = simdBaseJitType; indexedElementBaseType = simdBaseType; } } assert(indexedElementBaseType == simdBaseType); HWIntrinsicInfo::lookupImmBounds(intrinsic, indexedElementSimdSize, simdBaseType, &immLowerBound, &immUpperBound); } else { HWIntrinsicInfo::lookupImmBounds(intrinsic, simdSize, simdBaseType, &immLowerBound, &immUpperBound); } #endif if (!hasFullRangeImm && immOp->IsCnsIntOrI()) { const int ival = (int)immOp->AsIntCon()->IconValue(); bool immOutOfRange; #ifdef TARGET_XARCH if (HWIntrinsicInfo::isAVX2GatherIntrinsic(intrinsic)) { immOutOfRange = (ival != 1) && (ival != 2) && (ival != 4) && (ival != 8); } else #endif { immOutOfRange = (ival < immLowerBound) || (ival > immUpperBound); } if (immOutOfRange) { assert(!mustExpand); // The imm-HWintrinsics that do not accept all imm8 values may throw // ArgumentOutOfRangeException when the imm argument is not in the valid range return nullptr; } } else if (!immOp->IsCnsIntOrI()) { if (HWIntrinsicInfo::NoJmpTableImm(intrinsic)) { return impNonConstFallback(intrinsic, retType, simdBaseJitType); } else if (!mustExpand) { // When the imm-argument is not a constant and we are not being forced to expand, we need to // return nullptr so a GT_CALL to the intrinsic method is emitted instead. The // intrinsic method is recursive and will be forced to expand, at which point // we emit some less efficient fallback code. return nullptr; } } } if (HWIntrinsicInfo::IsFloatingPointUsed(intrinsic)) { // Set `compFloatingPointUsed` to cover the scenario where an intrinsic is operating on SIMD fields, but // where no SIMD local vars are in use. This is the same logic as is used for FEATURE_SIMD. compFloatingPointUsed = true; } // table-driven importer of simple intrinsics if (impIsTableDrivenHWIntrinsic(intrinsic, category)) { const bool isScalar = (category == HW_Category_Scalar); assert(numArgs >= 0); if (!isScalar && ((HWIntrinsicInfo::lookupIns(intrinsic, simdBaseType) == INS_invalid) || ((simdSize != 8) && (simdSize != 16) && (simdSize != 32)))) { assert(!"Unexpected HW Intrinsic"); return nullptr; } GenTree* op1 = nullptr; GenTree* op2 = nullptr; GenTree* op3 = nullptr; GenTree* op4 = nullptr; GenTreeHWIntrinsic* retNode = nullptr; switch (numArgs) { case 0: assert(!isScalar); retNode = gtNewSimdHWIntrinsicNode(retType, intrinsic, simdBaseJitType, simdSize); break; case 1: op1 = getArgForHWIntrinsic(sigReader.GetOp1Type(), sigReader.op1ClsHnd); if ((category == HW_Category_MemoryLoad) && op1->OperIs(GT_CAST)) { // Although the API specifies a pointer, if what we have is a BYREF, that's what // we really want, so throw away the cast. if (op1->gtGetOp1()->TypeGet() == TYP_BYREF) { op1 = op1->gtGetOp1(); } } retNode = isScalar ? gtNewScalarHWIntrinsicNode(retType, op1, intrinsic) : gtNewSimdHWIntrinsicNode(retType, op1, intrinsic, simdBaseJitType, simdSize); #if defined(TARGET_XARCH) switch (intrinsic) { case NI_SSE41_ConvertToVector128Int16: case NI_SSE41_ConvertToVector128Int32: case NI_SSE41_ConvertToVector128Int64: case NI_AVX2_BroadcastScalarToVector128: case NI_AVX2_BroadcastScalarToVector256: case NI_AVX2_ConvertToVector256Int16: case NI_AVX2_ConvertToVector256Int32: case NI_AVX2_ConvertToVector256Int64: { // These intrinsics have both pointer and vector overloads // We want to be able to differentiate between them so lets // just track the aux type as a ptr or undefined, depending CorInfoType auxiliaryType = CORINFO_TYPE_UNDEF; if (!varTypeIsSIMD(op1->TypeGet())) { auxiliaryType = CORINFO_TYPE_PTR; } retNode->AsHWIntrinsic()->SetAuxiliaryJitType(auxiliaryType); break; } default: { break; } } #endif // TARGET_XARCH break; case 2: op2 = getArgForHWIntrinsic(sigReader.GetOp2Type(), sigReader.op2ClsHnd); op2 = addRangeCheckIfNeeded(intrinsic, op2, mustExpand, immLowerBound, immUpperBound); op1 = getArgForHWIntrinsic(sigReader.GetOp1Type(), sigReader.op1ClsHnd); retNode = isScalar ? gtNewScalarHWIntrinsicNode(retType, op1, op2, intrinsic) : gtNewSimdHWIntrinsicNode(retType, op1, op2, intrinsic, simdBaseJitType, simdSize); #ifdef TARGET_XARCH if ((intrinsic == NI_SSE42_Crc32) || (intrinsic == NI_SSE42_X64_Crc32)) { // TODO-XArch-Cleanup: currently we use the simdBaseJitType to bring the type of the second argument // to the code generator. May encode the overload info in other way. retNode->AsHWIntrinsic()->SetSimdBaseJitType(sigReader.op2JitType); } #elif defined(TARGET_ARM64) switch (intrinsic) { case NI_Crc32_ComputeCrc32: case NI_Crc32_ComputeCrc32C: case NI_Crc32_Arm64_ComputeCrc32: case NI_Crc32_Arm64_ComputeCrc32C: retNode->AsHWIntrinsic()->SetSimdBaseJitType(sigReader.op2JitType); break; case NI_AdvSimd_AddWideningUpper: case NI_AdvSimd_SubtractWideningUpper: assert(varTypeIsSIMD(op1->TypeGet())); retNode->AsHWIntrinsic()->SetAuxiliaryJitType(getBaseJitTypeOfSIMDType(sigReader.op1ClsHnd)); break; case NI_AdvSimd_Arm64_AddSaturateScalar: assert(varTypeIsSIMD(op2->TypeGet())); retNode->AsHWIntrinsic()->SetAuxiliaryJitType(getBaseJitTypeOfSIMDType(sigReader.op2ClsHnd)); break; case NI_ArmBase_Arm64_MultiplyHigh: if (sig->retType == CORINFO_TYPE_ULONG) { retNode->AsHWIntrinsic()->SetSimdBaseJitType(CORINFO_TYPE_ULONG); } else { assert(sig->retType == CORINFO_TYPE_LONG); retNode->AsHWIntrinsic()->SetSimdBaseJitType(CORINFO_TYPE_LONG); } break; default: break; } #endif break; case 3: op3 = getArgForHWIntrinsic(sigReader.GetOp3Type(), sigReader.op3ClsHnd); op2 = getArgForHWIntrinsic(sigReader.GetOp2Type(), sigReader.op2ClsHnd); op1 = getArgForHWIntrinsic(sigReader.GetOp1Type(), sigReader.op1ClsHnd); #ifdef TARGET_ARM64 if (intrinsic == NI_AdvSimd_LoadAndInsertScalar) { op2 = addRangeCheckIfNeeded(intrinsic, op2, mustExpand, immLowerBound, immUpperBound); if (op1->OperIs(GT_CAST)) { // Although the API specifies a pointer, if what we have is a BYREF, that's what // we really want, so throw away the cast. if (op1->gtGetOp1()->TypeGet() == TYP_BYREF) { op1 = op1->gtGetOp1(); } } } else if ((intrinsic == NI_AdvSimd_Insert) || (intrinsic == NI_AdvSimd_InsertScalar)) { op2 = addRangeCheckIfNeeded(intrinsic, op2, mustExpand, immLowerBound, immUpperBound); } else #endif { op3 = addRangeCheckIfNeeded(intrinsic, op3, mustExpand, immLowerBound, immUpperBound); } retNode = isScalar ? gtNewScalarHWIntrinsicNode(retType, op1, op2, op3, intrinsic) : gtNewSimdHWIntrinsicNode(retType, op1, op2, op3, intrinsic, simdBaseJitType, simdSize); #ifdef TARGET_XARCH if ((intrinsic == NI_AVX2_GatherVector128) || (intrinsic == NI_AVX2_GatherVector256)) { assert(varTypeIsSIMD(op2->TypeGet())); retNode->AsHWIntrinsic()->SetAuxiliaryJitType(getBaseJitTypeOfSIMDType(sigReader.op2ClsHnd)); } #endif break; #ifdef TARGET_ARM64 case 4: op4 = getArgForHWIntrinsic(sigReader.GetOp4Type(), sigReader.op4ClsHnd); op4 = addRangeCheckIfNeeded(intrinsic, op4, mustExpand, immLowerBound, immUpperBound); op3 = getArgForHWIntrinsic(sigReader.GetOp3Type(), sigReader.op3ClsHnd); op2 = getArgForHWIntrinsic(sigReader.GetOp2Type(), sigReader.op2ClsHnd); op1 = getArgForHWIntrinsic(sigReader.GetOp1Type(), sigReader.op1ClsHnd); assert(!isScalar); retNode = gtNewSimdHWIntrinsicNode(retType, op1, op2, op3, op4, intrinsic, simdBaseJitType, simdSize); break; #endif default: return nullptr; } const bool isMemoryStore = retNode->OperIsMemoryStore(); if (isMemoryStore || retNode->OperIsMemoryLoad()) { if (isMemoryStore) { // A MemoryStore operation is an assignment retNode->gtFlags |= GTF_ASG; } // This operation contains an implicit indirection // it could point into the global heap or // it could throw a null reference exception. // retNode->gtFlags |= (GTF_GLOB_REF | GTF_EXCEPT); } return retNode; } return impSpecialIntrinsic(intrinsic, clsHnd, method, sig, simdBaseJitType, retType, simdSize); } #endif // FEATURE_HW_INTRINSICS
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "jitpch.h" #include "hwintrinsic.h" #ifdef FEATURE_HW_INTRINSICS static const HWIntrinsicInfo hwIntrinsicInfoArray[] = { // clang-format off #if defined(TARGET_XARCH) #define HARDWARE_INTRINSIC(isa, name, size, numarg, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, category, flag) \ {NI_##isa##_##name, #name, InstructionSet_##isa, size, numarg, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, category, static_cast<HWIntrinsicFlag>(flag)}, #include "hwintrinsiclistxarch.h" #elif defined (TARGET_ARM64) #define HARDWARE_INTRINSIC(isa, name, size, numarg, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, category, flag) \ {NI_##isa##_##name, #name, InstructionSet_##isa, size, numarg, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, category, static_cast<HWIntrinsicFlag>(flag)}, #include "hwintrinsiclistarm64.h" #else #error Unsupported platform #endif // clang-format on }; //------------------------------------------------------------------------ // lookup: Gets the HWIntrinsicInfo associated with a given NamedIntrinsic // // Arguments: // id -- The NamedIntrinsic associated with the HWIntrinsic to lookup // // Return Value: // The HWIntrinsicInfo associated with id const HWIntrinsicInfo& HWIntrinsicInfo::lookup(NamedIntrinsic id) { assert(id != NI_Illegal); assert(id > NI_HW_INTRINSIC_START); assert(id < NI_HW_INTRINSIC_END); return hwIntrinsicInfoArray[id - NI_HW_INTRINSIC_START - 1]; } //------------------------------------------------------------------------ // getBaseJitTypeFromArgIfNeeded: Get simdBaseJitType of intrinsic from 1st or 2nd argument depending on the flag // // Arguments: // intrinsic -- id of the intrinsic function. // clsHnd -- class handle containing the intrinsic function. // method -- method handle of the intrinsic function. // sig -- signature of the intrinsic call. // simdBaseJitType -- Predetermined simdBaseJitType, could be CORINFO_TYPE_UNDEF // // Return Value: // The basetype of intrinsic of it can be fetched from 1st or 2nd argument, else return baseType unmodified. // CorInfoType Compiler::getBaseJitTypeFromArgIfNeeded(NamedIntrinsic intrinsic, CORINFO_CLASS_HANDLE clsHnd, CORINFO_SIG_INFO* sig, CorInfoType simdBaseJitType) { if (HWIntrinsicInfo::BaseTypeFromSecondArg(intrinsic) || HWIntrinsicInfo::BaseTypeFromFirstArg(intrinsic)) { CORINFO_ARG_LIST_HANDLE arg = sig->args; if (HWIntrinsicInfo::BaseTypeFromSecondArg(intrinsic)) { arg = info.compCompHnd->getArgNext(arg); } CORINFO_CLASS_HANDLE argClass = info.compCompHnd->getArgClass(sig, arg); simdBaseJitType = getBaseJitTypeAndSizeOfSIMDType(argClass); if (simdBaseJitType == CORINFO_TYPE_UNDEF) // the argument is not a vector { CORINFO_CLASS_HANDLE tmpClass; simdBaseJitType = strip(info.compCompHnd->getArgType(sig, arg, &tmpClass)); if (simdBaseJitType == CORINFO_TYPE_PTR) { simdBaseJitType = info.compCompHnd->getChildType(argClass, &tmpClass); } } assert(simdBaseJitType != CORINFO_TYPE_UNDEF); } return simdBaseJitType; } CORINFO_CLASS_HANDLE Compiler::gtGetStructHandleForHWSIMD(var_types simdType, CorInfoType simdBaseJitType) { if (m_simdHandleCache == nullptr) { return NO_CLASS_HANDLE; } if (simdType == TYP_SIMD16) { switch (simdBaseJitType) { case CORINFO_TYPE_FLOAT: return m_simdHandleCache->Vector128FloatHandle; case CORINFO_TYPE_DOUBLE: return m_simdHandleCache->Vector128DoubleHandle; case CORINFO_TYPE_INT: return m_simdHandleCache->Vector128IntHandle; case CORINFO_TYPE_USHORT: return m_simdHandleCache->Vector128UShortHandle; case CORINFO_TYPE_UBYTE: return m_simdHandleCache->Vector128UByteHandle; case CORINFO_TYPE_SHORT: return m_simdHandleCache->Vector128ShortHandle; case CORINFO_TYPE_BYTE: return m_simdHandleCache->Vector128ByteHandle; case CORINFO_TYPE_LONG: return m_simdHandleCache->Vector128LongHandle; case CORINFO_TYPE_UINT: return m_simdHandleCache->Vector128UIntHandle; case CORINFO_TYPE_ULONG: return m_simdHandleCache->Vector128ULongHandle; case CORINFO_TYPE_NATIVEINT: return m_simdHandleCache->Vector128NIntHandle; case CORINFO_TYPE_NATIVEUINT: return m_simdHandleCache->Vector128NUIntHandle; default: assert(!"Didn't find a class handle for simdType"); } } #ifdef TARGET_XARCH else if (simdType == TYP_SIMD32) { switch (simdBaseJitType) { case CORINFO_TYPE_FLOAT: return m_simdHandleCache->Vector256FloatHandle; case CORINFO_TYPE_DOUBLE: return m_simdHandleCache->Vector256DoubleHandle; case CORINFO_TYPE_INT: return m_simdHandleCache->Vector256IntHandle; case CORINFO_TYPE_USHORT: return m_simdHandleCache->Vector256UShortHandle; case CORINFO_TYPE_UBYTE: return m_simdHandleCache->Vector256UByteHandle; case CORINFO_TYPE_SHORT: return m_simdHandleCache->Vector256ShortHandle; case CORINFO_TYPE_BYTE: return m_simdHandleCache->Vector256ByteHandle; case CORINFO_TYPE_LONG: return m_simdHandleCache->Vector256LongHandle; case CORINFO_TYPE_UINT: return m_simdHandleCache->Vector256UIntHandle; case CORINFO_TYPE_ULONG: return m_simdHandleCache->Vector256ULongHandle; case CORINFO_TYPE_NATIVEINT: return m_simdHandleCache->Vector256NIntHandle; case CORINFO_TYPE_NATIVEUINT: return m_simdHandleCache->Vector256NUIntHandle; default: assert(!"Didn't find a class handle for simdType"); } } #endif // TARGET_XARCH #ifdef TARGET_ARM64 else if (simdType == TYP_SIMD8) { switch (simdBaseJitType) { case CORINFO_TYPE_FLOAT: return m_simdHandleCache->Vector64FloatHandle; case CORINFO_TYPE_DOUBLE: return m_simdHandleCache->Vector64DoubleHandle; case CORINFO_TYPE_INT: return m_simdHandleCache->Vector64IntHandle; case CORINFO_TYPE_USHORT: return m_simdHandleCache->Vector64UShortHandle; case CORINFO_TYPE_UBYTE: return m_simdHandleCache->Vector64UByteHandle; case CORINFO_TYPE_SHORT: return m_simdHandleCache->Vector64ShortHandle; case CORINFO_TYPE_BYTE: return m_simdHandleCache->Vector64ByteHandle; case CORINFO_TYPE_UINT: return m_simdHandleCache->Vector64UIntHandle; case CORINFO_TYPE_LONG: return m_simdHandleCache->Vector64LongHandle; case CORINFO_TYPE_ULONG: return m_simdHandleCache->Vector64ULongHandle; case CORINFO_TYPE_NATIVEINT: return m_simdHandleCache->Vector64NIntHandle; case CORINFO_TYPE_NATIVEUINT: return m_simdHandleCache->Vector64NUIntHandle; default: assert(!"Didn't find a class handle for simdType"); } } #endif // TARGET_ARM64 return NO_CLASS_HANDLE; } //------------------------------------------------------------------------ // vnEncodesResultTypeForHWIntrinsic(NamedIntrinsic hwIntrinsicID): // // Arguments: // hwIntrinsicID -- The id for the HW intrinsic // // Return Value: // Returns true if this intrinsic requires value numbering to add an // extra SimdType argument that encodes the resulting type. // If we don't do this overloaded versions can return the same VN // leading to incorrect CSE subsitutions. // /* static */ bool Compiler::vnEncodesResultTypeForHWIntrinsic(NamedIntrinsic hwIntrinsicID) { int numArgs = HWIntrinsicInfo::lookupNumArgs(hwIntrinsicID); // HW Intrinsic's with -1 for numArgs have a varying number of args, so we currently // give themm a unique value number them, and don't add an extra argument. // if (numArgs == -1) { return false; } // We iterate over all of the different baseType's for this intrinsic in the HWIntrinsicInfo table // We set diffInsCount to the number of instructions that can execute differently. // unsigned diffInsCount = 0; #ifdef TARGET_XARCH instruction lastIns = INS_invalid; #endif for (var_types baseType = TYP_BYTE; (baseType <= TYP_DOUBLE); baseType = (var_types)(baseType + 1)) { instruction curIns = HWIntrinsicInfo::lookupIns(hwIntrinsicID, baseType); if (curIns != INS_invalid) { #ifdef TARGET_XARCH if (curIns != lastIns) { diffInsCount++; // remember the last valid instruction that we saw lastIns = curIns; } #elif defined(TARGET_ARM64) // On ARM64 we use the same instruction and specify an insOpt arrangement // so we always consider the instruction operation to be different // diffInsCount++; #endif // TARGET if (diffInsCount >= 2) { // We can early exit the loop now break; } } } // If we see two (or more) different instructions we need the extra VNF_SimdType arg return (diffInsCount >= 2); } //------------------------------------------------------------------------ // lookupId: Gets the NamedIntrinsic for a given method name and InstructionSet // // Arguments: // comp -- The compiler // sig -- The signature of the intrinsic // className -- The name of the class associated with the HWIntrinsic to lookup // methodName -- The name of the method associated with the HWIntrinsic to lookup // enclosingClassName -- The name of the enclosing class of X64 classes // // Return Value: // The NamedIntrinsic associated with methodName and isa NamedIntrinsic HWIntrinsicInfo::lookupId(Compiler* comp, CORINFO_SIG_INFO* sig, const char* className, const char* methodName, const char* enclosingClassName) { // TODO-Throughput: replace sequential search by binary search CORINFO_InstructionSet isa = lookupIsa(className, enclosingClassName); if (isa == InstructionSet_ILLEGAL) { return NI_Illegal; } bool isIsaSupported = comp->compSupportsHWIntrinsic(isa); bool isHardwareAcceleratedProp = (strcmp(methodName, "get_IsHardwareAccelerated") == 0); #ifdef TARGET_XARCH if (isHardwareAcceleratedProp) { // Special case: Some of Vector128/256 APIs are hardware accelerated with Sse1 and Avx1, // but we want IsHardwareAccelerated to return true only when all of them are (there are // still can be cases where e.g. Sse41 might give an additional boost for Vector128, but it's // not important enough to bump the minimal Sse version here) if (strcmp(className, "Vector128") == 0) { isa = InstructionSet_SSE2; } else if (strcmp(className, "Vector256") == 0) { isa = InstructionSet_AVX2; } } #endif if ((strcmp(methodName, "get_IsSupported") == 0) || isHardwareAcceleratedProp) { return isIsaSupported ? (comp->compExactlyDependsOn(isa) ? NI_IsSupported_True : NI_IsSupported_Dynamic) : NI_IsSupported_False; } else if (!isIsaSupported) { return NI_Throw_PlatformNotSupportedException; } for (int i = 0; i < (NI_HW_INTRINSIC_END - NI_HW_INTRINSIC_START - 1); i++) { const HWIntrinsicInfo& intrinsicInfo = hwIntrinsicInfoArray[i]; if (isa != hwIntrinsicInfoArray[i].isa) { continue; } int numArgs = static_cast<unsigned>(intrinsicInfo.numArgs); if ((numArgs != -1) && (sig->numArgs != static_cast<unsigned>(intrinsicInfo.numArgs))) { continue; } if (strcmp(methodName, intrinsicInfo.name) == 0) { return intrinsicInfo.id; } } // There are several helper intrinsics that are implemented in managed code // Those intrinsics will hit this code path and need to return NI_Illegal return NI_Illegal; } //------------------------------------------------------------------------ // lookupSimdSize: Gets the SimdSize for a given HWIntrinsic and signature // // Arguments: // id -- The ID associated with the HWIntrinsic to lookup // sig -- The signature of the HWIntrinsic to lookup // // Return Value: // The SIMD size for the HWIntrinsic associated with id and sig // // Remarks: // This function is only used by the importer. After importation, we can // get the SIMD size from the GenTreeHWIntrinsic node. unsigned HWIntrinsicInfo::lookupSimdSize(Compiler* comp, NamedIntrinsic id, CORINFO_SIG_INFO* sig) { unsigned simdSize = 0; if (tryLookupSimdSize(id, &simdSize)) { return simdSize; } CORINFO_CLASS_HANDLE typeHnd = nullptr; if (HWIntrinsicInfo::BaseTypeFromFirstArg(id)) { typeHnd = comp->info.compCompHnd->getArgClass(sig, sig->args); } else if (HWIntrinsicInfo::BaseTypeFromSecondArg(id)) { CORINFO_ARG_LIST_HANDLE secondArg = comp->info.compCompHnd->getArgNext(sig->args); typeHnd = comp->info.compCompHnd->getArgClass(sig, secondArg); } else { assert(JITtype2varType(sig->retType) == TYP_STRUCT); typeHnd = sig->retTypeSigClass; } CorInfoType simdBaseJitType = comp->getBaseJitTypeAndSizeOfSIMDType(typeHnd, &simdSize); assert((simdSize > 0) && (simdBaseJitType != CORINFO_TYPE_UNDEF)); return simdSize; } //------------------------------------------------------------------------ // isImmOp: Checks whether the HWIntrinsic node has an imm operand // // Arguments: // id -- The NamedIntrinsic associated with the HWIntrinsic to lookup // op -- The operand to check // // Return Value: // true if the node has an imm operand; otherwise, false bool HWIntrinsicInfo::isImmOp(NamedIntrinsic id, const GenTree* op) { #ifdef TARGET_XARCH if (HWIntrinsicInfo::lookupCategory(id) != HW_Category_IMM) { return false; } if (!HWIntrinsicInfo::MaybeImm(id)) { return true; } #elif defined(TARGET_ARM64) if (!HWIntrinsicInfo::HasImmediateOperand(id)) { return false; } #else #error Unsupported platform #endif if (genActualType(op->TypeGet()) != TYP_INT) { return false; } return true; } //------------------------------------------------------------------------ // getArgForHWIntrinsic: pop an argument from the stack and validate its type // // Arguments: // argType -- the required type of argument // argClass -- the class handle of argType // expectAddr -- if true indicates we are expecting type stack entry to be a TYP_BYREF. // newobjThis -- For CEE_NEWOBJ, this is the temp grabbed for the allocated uninitalized object. // // Return Value: // the validated argument // GenTree* Compiler::getArgForHWIntrinsic(var_types argType, CORINFO_CLASS_HANDLE argClass, bool expectAddr, GenTree* newobjThis) { GenTree* arg = nullptr; if (varTypeIsStruct(argType)) { if (!varTypeIsSIMD(argType)) { unsigned int argSizeBytes; (void)getBaseJitTypeAndSizeOfSIMDType(argClass, &argSizeBytes); argType = getSIMDTypeForSize(argSizeBytes); } assert(varTypeIsSIMD(argType)); if (newobjThis == nullptr) { arg = impSIMDPopStack(argType, expectAddr); assert(varTypeIsSIMD(arg->TypeGet())); } else { assert((newobjThis->gtOper == GT_ADDR) && (newobjThis->AsOp()->gtOp1->gtOper == GT_LCL_VAR)); arg = newobjThis; // push newobj result on type stack unsigned tmp = arg->AsOp()->gtOp1->AsLclVarCommon()->GetLclNum(); impPushOnStack(gtNewLclvNode(tmp, lvaGetRealType(tmp)), verMakeTypeInfo(argClass).NormaliseForStack()); } } else { assert(varTypeIsArithmetic(argType)); arg = impPopStack().val; assert(varTypeIsArithmetic(arg->TypeGet())); assert(genActualType(arg->gtType) == genActualType(argType)); } return arg; } //------------------------------------------------------------------------ // addRangeCheckIfNeeded: add a GT_BOUNDS_CHECK node for non-full-range imm-intrinsic // // Arguments: // intrinsic -- intrinsic ID // immOp -- the immediate operand of the intrinsic // mustExpand -- true if the compiler is compiling the fallback(GT_CALL) of this intrinsics // immLowerBound -- lower incl. bound for a value of the immediate operand (for a non-full-range imm-intrinsic) // immUpperBound -- upper incl. bound for a value of the immediate operand (for a non-full-range imm-intrinsic) // // Return Value: // add a GT_BOUNDS_CHECK node for non-full-range imm-intrinsic, which would throw ArgumentOutOfRangeException // when the imm-argument is not in the valid range // GenTree* Compiler::addRangeCheckIfNeeded( NamedIntrinsic intrinsic, GenTree* immOp, bool mustExpand, int immLowerBound, int immUpperBound) { assert(immOp != nullptr); // Full-range imm-intrinsics do not need the range-check // because the imm-parameter of the intrinsic method is a byte. // AVX2 Gather intrinsics no not need the range-check // because their imm-parameter have discrete valid values that are handle by managed code if (mustExpand && HWIntrinsicInfo::isImmOp(intrinsic, immOp) #ifdef TARGET_XARCH && !HWIntrinsicInfo::isAVX2GatherIntrinsic(intrinsic) && !HWIntrinsicInfo::HasFullRangeImm(intrinsic) #endif ) { assert(!immOp->IsCnsIntOrI()); assert(varTypeIsUnsigned(immOp)); return addRangeCheckForHWIntrinsic(immOp, immLowerBound, immUpperBound); } else { return immOp; } } //------------------------------------------------------------------------ // addRangeCheckForHWIntrinsic: add a GT_BOUNDS_CHECK node for an intrinsic // // Arguments: // immOp -- the immediate operand of the intrinsic // immLowerBound -- lower incl. bound for a value of the immediate operand (for a non-full-range imm-intrinsic) // immUpperBound -- upper incl. bound for a value of the immediate operand (for a non-full-range imm-intrinsic) // // Return Value: // add a GT_BOUNDS_CHECK node for non-full-range imm-intrinsic, which would throw ArgumentOutOfRangeException // when the imm-argument is not in the valid range // GenTree* Compiler::addRangeCheckForHWIntrinsic(GenTree* immOp, int immLowerBound, int immUpperBound) { // Bounds check for value of an immediate operand // (immLowerBound <= immOp) && (immOp <= immUpperBound) // // implemented as a single comparison in the form of // // if ((immOp - immLowerBound) >= (immUpperBound - immLowerBound + 1)) // { // throw new ArgumentOutOfRangeException(); // } // // The value of (immUpperBound - immLowerBound + 1) is denoted as adjustedUpperBound. const ssize_t adjustedUpperBound = (ssize_t)immUpperBound - immLowerBound + 1; GenTree* adjustedUpperBoundNode = gtNewIconNode(adjustedUpperBound, TYP_INT); GenTree* immOpDup = nullptr; immOp = impCloneExpr(immOp, &immOpDup, NO_CLASS_HANDLE, (unsigned)CHECK_SPILL_ALL, nullptr DEBUGARG("Clone an immediate operand for immediate value bounds check")); if (immLowerBound != 0) { immOpDup = gtNewOperNode(GT_SUB, TYP_INT, immOpDup, gtNewIconNode(immLowerBound, TYP_INT)); } GenTreeBoundsChk* hwIntrinsicChk = new (this, GT_BOUNDS_CHECK) GenTreeBoundsChk(immOpDup, adjustedUpperBoundNode, SCK_ARG_RNG_EXCPN); return gtNewOperNode(GT_COMMA, immOp->TypeGet(), hwIntrinsicChk, immOp); } //------------------------------------------------------------------------ // compSupportsHWIntrinsic: check whether a given instruction is enabled via configuration // // Arguments: // isa - Instruction set // // Return Value: // true iff the given instruction set is enabled via configuration (environment variables, etc.). bool Compiler::compSupportsHWIntrinsic(CORINFO_InstructionSet isa) { return compHWIntrinsicDependsOn(isa) && (featureSIMD || HWIntrinsicInfo::isScalarIsa(isa)) && ( #ifdef DEBUG JitConfig.EnableIncompleteISAClass() || #endif HWIntrinsicInfo::isFullyImplementedIsa(isa)); } //------------------------------------------------------------------------ // impIsTableDrivenHWIntrinsic: // // Arguments: // intrinsicId - HW intrinsic id // category - category of a HW intrinsic // // Return Value: // returns true if this category can be table-driven in the importer // static bool impIsTableDrivenHWIntrinsic(NamedIntrinsic intrinsicId, HWIntrinsicCategory category) { return (category != HW_Category_Special) && HWIntrinsicInfo::RequiresCodegen(intrinsicId) && !HWIntrinsicInfo::HasSpecialImport(intrinsicId); } //------------------------------------------------------------------------ // isSupportedBaseType // // Arguments: // intrinsicId - HW intrinsic id // baseJitType - Base JIT type of the intrinsic. // // Return Value: // returns true if the baseType is supported for given intrinsic. // static bool isSupportedBaseType(NamedIntrinsic intrinsic, CorInfoType baseJitType) { if (baseJitType == CORINFO_TYPE_UNDEF) { return false; } var_types baseType = JitType2PreciseVarType(baseJitType); // We don't actually check the intrinsic outside of the false case as we expect // the exposed managed signatures are either generic and support all types // or they are explicit and support the type indicated. if (varTypeIsArithmetic(baseType)) { return true; } #ifdef TARGET_XARCH assert((intrinsic == NI_Vector128_As) || (intrinsic == NI_Vector128_AsByte) || (intrinsic == NI_Vector128_AsDouble) || (intrinsic == NI_Vector128_AsInt16) || (intrinsic == NI_Vector128_AsInt32) || (intrinsic == NI_Vector128_AsInt64) || (intrinsic == NI_Vector128_AsSByte) || (intrinsic == NI_Vector128_AsSingle) || (intrinsic == NI_Vector128_AsUInt16) || (intrinsic == NI_Vector128_AsUInt32) || (intrinsic == NI_Vector128_AsUInt64) || (intrinsic == NI_Vector128_get_AllBitsSet) || (intrinsic == NI_Vector128_get_Count) || (intrinsic == NI_Vector128_get_Zero) || (intrinsic == NI_Vector128_GetElement) || (intrinsic == NI_Vector128_WithElement) || (intrinsic == NI_Vector128_ToScalar) || (intrinsic == NI_Vector128_ToVector256) || (intrinsic == NI_Vector128_ToVector256Unsafe) || (intrinsic == NI_Vector256_As) || (intrinsic == NI_Vector256_AsByte) || (intrinsic == NI_Vector256_AsDouble) || (intrinsic == NI_Vector256_AsInt16) || (intrinsic == NI_Vector256_AsInt32) || (intrinsic == NI_Vector256_AsInt64) || (intrinsic == NI_Vector256_AsSByte) || (intrinsic == NI_Vector256_AsSingle) || (intrinsic == NI_Vector256_AsUInt16) || (intrinsic == NI_Vector256_AsUInt32) || (intrinsic == NI_Vector256_AsUInt64) || (intrinsic == NI_Vector256_get_AllBitsSet) || (intrinsic == NI_Vector256_get_Count) || (intrinsic == NI_Vector256_get_Zero) || (intrinsic == NI_Vector256_GetElement) || (intrinsic == NI_Vector256_WithElement) || (intrinsic == NI_Vector256_GetLower) || (intrinsic == NI_Vector256_ToScalar)); #endif // TARGET_XARCH #ifdef TARGET_ARM64 assert((intrinsic == NI_Vector64_As) || (intrinsic == NI_Vector64_AsByte) || (intrinsic == NI_Vector64_AsDouble) || (intrinsic == NI_Vector64_AsInt16) || (intrinsic == NI_Vector64_AsInt32) || (intrinsic == NI_Vector64_AsInt64) || (intrinsic == NI_Vector64_AsSByte) || (intrinsic == NI_Vector64_AsSingle) || (intrinsic == NI_Vector64_AsUInt16) || (intrinsic == NI_Vector64_AsUInt32) || (intrinsic == NI_Vector64_AsUInt64) || (intrinsic == NI_Vector64_get_AllBitsSet) || (intrinsic == NI_Vector64_get_Count) || (intrinsic == NI_Vector64_get_Zero) || (intrinsic == NI_Vector64_GetElement) || (intrinsic == NI_Vector64_ToScalar) || (intrinsic == NI_Vector64_ToVector128) || (intrinsic == NI_Vector64_ToVector128Unsafe) || (intrinsic == NI_Vector64_WithElement) || (intrinsic == NI_Vector128_As) || (intrinsic == NI_Vector128_AsByte) || (intrinsic == NI_Vector128_AsDouble) || (intrinsic == NI_Vector128_AsInt16) || (intrinsic == NI_Vector128_AsInt32) || (intrinsic == NI_Vector128_AsInt64) || (intrinsic == NI_Vector128_AsSByte) || (intrinsic == NI_Vector128_AsSingle) || (intrinsic == NI_Vector128_AsUInt16) || (intrinsic == NI_Vector128_AsUInt32) || (intrinsic == NI_Vector128_AsUInt64) || (intrinsic == NI_Vector128_get_AllBitsSet) || (intrinsic == NI_Vector128_get_Count) || (intrinsic == NI_Vector128_get_Zero) || (intrinsic == NI_Vector128_GetElement) || (intrinsic == NI_Vector128_GetLower) || (intrinsic == NI_Vector128_GetUpper) || (intrinsic == NI_Vector128_ToScalar) || (intrinsic == NI_Vector128_WithElement)); #endif // TARGET_ARM64 return false; } // HWIntrinsicSignatureReader: a helper class that "reads" a list of hardware intrinsic arguments and stores // the corresponding argument type descriptors as the fields of the class instance. // struct HWIntrinsicSignatureReader final { // Read: enumerates the list of arguments of a hardware intrinsic and stores the CORINFO_CLASS_HANDLE // and var_types values of each operand into the corresponding fields of the class instance. // // Arguments: // compHnd -- an instance of COMP_HANDLE class. // sig -- a hardware intrinsic signature. // void Read(COMP_HANDLE compHnd, CORINFO_SIG_INFO* sig) { CORINFO_ARG_LIST_HANDLE args = sig->args; if (sig->numArgs > 0) { op1JitType = strip(compHnd->getArgType(sig, args, &op1ClsHnd)); if (sig->numArgs > 1) { args = compHnd->getArgNext(args); op2JitType = strip(compHnd->getArgType(sig, args, &op2ClsHnd)); } if (sig->numArgs > 2) { args = compHnd->getArgNext(args); op3JitType = strip(compHnd->getArgType(sig, args, &op3ClsHnd)); } if (sig->numArgs > 3) { args = compHnd->getArgNext(args); op4JitType = strip(compHnd->getArgType(sig, args, &op4ClsHnd)); } } } CORINFO_CLASS_HANDLE op1ClsHnd; CORINFO_CLASS_HANDLE op2ClsHnd; CORINFO_CLASS_HANDLE op3ClsHnd; CORINFO_CLASS_HANDLE op4ClsHnd; CorInfoType op1JitType; CorInfoType op2JitType; CorInfoType op3JitType; CorInfoType op4JitType; var_types GetOp1Type() const { return JITtype2varType(op1JitType); } var_types GetOp2Type() const { return JITtype2varType(op2JitType); } var_types GetOp3Type() const { return JITtype2varType(op3JitType); } var_types GetOp4Type() const { return JITtype2varType(op4JitType); } }; //------------------------------------------------------------------------ // impHWIntrinsic: Import a hardware intrinsic as a GT_HWINTRINSIC node if possible // // Arguments: // intrinsic -- id of the intrinsic function. // clsHnd -- class handle containing the intrinsic function. // method -- method handle of the intrinsic function. // sig -- signature of the intrinsic call // mustExpand -- true if the intrinsic must return a GenTree*; otherwise, false // Return Value: // The GT_HWINTRINSIC node, or nullptr if not a supported intrinsic // GenTree* Compiler::impHWIntrinsic(NamedIntrinsic intrinsic, CORINFO_CLASS_HANDLE clsHnd, CORINFO_METHOD_HANDLE method, CORINFO_SIG_INFO* sig, bool mustExpand) { HWIntrinsicCategory category = HWIntrinsicInfo::lookupCategory(intrinsic); CORINFO_InstructionSet isa = HWIntrinsicInfo::lookupIsa(intrinsic); int numArgs = sig->numArgs; var_types retType = JITtype2varType(sig->retType); CorInfoType simdBaseJitType = CORINFO_TYPE_UNDEF; if ((retType == TYP_STRUCT) && featureSIMD) { unsigned int sizeBytes; simdBaseJitType = getBaseJitTypeAndSizeOfSIMDType(sig->retTypeSigClass, &sizeBytes); if (HWIntrinsicInfo::IsMultiReg(intrinsic)) { assert(sizeBytes == 0); } else { assert(sizeBytes != 0); // We want to return early here for cases where retType was TYP_STRUCT as per method signature and // rather than deferring the decision after getting the simdBaseJitType of arg. if (!isSupportedBaseType(intrinsic, simdBaseJitType)) { return nullptr; } retType = getSIMDTypeForSize(sizeBytes); } } simdBaseJitType = getBaseJitTypeFromArgIfNeeded(intrinsic, clsHnd, sig, simdBaseJitType); if (simdBaseJitType == CORINFO_TYPE_UNDEF) { if ((category == HW_Category_Scalar) || HWIntrinsicInfo::isScalarIsa(isa)) { simdBaseJitType = sig->retType; if (simdBaseJitType == CORINFO_TYPE_VOID) { simdBaseJitType = CORINFO_TYPE_UNDEF; } } else { assert(featureSIMD); unsigned int sizeBytes; simdBaseJitType = getBaseJitTypeAndSizeOfSIMDType(clsHnd, &sizeBytes); assert((category == HW_Category_Special) || (category == HW_Category_Helper) || (sizeBytes != 0)); } } // Immediately return if the category is other than scalar/special and this is not a supported base type. if ((category != HW_Category_Special) && (category != HW_Category_Scalar) && !HWIntrinsicInfo::isScalarIsa(isa) && !isSupportedBaseType(intrinsic, simdBaseJitType)) { return nullptr; } var_types simdBaseType = TYP_UNKNOWN; GenTree* immOp = nullptr; if (simdBaseJitType != CORINFO_TYPE_UNDEF) { simdBaseType = JitType2PreciseVarType(simdBaseJitType); } HWIntrinsicSignatureReader sigReader; sigReader.Read(info.compCompHnd, sig); #ifdef TARGET_ARM64 if ((intrinsic == NI_AdvSimd_Insert) || (intrinsic == NI_AdvSimd_InsertScalar) || (intrinsic == NI_AdvSimd_LoadAndInsertScalar)) { assert(sig->numArgs == 3); immOp = impStackTop(1).val; assert(HWIntrinsicInfo::isImmOp(intrinsic, immOp)); } else if (intrinsic == NI_AdvSimd_Arm64_InsertSelectedScalar) { // InsertSelectedScalar intrinsic has two immediate operands. // Since all the remaining intrinsics on both platforms have only one immediate // operand, in order to not complicate the shared logic even further we ensure here that // 1) The second immediate operand immOp2 is constant and // 2) its value belongs to [0, sizeof(op3) / sizeof(op3.BaseType)). // If either is false, we should fallback to the managed implementation Insert(dst, dstIdx, Extract(src, // srcIdx)). // The check for the first immediate operand immOp will use the same logic as other intrinsics that have an // immediate operand. GenTree* immOp2 = nullptr; assert(sig->numArgs == 4); immOp = impStackTop(2).val; immOp2 = impStackTop().val; assert(HWIntrinsicInfo::isImmOp(intrinsic, immOp)); assert(HWIntrinsicInfo::isImmOp(intrinsic, immOp2)); if (!immOp2->IsCnsIntOrI()) { assert(HWIntrinsicInfo::NoJmpTableImm(intrinsic)); return impNonConstFallback(intrinsic, retType, simdBaseJitType); } unsigned int otherSimdSize = 0; CorInfoType otherBaseJitType = getBaseJitTypeAndSizeOfSIMDType(sigReader.op3ClsHnd, &otherSimdSize); var_types otherBaseType = JitType2PreciseVarType(otherBaseJitType); assert(otherBaseJitType == simdBaseJitType); int immLowerBound2 = 0; int immUpperBound2 = 0; HWIntrinsicInfo::lookupImmBounds(intrinsic, otherSimdSize, otherBaseType, &immLowerBound2, &immUpperBound2); const int immVal2 = (int)immOp2->AsIntCon()->IconValue(); if ((immVal2 < immLowerBound2) || (immVal2 > immUpperBound2)) { assert(!mustExpand); return nullptr; } } else #endif if ((sig->numArgs > 0) && HWIntrinsicInfo::isImmOp(intrinsic, impStackTop().val)) { // NOTE: The following code assumes that for all intrinsics // taking an immediate operand, that operand will be last. immOp = impStackTop().val; } const unsigned simdSize = HWIntrinsicInfo::lookupSimdSize(this, intrinsic, sig); int immLowerBound = 0; int immUpperBound = 0; bool hasFullRangeImm = false; if (immOp != nullptr) { #ifdef TARGET_XARCH immUpperBound = HWIntrinsicInfo::lookupImmUpperBound(intrinsic); hasFullRangeImm = HWIntrinsicInfo::HasFullRangeImm(intrinsic); #elif defined(TARGET_ARM64) if (category == HW_Category_SIMDByIndexedElement) { CorInfoType indexedElementBaseJitType; var_types indexedElementBaseType; unsigned int indexedElementSimdSize = 0; if (numArgs == 3) { indexedElementBaseJitType = getBaseJitTypeAndSizeOfSIMDType(sigReader.op2ClsHnd, &indexedElementSimdSize); indexedElementBaseType = JitType2PreciseVarType(indexedElementBaseJitType); } else { assert(numArgs == 4); indexedElementBaseJitType = getBaseJitTypeAndSizeOfSIMDType(sigReader.op3ClsHnd, &indexedElementSimdSize); indexedElementBaseType = JitType2PreciseVarType(indexedElementBaseJitType); if (intrinsic == NI_Dp_DotProductBySelectedQuadruplet) { assert(((simdBaseType == TYP_INT) && (indexedElementBaseType == TYP_BYTE)) || ((simdBaseType == TYP_UINT) && (indexedElementBaseType == TYP_UBYTE))); // The second source operand of sdot, udot instructions is an indexed 32-bit element. indexedElementBaseJitType = simdBaseJitType; indexedElementBaseType = simdBaseType; } } assert(indexedElementBaseType == simdBaseType); HWIntrinsicInfo::lookupImmBounds(intrinsic, indexedElementSimdSize, simdBaseType, &immLowerBound, &immUpperBound); } else { HWIntrinsicInfo::lookupImmBounds(intrinsic, simdSize, simdBaseType, &immLowerBound, &immUpperBound); } #endif if (!hasFullRangeImm && immOp->IsCnsIntOrI()) { const int ival = (int)immOp->AsIntCon()->IconValue(); bool immOutOfRange; #ifdef TARGET_XARCH if (HWIntrinsicInfo::isAVX2GatherIntrinsic(intrinsic)) { immOutOfRange = (ival != 1) && (ival != 2) && (ival != 4) && (ival != 8); } else #endif { immOutOfRange = (ival < immLowerBound) || (ival > immUpperBound); } if (immOutOfRange) { assert(!mustExpand); // The imm-HWintrinsics that do not accept all imm8 values may throw // ArgumentOutOfRangeException when the imm argument is not in the valid range return nullptr; } } else if (!immOp->IsCnsIntOrI()) { if (HWIntrinsicInfo::NoJmpTableImm(intrinsic)) { return impNonConstFallback(intrinsic, retType, simdBaseJitType); } else if (!mustExpand) { // When the imm-argument is not a constant and we are not being forced to expand, we need to // return nullptr so a GT_CALL to the intrinsic method is emitted instead. The // intrinsic method is recursive and will be forced to expand, at which point // we emit some less efficient fallback code. return nullptr; } } } if (HWIntrinsicInfo::IsFloatingPointUsed(intrinsic)) { // Set `compFloatingPointUsed` to cover the scenario where an intrinsic is operating on SIMD fields, but // where no SIMD local vars are in use. This is the same logic as is used for FEATURE_SIMD. compFloatingPointUsed = true; } // table-driven importer of simple intrinsics if (impIsTableDrivenHWIntrinsic(intrinsic, category)) { const bool isScalar = (category == HW_Category_Scalar); assert(numArgs >= 0); if (!isScalar && ((HWIntrinsicInfo::lookupIns(intrinsic, simdBaseType) == INS_invalid) || ((simdSize != 8) && (simdSize != 16) && (simdSize != 32)))) { assert(!"Unexpected HW Intrinsic"); return nullptr; } GenTree* op1 = nullptr; GenTree* op2 = nullptr; GenTree* op3 = nullptr; GenTree* op4 = nullptr; GenTreeHWIntrinsic* retNode = nullptr; switch (numArgs) { case 0: assert(!isScalar); retNode = gtNewSimdHWIntrinsicNode(retType, intrinsic, simdBaseJitType, simdSize); break; case 1: op1 = getArgForHWIntrinsic(sigReader.GetOp1Type(), sigReader.op1ClsHnd); if ((category == HW_Category_MemoryLoad) && op1->OperIs(GT_CAST)) { // Although the API specifies a pointer, if what we have is a BYREF, that's what // we really want, so throw away the cast. if (op1->gtGetOp1()->TypeGet() == TYP_BYREF) { op1 = op1->gtGetOp1(); } } retNode = isScalar ? gtNewScalarHWIntrinsicNode(retType, op1, intrinsic) : gtNewSimdHWIntrinsicNode(retType, op1, intrinsic, simdBaseJitType, simdSize); #if defined(TARGET_XARCH) switch (intrinsic) { case NI_SSE41_ConvertToVector128Int16: case NI_SSE41_ConvertToVector128Int32: case NI_SSE41_ConvertToVector128Int64: case NI_AVX2_BroadcastScalarToVector128: case NI_AVX2_BroadcastScalarToVector256: case NI_AVX2_ConvertToVector256Int16: case NI_AVX2_ConvertToVector256Int32: case NI_AVX2_ConvertToVector256Int64: { // These intrinsics have both pointer and vector overloads // We want to be able to differentiate between them so lets // just track the aux type as a ptr or undefined, depending CorInfoType auxiliaryType = CORINFO_TYPE_UNDEF; if (!varTypeIsSIMD(op1->TypeGet())) { auxiliaryType = CORINFO_TYPE_PTR; } retNode->AsHWIntrinsic()->SetAuxiliaryJitType(auxiliaryType); break; } default: { break; } } #endif // TARGET_XARCH break; case 2: op2 = getArgForHWIntrinsic(sigReader.GetOp2Type(), sigReader.op2ClsHnd); op2 = addRangeCheckIfNeeded(intrinsic, op2, mustExpand, immLowerBound, immUpperBound); op1 = getArgForHWIntrinsic(sigReader.GetOp1Type(), sigReader.op1ClsHnd); retNode = isScalar ? gtNewScalarHWIntrinsicNode(retType, op1, op2, intrinsic) : gtNewSimdHWIntrinsicNode(retType, op1, op2, intrinsic, simdBaseJitType, simdSize); #ifdef TARGET_XARCH if ((intrinsic == NI_SSE42_Crc32) || (intrinsic == NI_SSE42_X64_Crc32)) { // TODO-XArch-Cleanup: currently we use the simdBaseJitType to bring the type of the second argument // to the code generator. May encode the overload info in other way. retNode->AsHWIntrinsic()->SetSimdBaseJitType(sigReader.op2JitType); } #elif defined(TARGET_ARM64) switch (intrinsic) { case NI_Crc32_ComputeCrc32: case NI_Crc32_ComputeCrc32C: case NI_Crc32_Arm64_ComputeCrc32: case NI_Crc32_Arm64_ComputeCrc32C: retNode->AsHWIntrinsic()->SetSimdBaseJitType(sigReader.op2JitType); break; case NI_AdvSimd_AddWideningUpper: case NI_AdvSimd_SubtractWideningUpper: assert(varTypeIsSIMD(op1->TypeGet())); retNode->AsHWIntrinsic()->SetAuxiliaryJitType(getBaseJitTypeOfSIMDType(sigReader.op1ClsHnd)); break; case NI_AdvSimd_Arm64_AddSaturateScalar: assert(varTypeIsSIMD(op2->TypeGet())); retNode->AsHWIntrinsic()->SetAuxiliaryJitType(getBaseJitTypeOfSIMDType(sigReader.op2ClsHnd)); break; case NI_ArmBase_Arm64_MultiplyHigh: if (sig->retType == CORINFO_TYPE_ULONG) { retNode->AsHWIntrinsic()->SetSimdBaseJitType(CORINFO_TYPE_ULONG); } else { assert(sig->retType == CORINFO_TYPE_LONG); retNode->AsHWIntrinsic()->SetSimdBaseJitType(CORINFO_TYPE_LONG); } break; default: break; } #endif break; case 3: op3 = getArgForHWIntrinsic(sigReader.GetOp3Type(), sigReader.op3ClsHnd); op2 = getArgForHWIntrinsic(sigReader.GetOp2Type(), sigReader.op2ClsHnd); op1 = getArgForHWIntrinsic(sigReader.GetOp1Type(), sigReader.op1ClsHnd); #ifdef TARGET_ARM64 if (intrinsic == NI_AdvSimd_LoadAndInsertScalar) { op2 = addRangeCheckIfNeeded(intrinsic, op2, mustExpand, immLowerBound, immUpperBound); if (op1->OperIs(GT_CAST)) { // Although the API specifies a pointer, if what we have is a BYREF, that's what // we really want, so throw away the cast. if (op1->gtGetOp1()->TypeGet() == TYP_BYREF) { op1 = op1->gtGetOp1(); } } } else if ((intrinsic == NI_AdvSimd_Insert) || (intrinsic == NI_AdvSimd_InsertScalar)) { op2 = addRangeCheckIfNeeded(intrinsic, op2, mustExpand, immLowerBound, immUpperBound); } else #endif { op3 = addRangeCheckIfNeeded(intrinsic, op3, mustExpand, immLowerBound, immUpperBound); } retNode = isScalar ? gtNewScalarHWIntrinsicNode(retType, op1, op2, op3, intrinsic) : gtNewSimdHWIntrinsicNode(retType, op1, op2, op3, intrinsic, simdBaseJitType, simdSize); #ifdef TARGET_XARCH if ((intrinsic == NI_AVX2_GatherVector128) || (intrinsic == NI_AVX2_GatherVector256)) { assert(varTypeIsSIMD(op2->TypeGet())); retNode->AsHWIntrinsic()->SetAuxiliaryJitType(getBaseJitTypeOfSIMDType(sigReader.op2ClsHnd)); } #endif break; #ifdef TARGET_ARM64 case 4: op4 = getArgForHWIntrinsic(sigReader.GetOp4Type(), sigReader.op4ClsHnd); op4 = addRangeCheckIfNeeded(intrinsic, op4, mustExpand, immLowerBound, immUpperBound); op3 = getArgForHWIntrinsic(sigReader.GetOp3Type(), sigReader.op3ClsHnd); op2 = getArgForHWIntrinsic(sigReader.GetOp2Type(), sigReader.op2ClsHnd); op1 = getArgForHWIntrinsic(sigReader.GetOp1Type(), sigReader.op1ClsHnd); assert(!isScalar); retNode = gtNewSimdHWIntrinsicNode(retType, op1, op2, op3, op4, intrinsic, simdBaseJitType, simdSize); break; #endif default: return nullptr; } const bool isMemoryStore = retNode->OperIsMemoryStore(); if (isMemoryStore || retNode->OperIsMemoryLoad()) { if (isMemoryStore) { // A MemoryStore operation is an assignment retNode->gtFlags |= GTF_ASG; } // This operation contains an implicit indirection // it could point into the global heap or // it could throw a null reference exception. // retNode->gtFlags |= (GTF_GLOB_REF | GTF_EXCEPT); } return retNode; } return impSpecialIntrinsic(intrinsic, clsHnd, method, sig, simdBaseJitType, retType, simdSize); } #endif // FEATURE_HW_INTRINSICS
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/coreclr/pal/src/libunwind/include/win/unistd.h
// This is an incomplete & imprecice implementation of the Posix // standard file by the same name // Since this is only intended for VC++ compilers // use #pragma once instead of guard macros #pragma once #ifdef _MSC_VER // Only for cross compilation to windows #ifndef UNW_REMOTE_ONLY // This is solely intended to enable compilation of libunwind // for UNW_REMOTE_ONLY on windows #error Cross compilation of libunwind on Windows can only support UNW_REMOTE_ONLY #endif #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <sys/types.h> int close(int); int getpagesize(void); int open(const char *, int, ...); ssize_t read(int fd, void *buf, size_t count); ssize_t write(int, const void *, size_t); #endif // _MSC_VER
// This is an incomplete & imprecice implementation of the Posix // standard file by the same name // Since this is only intended for VC++ compilers // use #pragma once instead of guard macros #pragma once #ifdef _MSC_VER // Only for cross compilation to windows #ifndef UNW_REMOTE_ONLY // This is solely intended to enable compilation of libunwind // for UNW_REMOTE_ONLY on windows #error Cross compilation of libunwind on Windows can only support UNW_REMOTE_ONLY #endif #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <sys/types.h> int close(int); int getpagesize(void); int open(const char *, int, ...); ssize_t read(int fd, void *buf, size_t count); ssize_t write(int, const void *, size_t); #endif // _MSC_VER
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/tests/JIT/HardwareIntrinsics/General/Vector256_1/GetAndWithElement.UInt16.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\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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementUInt163() { var test = new VectorGetAndWithElement__GetAndWithElementUInt163(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt163 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 3, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); UInt16[] values = new UInt16[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt16(); } Vector256<UInt16> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15]); bool succeeded = !expectedOutOfRangeException; try { UInt16 result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt16 insertedValue = TestLibrary.Generator.GetUInt16(); try { Vector256<UInt16> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 3, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); UInt16[] values = new UInt16[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt16(); } Vector256<UInt16> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector256) .GetMethod(nameof(Vector256.GetElement)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((UInt16)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt16 insertedValue = TestLibrary.Generator.GetUInt16(); try { object result2 = typeof(Vector256) .GetMethod(nameof(Vector256.WithElement)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector256<UInt16>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(3 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(3 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(3 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(3 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(UInt16 result, UInt16[] values, [CallerMemberName] string method = "") { if (result != values[3]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.GetElement(3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector256<UInt16> result, UInt16[] values, UInt16 insertedValue, [CallerMemberName] string method = "") { UInt16[] resultElements = new UInt16[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(UInt16[] result, UInt16[] values, UInt16 insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 3) && (result[i] != values[i])) { succeeded = false; break; } } if (result[3] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.WithElement(3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); 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\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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementUInt163() { var test = new VectorGetAndWithElement__GetAndWithElementUInt163(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt163 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 3, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); UInt16[] values = new UInt16[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt16(); } Vector256<UInt16> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15]); bool succeeded = !expectedOutOfRangeException; try { UInt16 result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt16 insertedValue = TestLibrary.Generator.GetUInt16(); try { Vector256<UInt16> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 3, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); UInt16[] values = new UInt16[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt16(); } Vector256<UInt16> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector256) .GetMethod(nameof(Vector256.GetElement)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((UInt16)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt16 insertedValue = TestLibrary.Generator.GetUInt16(); try { object result2 = typeof(Vector256) .GetMethod(nameof(Vector256.WithElement)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector256<UInt16>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(3 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(3 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(3 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(3 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(UInt16 result, UInt16[] values, [CallerMemberName] string method = "") { if (result != values[3]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.GetElement(3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector256<UInt16> result, UInt16[] values, UInt16 insertedValue, [CallerMemberName] string method = "") { UInt16[] resultElements = new UInt16[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(UInt16[] result, UInt16[] values, UInt16 insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 3) && (result[i] != values[i])) { succeeded = false; break; } } if (result[3] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.WithElement(3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessInfo.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.Diagnostics { /// <summary> /// This data structure contains information about a process that is collected /// in bulk by querying the operating system. The reason to make this a separate /// structure from the process component is so that we can throw it away all at once /// when Refresh is called on the component. /// </summary> internal sealed class ProcessInfo { internal readonly List<ThreadInfo> _threadInfoList; internal int BasePriority { get; set; } internal string ProcessName { get; set; } = string.Empty; internal int ProcessId { get; set; } internal long PoolPagedBytes { get; set; } internal long PoolNonPagedBytes { get; set; } internal long VirtualBytes { get; set; } internal long VirtualBytesPeak { get; set; } internal long WorkingSetPeak { get; set; } internal long WorkingSet { get; set; } internal long PageFileBytesPeak { get; set; } internal long PageFileBytes { get; set; } internal long PrivateBytes { get; set; } internal int SessionId { get; set; } internal int HandleCount { get; set; } internal ProcessInfo() { _threadInfoList = new List<ThreadInfo>(); } internal ProcessInfo(int threadsNumber) { _threadInfoList = new List<ThreadInfo>(threadsNumber); } } }
// 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.Diagnostics { /// <summary> /// This data structure contains information about a process that is collected /// in bulk by querying the operating system. The reason to make this a separate /// structure from the process component is so that we can throw it away all at once /// when Refresh is called on the component. /// </summary> internal sealed class ProcessInfo { internal readonly List<ThreadInfo> _threadInfoList; internal int BasePriority { get; set; } internal string ProcessName { get; set; } = string.Empty; internal int ProcessId { get; set; } internal long PoolPagedBytes { get; set; } internal long PoolNonPagedBytes { get; set; } internal long VirtualBytes { get; set; } internal long VirtualBytesPeak { get; set; } internal long WorkingSetPeak { get; set; } internal long WorkingSet { get; set; } internal long PageFileBytesPeak { get; set; } internal long PageFileBytes { get; set; } internal long PrivateBytes { get; set; } internal int SessionId { get; set; } internal int HandleCount { get; set; } internal ProcessInfo() { _threadInfoList = new List<ThreadInfo>(); } internal ProcessInfo(int threadsNumber) { _threadInfoList = new List<ThreadInfo>(threadsNumber); } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./docs/design/coreclr/jit/images/ryujit-initial-phases.png
PNG  IHDR&N2sRGBgAMA a pHYsod/IDATx^kpוJ[Tm%ؿM~ǯ$IB@M\Te#Q$ѕX2- $ mm(Q E@Q$"/>'xs}3T}u>qH2,7 e&cr`{(>݌s+/0nF1)G7f$8]ž.yk6!dE(x >v>݌6eNAm?Vn~Xwԓ0@G]7)G7f5BÜa ϰxyly97<~OYm<dHڛtIH_yAP77Mnɮ%b[ḙ) :EohmZ7Օ߱0f1)GG1ff5}AlέD./} ԧԧQKra3)u{^ymdY(x >v>݌gB.^Av3 O9O%d74H]Lg9YO%d7|UY 7f,-˫'8V>݌\-tm(/E)xy(+vrc7qԧاT@W;p7rzfAlN)״J ]KoQ3k7(뙛 ٵDLsSoiaWaV#|ll>aܕ)SJnFan>Ѽ٧ٝO8k>݌uC;.c@w%js 6#jTԧQ>im|Mg9 nS (4Hjb3i[4% 8W^ƌ [4un^})1Ui̸E#}Bvg?O;!# ҜR78=lt[R \-~/q p^7--din}OAb_,7XM vsj)UoF4*Kk _+ L>}e9D8~)G+Mqw0/R<vORs{f :~:4f_=+y$A-QT[kj\IwV?I"Z[Y:]` Iq˃8=?5#iV*M ^ToW?Jzj3.ZmnNOx:[ mNYVQpKK^ƌ [46uGϲr"*@lfĪN=s(80LBԫTӘqAsFέeDxq"wILʼnM$1'r74^ݐX-qW*Ƌ[4uneK:uYb/Nhnhֹ=2qRϤM -:bzR/NSy̸E޹[j>qׂ7f,G9IdIQϤM -MLIQ~Evx$7>iB3D\9 ꙴi8i޹E296/z^/ᕅA{Y]9$0i׎m34^aƋdv-,d+Sʲlya'KzHavEIo5$w"ĉ43S7dbW' Jf7M[Mը6'̭'|sfOo\Z$nXd^wOP|wd;Gzf z&Q60x~{(¡mp!n}jOvy|IKڈ[63NxҏzAHjn%?GS><sUA9Vkl's#?#u2 UfI-^S|_z^\$B:GP6sNWͪ#!.+Wԙ|0y7%QE=gl>XKU ˖ZEۦ\ A;F1'a?l]LIs;cK'y=5u>^5: ]>{ʰ-nczW7pD&'⤞4^$1qc5]V-`$xbn|z_  RU^ף`<Y⤂B4^aƋvb N$w/*_0WaCoX^zVVW%A=6'47[WAG F8YxڀyjGI$1='L4^ܢCLeF<T'yݯe"$OB'}qSBc-imz`I$ >7L4^ܢѬs++I} 54h4 kzV8.` -4hBsk`_ιs<kbG E [4[$ɚ 8_V[4!E[4!Y썯d44@z-hH•mxKVHH hޢzsW _^?+rߜwPWݎ2IKo'vrfIHM hޢzCw㛉.>W& 1 1{@.X߈y5.LD8sFE{&!e[Ӈg.ڃ#slu .}H•(a>Y [4AoܙNp NBVE0ʲQ/nU^Zxk 68S7/U@7|\:>dWol|_WMU変fUHoѤ<鹞OAX|MAj _2zՙij ∸s6_;cz5z:| SApͪޢI53Qļ7ߕ;!{rE`ʡ3~冏b-YTھLEÆ45_Yo c>Y.8Մ< >|. eA|\߆G{ -H9=cs9l)ێSu<{`qWmja߱l(_!-Rb6|ve;*9ОE^ާl`foWV>zc6h$ Tl:XHkuϋWf<.ϯe웇A=:r{?=^WUzlmӿ8Zz|G'Q^~) tm\_E]F!kzz˜S< ڙn?A[amE{k2gop{rMv Q~.ײ`^la0-~u_p{pǯjfE5 ˬ{BCl)»WW~*Bܓ<6$+Pe oVQʣ< Boo(L}NuB^e7Zq؞D?A;'h5b5ծVhoš<27mM Kڨw.ֲ|HM}wz ~w:?pt&dc'kzx$?6'HD#E]%-"nm2Kzÿ&(y_ԊU\z{]vBw;`W'6eJje-fM_У=L0EgR,~<grNHuzYZTou -[Kqڝ6(u7v6' ]÷lW漯l[4MwJpaSw%!s2ʾafIHM hގc ס_C02AʋK𤥷H• *a>Y [4^o3?a[q[9Vfۋuϊ<ƀr}_HKo'kHo E# zx߂w v^Y]{hǐ_p2/ݲi-dM4R|-h_^c3"Pv_et<,@z-hH҈Q%#%E[4!E IVd>'{|$cC"hBz&hBz(_[gS~SyHVYg-ޢ ͢4"ȽHԩS,Ɋޢ -,PįdtIMz +hBz(J7`Yd.egbSPzK6) ޢAzFZz$o3ٔaNY@-0,@z-i-3&dфMHoDžcS]_}צ(r ][:˙d쑔y^[z'y^-=,Cgr9.ʎt@#iC>uWWIP^g4I3-^HoD<8yoNǙ7VaQ;" v:O 6T$qY'8`I^?QKW) u:lhQ 6jt&{`x#]g}sr -zD "I 8X6iQx/.)S.CT3 K#zzI:6:^&$=Ew@13HΤ Mz -h; oN<2ҙv9\!Eg+t]<P]98aˤ3;,8lEt&é:Ӝ[Z'iNY'~P~bn/ﲞær?/MŹ2jSS+E^T_S]l6RT6L=;;|&Pܱz nf[z'y^N#;m gR&~31!{NyA>63%([y׬1t&NЁQy(IP.P=f['7-Ԣ7t&j 8- ?y.s}8NWnoqcP.*sTs'[4l-fg2 Ge^0ZAi(}}@'t&J~mc9:;͢tNn[XEoN+Ζa[8 (si`w a8/x>'{>`h+}=G䞁p.>|q_EaΑޯMOf3™BAg$Z. tT(n*\7JoI;GaShd9#v#`[/=@G[mЙgoE$}Sc οr+66TQįeVSgUj˯u2sfBw&(A}Jz mxg8ꍗ[rzTxlB-I#EHzY˿zX m6,~hd3k :۸\K\/!獡˂d: Jt>|-%l-hrgŕTJepô5߫el`~?A 聶9f~Cl`im,u&)C-#У8NUWz/Rc^R: JoN6jfh=u'hGٶI!zݰ` ےN,?Sye\'zu"\0T=n\('t\!5[lħ6P~>J\Sl׼j8;e<VOXނ(= ˤTyzRynЗ˰dQoh/J'- ԕؙn?U,ȢK`ohcsMW\J6]+'8Hc^,oPާRqżX͛p"v8mZyJe=$uڪ8Pʶȇ[70Bԓ*/W:U:y]aeqM FPPWbglR gFdNo&);A|޹\J67u)(H'VPD"v-pem`݅yH?l+B+b mωv/ Ѧ⦅Lq\8Qzë^&_[y]y]aQzKQoN0]7ޓu~;'huE,V8ȢC.|N ]szosѿVoxP5gފ"EeV/Éj*O?ՙNQ;4>|fWoQzK}kY[w^낈\8JKb"󀺵!t@Tݿ)F ʙX"39:.ʒDD2Î[oQzK䶬8m2Kz;N>t6~kex<L|'Cy>h o*J'aC=".n#@)cPal?xlekr&фMS&<p[9Z'LL7+Xk<6Z {FW(r"z.ʁPuzdڏ.=*UP3ɉ:Ū,zK&zǺKcሺl ǽ6Nl ׷ cc6zSh՛ k(%.y%z.gQeǢ:%|EiwrdEob/~L ϝ*ǯ4g"vJKy@Y-4+%MX#%C=F*{7a&9ݙ%͢tNn[X71cyT"tM^ P PTI<e/3ŔaNY@-0,*zd(, 1=8 }L]?DQ|Xw菏+UI>I/Ljt;jtHoȂڹ3L^d]y=]ʣ3G!@۱mb,`[f UcxUHKosP6vY$Mg zK&[4 QpzxRpGG1bYv@oB<m+Ag &=u&[:'7-ޢIXu7)ܑ`ُA'uV8p&gٻd{WWEșDhޢAzh,R%LjYc:MgzK&[4i8]}1HKoI4;ޢ -,JQdŃ);Nn[4HoHKoI4!#&hBz&7??įeݙ4ެܤHBz&7˲6??Y_'ǚ={_e]o<kBz&hBzkqyvd_ݴ!aƫ{6f㊨N!{K7&doMYPj~]cn~u̩s?_; [4 a7&doMZެ߰Q-oJ|r-]{" [6!{#ljfMȰӅ& 6!{#lBIBR4a7BXfe4[8n4 {#lBFؤ͚a &Mq6!{#lBF؄gطAلUζp`b,A{k)m,doMޢ3e1ca͚ 2aGZ801H6H7&do=g ZY5a`#]q`18H<*cuYnxݺLn6el[; K/?ckfoքt 9n&doM@.! x_`1mJr6|u:.eJ#}H`LǑZX}GDp$x:0n & 2;݆J&doЪ- e`2qB;紳Z٭lItjPr{E&z@Uy~Gů+/1`SЗ_w}\:(Qe}\~RWCd{o߭go3wOiMZ60!{Kudo@F؄MZgQ^l/]/cukB7<OU` |10KI L6}E$c$$~F6;{N[k9nN {I~+Ac]6y 4>do[nn nB\ږ wKꊿr  Å=L^QMis1WsOAT_f<}`{ L0%;^@f7\6'aIѨ^1X [IDg_<`+7.A8쁋=s}8ވ:e" vPɛ@c&v`g ~  _\XT A;Jp*@1+T0Wզdor}BVw .otI w0s'`ЦsS]>;.b_HT=> TU蛃d\}8ވX[ 75t`wMP<aa/nc\Lꂿ\P1`/=A[2C)7;UߟVҥU7[:pzvA:^07^a=^c^\ P>BPmgXYAlO~.4n|Ζ<=fy^'談r9썰 & ϰa!2{fg y`W}vIpߕWm.(GZqA$ [x&z!ZpQ2r T?g0`W獫;e5̐ Lxwdp2 7&`oD}osĺMGpe(a/߀%& @S+:̙ akϘϘ'J ! m+m Lު @ M`A{˲G1V nkxaW^fO[i} ?S]򐽅ǿT[Z7$4AT2ax_-߸f7S<گgCX<mKZd}? {+ю`ӬlPI9l 0~ެPi;/m셃~skfCl  ~c]4NL2'_<ΎydIު3/iv]EXkE兴QMl7\pu . v(6eKAI&ymkǮ`?AZf6ׇaloώl ;ޱ ƫ~| /b3<`p2cmYc<!4 ) ~ +z{_u^}qb;/0ߟ7ұDx}f}Ň/@9ar;_ݲ?ުGa[f[A?[l62/봼%U\ٌŊd[O!mK. 8<8X0h{6"ְAU`ZjRW `YnE/">s﷩` .˼08ɭ`[Y^8}|㔴}#OE`h>yz9y?a375T#ꆇ[5PSZ̟/k4lEیL)U]Lu[O7&do #}/;a- Lk\5_Z&m[4D"P F_a}0b1/wDz`Bʯ*~ӷ{N im #eQ=fd޴_k|Ǫ ;˷r[5&>kg}럎-B޲6m>oezVfm=I%\o kLǷU"F Lk\5_Z>Y7ZSM *PD||乃%SgV++UWOl\+) :xZ}+7ʋmc6ӟ|?J ,Y8U^?S0Ǐy%U?k@`fjX'K$[@ɿ!`X_䅣v6m6!{pޯ?ڏFHLo*tEJ#FLՅ>xчo]RQ~zL>@gGK>ty]:\S]pC6[email protected]\{k U]45:IOg _~'ƺP,]Y6'a$ /W 5 `{Sy6 /sXcP1֩Pa jT.F=aLT]T^!{Kudoi@`Tyvf>c6;kӻ׋Dl_ds~jS]\6<J^I*H0&X_OL ꧗9GL*S10y ,UN?v`l!OD%hoҁ-~Ng ;6rCm^h&>1Gfgnq R0Pm>euº1ֳ>q* 7&I[Bm[R<^. zA*uFt(z~l@1p,ަ>U7˜8=( ڇ.dor}B3`w8}vwAcm0h8 /2 *q y8vqAF$){+PA􋻬Iuþ &rn`KZqA$ [,}.-9Z ԗE|mLт \Tldo2֫~2k̡'th${ %){Ѱwqq"lҺ [&{Kf7xxMC;FW0;+Ba3&!01ԅaju)jfM|8a-A$KZqA$ ayU0yX _b]y':C\^ _Etmx`^slz: q!`چTeDžmF^oOlkr;:i5{&ʰ}GM/d`BA{kMdoMEtLuc m}ef61b,0&-h|Pi͚B.6!M؄썰 [LxzT 2(3AŤbvǣgEj$$E>KXu4h]MdoMi(ʵ>6m@U?=o; !X@P`x6~UZ60!{Kudo@F؄(Wb\3& nivnĤ"YJۤ"Y6i5{&~~"0xN[k9nN {#lBFؤ͚a &Mq6!{#lBF؄D>:BZqa7&eoV1ǝ $ ʏi O`8VA{345doMY?o{˙3gHZE|doD␽6!{#lR"!XrIIENDB`
PNG  IHDR&N2sRGBgAMA a pHYsod/IDATx^kpוJ[Tm%ؿM~ǯ$IB@M\Te#Q$ѕX2- $ mm(Q E@Q$"/>'xs}3T}u>qH2,7 e&cr`{(>݌s+/0nF1)G7f$8]ž.yk6!dE(x >v>݌6eNAm?Vn~Xwԓ0@G]7)G7f5BÜa ϰxyly97<~OYm<dHڛtIH_yAP77Mnɮ%b[ḙ) :EohmZ7Օ߱0f1)GG1ff5}AlέD./} ԧԧQKra3)u{^ymdY(x >v>݌gB.^Av3 O9O%d74H]Lg9YO%d7|UY 7f,-˫'8V>݌\-tm(/E)xy(+vrc7qԧاT@W;p7rzfAlN)״J ]KoQ3k7(뙛 ٵDLsSoiaWaV#|ll>aܕ)SJnFan>Ѽ٧ٝO8k>݌uC;.c@w%js 6#jTԧQ>im|Mg9 nS (4Hjb3i[4% 8W^ƌ [4un^})1Ui̸E#}Bvg?O;!# ҜR78=lt[R \-~/q p^7--din}OAb_,7XM vsj)UoF4*Kk _+ L>}e9D8~)G+Mqw0/R<vORs{f :~:4f_=+y$A-QT[kj\IwV?I"Z[Y:]` Iq˃8=?5#iV*M ^ToW?Jzj3.ZmnNOx:[ mNYVQpKK^ƌ [46uGϲr"*@lfĪN=s(80LBԫTӘqAsFέeDxq"wILʼnM$1'r74^ݐX-qW*Ƌ[4uneK:uYb/Nhnhֹ=2qRϤM -:bzR/NSy̸E޹[j>qׂ7f,G9IdIQϤM -MLIQ~Evx$7>iB3D\9 ꙴi8i޹E296/z^/ᕅA{Y]9$0i׎m34^aƋdv-,d+Sʲlya'KzHavEIo5$w"ĉ43S7dbW' Jf7M[Mը6'̭'|sfOo\Z$nXd^wOP|wd;Gzf z&Q60x~{(¡mp!n}jOvy|IKڈ[63NxҏzAHjn%?GS><sUA9Vkl's#?#u2 UfI-^S|_z^\$B:GP6sNWͪ#!.+Wԙ|0y7%QE=gl>XKU ˖ZEۦ\ A;F1'a?l]LIs;cK'y=5u>^5: ]>{ʰ-nczW7pD&'⤞4^$1qc5]V-`$xbn|z_  RU^ף`<Y⤂B4^aƋvb N$w/*_0WaCoX^zVVW%A=6'47[WAG F8YxڀyjGI$1='L4^ܢCLeF<T'yݯe"$OB'}qSBc-imz`I$ >7L4^ܢѬs++I} 54h4 kzV8.` -4hBsk`_ιs<kbG E [4[$ɚ 8_V[4!E[4!Y썯d44@z-hH•mxKVHH hޢzsW _^?+rߜwPWݎ2IKo'vrfIHM hޢzCw㛉.>W& 1 1{@.X߈y5.LD8sFE{&!e[Ӈg.ڃ#slu .}H•(a>Y [4AoܙNp NBVE0ʲQ/nU^Zxk 68S7/U@7|\:>dWol|_WMU変fUHoѤ<鹞OAX|MAj _2zՙij ∸s6_;cz5z:| SApͪޢI53Qļ7ߕ;!{rE`ʡ3~冏b-YTھLEÆ45_Yo c>Y.8Մ< >|. eA|\߆G{ -H9=cs9l)ێSu<{`qWmja߱l(_!-Rb6|ve;*9ОE^ާl`foWV>zc6h$ Tl:XHkuϋWf<.ϯe웇A=:r{?=^WUzlmӿ8Zz|G'Q^~) tm\_E]F!kzz˜S< ڙn?A[amE{k2gop{rMv Q~.ײ`^la0-~u_p{pǯjfE5 ˬ{BCl)»WW~*Bܓ<6$+Pe oVQʣ< Boo(L}NuB^e7Zq؞D?A;'h5b5ծVhoš<27mM Kڨw.ֲ|HM}wz ~w:?pt&dc'kzx$?6'HD#E]%-"nm2Kzÿ&(y_ԊU\z{]vBw;`W'6eJje-fM_У=L0EgR,~<grNHuzYZTou -[Kqڝ6(u7v6' ]÷lW漯l[4MwJpaSw%!s2ʾafIHM hގc ס_C02AʋK𤥷H• *a>Y [4^o3?a[q[9Vfۋuϊ<ƀr}_HKo'kHo E# zx߂w v^Y]{hǐ_p2/ݲi-dM4R|-h_^c3"Pv_et<,@z-hH҈Q%#%E[4!E IVd>'{|$cC"hBz&hBz(_[gS~SyHVYg-ޢ ͢4"ȽHԩS,Ɋޢ -,PįdtIMz +hBz(J7`Yd.egbSPzK6) ޢAzFZz$o3ٔaNY@-0,@z-i-3&dфMHoDžcS]_}צ(r ][:˙d쑔y^[z'y^-=,Cgr9.ʎt@#iC>uWWIP^g4I3-^HoD<8yoNǙ7VaQ;" v:O 6T$qY'8`I^?QKW) u:lhQ 6jt&{`x#]g}sr -zD "I 8X6iQx/.)S.CT3 K#zzI:6:^&$=Ew@13HΤ Mz -h; oN<2ҙv9\!Eg+t]<P]98aˤ3;,8lEt&é:Ӝ[Z'iNY'~P~bn/ﲞær?/MŹ2jSS+E^T_S]l6RT6L=;;|&Pܱz nf[z'y^N#;m gR&~31!{NyA>63%([y׬1t&NЁQy(IP.P=f['7-Ԣ7t&j 8- ?y.s}8NWnoqcP.*sTs'[4l-fg2 Ge^0ZAi(}}@'t&J~mc9:;͢tNn[XEoN+Ζa[8 (si`w a8/x>'{>`h+}=G䞁p.>|q_EaΑޯMOf3™BAg$Z. tT(n*\7JoI;GaShd9#v#`[/=@G[mЙgoE$}Sc οr+66TQįeVSgUj˯u2sfBw&(A}Jz mxg8ꍗ[rzTxlB-I#EHzY˿zX m6,~hd3k :۸\K\/!獡˂d: Jt>|-%l-hrgŕTJepô5߫el`~?A 聶9f~Cl`im,u&)C-#У8NUWz/Rc^R: JoN6jfh=u'hGٶI!zݰ` ےN,?Sye\'zu"\0T=n\('t\!5[lħ6P~>J\Sl׼j8;e<VOXނ(= ˤTyzRynЗ˰dQoh/J'- ԕؙn?U,ȢK`ohcsMW\J6]+'8Hc^,oPާRqżX͛p"v8mZyJe=$uڪ8Pʶȇ[70Bԓ*/W:U:y]aeqM FPPWbglR gFdNo&);A|޹\J67u)(H'VPD"v-pem`݅yH?l+B+b mωv/ Ѧ⦅Lq\8Qzë^&_[y]y]aQzKQoN0]7ޓu~;'huE,V8ȢC.|N ]szosѿVoxP5gފ"EeV/Éj*O?ՙNQ;4>|fWoQzK}kY[w^낈\8JKb"󀺵!t@Tݿ)F ʙX"39:.ʒDD2Î[oQzK䶬8m2Kz;N>t6~kex<L|'Cy>h o*J'aC=".n#@)cPal?xlekr&фMS&<p[9Z'LL7+Xk<6Z {FW(r"z.ʁPuzdڏ.=*UP3ɉ:Ū,zK&zǺKcሺl ǽ6Nl ׷ cc6zSh՛ k(%.y%z.gQeǢ:%|EiwrdEob/~L ϝ*ǯ4g"vJKy@Y-4+%MX#%C=F*{7a&9ݙ%͢tNn[X71cyT"tM^ P PTI<e/3ŔaNY@-0,*zd(, 1=8 }L]?DQ|Xw菏+UI>I/Ljt;jtHoȂڹ3L^d]y=]ʣ3G!@۱mb,`[f UcxUHKosP6vY$Mg zK&[4 QpzxRpGG1bYv@oB<m+Ag &=u&[:'7-ޢIXu7)ܑ`ُA'uV8p&gٻd{WWEșDhޢAzh,R%LjYc:MgzK&[4i8]}1HKoI4;ޢ -,JQdŃ);Nn[4HoHKoI4!#&hBz&7??įeݙ4ެܤHBz&7˲6??Y_'ǚ={_e]o<kBz&hBzkqyvd_ݴ!aƫ{6f㊨N!{K7&doMYPj~]cn~u̩s?_; [4 a7&doMZެ߰Q-oJ|r-]{" [6!{#ljfMȰӅ& 6!{#lBIBR4a7BXfe4[8n4 {#lBFؤ͚a &Mq6!{#lBF؄gطAلUζp`b,A{k)m,doMޢ3e1ca͚ 2aGZ801H6H7&do=g ZY5a`#]q`18H<*cuYnxݺLn6el[; K/?ckfoքt 9n&doM@.! x_`1mJr6|u:.eJ#}H`LǑZX}GDp$x:0n & 2;݆J&doЪ- e`2qB;紳Z٭lItjPr{E&z@Uy~Gů+/1`SЗ_w}\:(Qe}\~RWCd{o߭go3wOiMZ60!{Kudo@F؄MZgQ^l/]/cukB7<OU` |10KI L6}E$c$$~F6;{N[k9nN {I~+Ac]6y 4>do[nn nB\ږ wKꊿr  Å=L^QMis1WsOAT_f<}`{ L0%;^@f7\6'aIѨ^1X [IDg_<`+7.A8쁋=s}8ވ:e" vPɛ@c&v`g ~  _\XT A;Jp*@1+T0Wզdor}BVw .otI w0s'`ЦsS]>;.b_HT=> TU蛃d\}8ވX[ 75t`wMP<aa/nc\Lꂿ\P1`/=A[2C)7;UߟVҥU7[:pzvA:^07^a=^c^\ P>BPmgXYAlO~.4n|Ζ<=fy^'談r9썰 & ϰa!2{fg y`W}vIpߕWm.(GZqA$ [x&z!ZpQ2r T?g0`W獫;e5̐ Lxwdp2 7&`oD}osĺMGpe(a/߀%& @S+:̙ akϘϘ'J ! m+m Lު @ M`A{˲G1V nkxaW^fO[i} ?S]򐽅ǿT[Z7$4AT2ax_-߸f7S<گgCX<mKZd}? {+ю`ӬlPI9l 0~ެPi;/m셃~skfCl  ~c]4NL2'_<ΎydIު3/iv]EXkE兴QMl7\pu . v(6eKAI&ymkǮ`?AZf6ׇaloώl ;ޱ ƫ~| /b3<`p2cmYc<!4 ) ~ +z{_u^}qb;/0ߟ7ұDx}f}Ň/@9ar;_ݲ?ުGa[f[A?[l62/봼%U\ٌŊd[O!mK. 8<8X0h{6"ְAU`ZjRW `YnE/">s﷩` .˼08ɭ`[Y^8}|㔴}#OE`h>yz9y?a375T#ꆇ[5PSZ̟/k4lEیL)U]Lu[O7&do #}/;a- Lk\5_Z&m[4D"P F_a}0b1/wDz`Bʯ*~ӷ{N im #eQ=fd޴_k|Ǫ ;˷r[5&>kg}럎-B޲6m>oezVfm=I%\o kLǷU"F Lk\5_Z>Y7ZSM *PD||乃%SgV++UWOl\+) :xZ}+7ʋmc6ӟ|?J ,Y8U^?S0Ǐy%U?k@`fjX'K$[@ɿ!`X_䅣v6m6!{pޯ?ڏFHLo*tEJ#FLՅ>xчo]RQ~zL>@gGK>ty]:\S]pC6[email protected]\{k U]45:IOg _~'ƺP,]Y6'a$ /W 5 `{Sy6 /sXcP1֩Pa jT.F=aLT]T^!{Kudoi@`Tyvf>c6;kӻ׋Dl_ds~jS]\6<J^I*H0&X_OL ꧗9GL*S10y ,UN?v`l!OD%hoҁ-~Ng ;6rCm^h&>1Gfgnq R0Pm>euº1ֳ>q* 7&I[Bm[R<^. zA*uFt(z~l@1p,ަ>U7˜8=( ڇ.dor}B3`w8}vwAcm0h8 /2 *q y8vqAF$){+PA􋻬Iuþ &rn`KZqA$ [,}.-9Z ԗE|mLт \Tldo2֫~2k̡'th${ %){Ѱwqq"lҺ [&{Kf7xxMC;FW0;+Ba3&!01ԅaju)jfM|8a-A$KZqA$ ayU0yX _b]y':C\^ _Etmx`^slz: q!`چTeDžmF^oOlkr;:i5{&ʰ}GM/d`BA{kMdoMEtLuc m}ef61b,0&-h|Pi͚B.6!M؄썰 [LxzT 2(3AŤbvǣgEj$$E>KXu4h]MdoMi(ʵ>6m@U?=o; !X@P`x6~UZ60!{Kudo@F؄(Wb\3& nivnĤ"YJۤ"Y6i5{&~~"0xN[k9nN {#lBFؤ͚a &Mq6!{#lBF؄D>:BZqa7&eoV1ǝ $ ʏi O`8VA{345doMY?o{˙3gHZE|doD␽6!{#lR"!XrIIENDB`
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b67744/b67744.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 legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly 'b67744' {} .assembly extern xunit.core {} .class ILGEN_0xc881452f { .field static native int field_0x5 .method static int32 Method_0x34c75948() { .maxstack 5 .locals (unsigned int32 LOCAL_0x1) ldc.i4 0x3 stloc LOCAL_0x1 ldc.i4 -1 stsfld native int ILGEN_0xc881452f::field_0x5 ldsfld native int ILGEN_0xc881452f::field_0x5 ldc.i4.0 ble Branch_0x0 ldsfld native int ILGEN_0xc881452f::field_0x5 ldsfld native int ILGEN_0xc881452f::field_0x5 cgt.un br Branch_0x1 Branch_0x0: ldloca LOCAL_0x1 ldind.u4 Branch_0x1: ret } .method static int32 Main() { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 2 call int32 ILGEN_0xc881452f::Method_0x34c75948() conv.i4 ldc.i4 97 add 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 legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly 'b67744' {} .assembly extern xunit.core {} .class ILGEN_0xc881452f { .field static native int field_0x5 .method static int32 Method_0x34c75948() { .maxstack 5 .locals (unsigned int32 LOCAL_0x1) ldc.i4 0x3 stloc LOCAL_0x1 ldc.i4 -1 stsfld native int ILGEN_0xc881452f::field_0x5 ldsfld native int ILGEN_0xc881452f::field_0x5 ldc.i4.0 ble Branch_0x0 ldsfld native int ILGEN_0xc881452f::field_0x5 ldsfld native int ILGEN_0xc881452f::field_0x5 cgt.un br Branch_0x1 Branch_0x0: ldloca LOCAL_0x1 ldind.u4 Branch_0x1: ret } .method static int32 Main() { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 2 call int32 ILGEN_0xc881452f::Method_0x34c75948() conv.i4 ldc.i4 97 add ret } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/tests/JIT/Methodical/cctor/simple/precise1_cs_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="precise1.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="precise1.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.IO.FileSystem/tests/Enumeration/RecursionDepthTests.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.Enumeration; using System.Linq; using Xunit; namespace System.IO.Tests.Enumeration { public class RecursionDepthTests : FileSystemTest { public static IEnumerable<string> GetEntryNames(string directory, int depth) { return new FileSystemEnumerable<string>( directory, (ref FileSystemEntry entry) => entry.FileName.ToString(), new EnumerationOptions() { RecurseSubdirectories = true, MaxRecursionDepth = depth }); } [Theory, InlineData(0, 2), InlineData(1, 4), InlineData(2, 5), InlineData(3, 5), InlineData(int.MaxValue, 5) ] public void EnumerateDirectory_WithSpecifedRecursionDepth(int depth, int expectedCount) { DirectoryInfo testDirectory = Directory.CreateDirectory(GetTestFilePath()); DirectoryInfo testSubdirectory1 = Directory.CreateDirectory(Path.Combine(testDirectory.FullName, "Subdirectory1")); DirectoryInfo testSubdirectory2 = Directory.CreateDirectory(Path.Combine(testSubdirectory1.FullName, "Subdirectory2")); FileInfo fileOne = new FileInfo(Path.Combine(testDirectory.FullName, "fileone.htm")); FileInfo fileTwo = new FileInfo(Path.Combine(testSubdirectory1.FullName, "filetwo.html")); FileInfo fileThree = new FileInfo(Path.Combine(testSubdirectory2.FullName, "filethree.doc")); fileOne.Create().Dispose(); fileTwo.Create().Dispose(); fileThree.Create().Dispose(); string[] results = GetEntryNames(testDirectory.FullName, depth).ToArray(); Assert.Equal(expectedCount, results.Length); } [Fact] public void NegativeRecursionDepth_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>(() => new EnumerationOptions() { MaxRecursionDepth = -1 }); } } }
// 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.Enumeration; using System.Linq; using Xunit; namespace System.IO.Tests.Enumeration { public class RecursionDepthTests : FileSystemTest { public static IEnumerable<string> GetEntryNames(string directory, int depth) { return new FileSystemEnumerable<string>( directory, (ref FileSystemEntry entry) => entry.FileName.ToString(), new EnumerationOptions() { RecurseSubdirectories = true, MaxRecursionDepth = depth }); } [Theory, InlineData(0, 2), InlineData(1, 4), InlineData(2, 5), InlineData(3, 5), InlineData(int.MaxValue, 5) ] public void EnumerateDirectory_WithSpecifedRecursionDepth(int depth, int expectedCount) { DirectoryInfo testDirectory = Directory.CreateDirectory(GetTestFilePath()); DirectoryInfo testSubdirectory1 = Directory.CreateDirectory(Path.Combine(testDirectory.FullName, "Subdirectory1")); DirectoryInfo testSubdirectory2 = Directory.CreateDirectory(Path.Combine(testSubdirectory1.FullName, "Subdirectory2")); FileInfo fileOne = new FileInfo(Path.Combine(testDirectory.FullName, "fileone.htm")); FileInfo fileTwo = new FileInfo(Path.Combine(testSubdirectory1.FullName, "filetwo.html")); FileInfo fileThree = new FileInfo(Path.Combine(testSubdirectory2.FullName, "filethree.doc")); fileOne.Create().Dispose(); fileTwo.Create().Dispose(); fileThree.Create().Dispose(); string[] results = GetEntryNames(testDirectory.FullName, depth).ToArray(); Assert.Equal(expectedCount, results.Length); } [Fact] public void NegativeRecursionDepth_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>(() => new EnumerationOptions() { MaxRecursionDepth = -1 }); } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Text.Json/gen/System.Text.Json.SourceGeneration.Roslyn3.11.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AnalyzerRoslynVersion>3.11</AnalyzerRoslynVersion> <RoslynApiVersion>$(MicrosoftCodeAnalysisVersion_3_11)</RoslynApiVersion> </PropertyGroup> <Import Project="System.Text.Json.SourceGeneration.targets" /> <ItemGroup> <Compile Include="JsonSourceGenerator.Roslyn3.11.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AnalyzerRoslynVersion>3.11</AnalyzerRoslynVersion> <RoslynApiVersion>$(MicrosoftCodeAnalysisVersion_3_11)</RoslynApiVersion> </PropertyGroup> <Import Project="System.Text.Json.SourceGeneration.targets" /> <ItemGroup> <Compile Include="JsonSourceGenerator.Roslyn3.11.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/TypeLibImportClassAttributeTests.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.Runtime.InteropServices.Tests { public class TypeLibImportClassAttributeTests { [Fact] public void Ctor_ImportClass() { var attribute = new TypeLibImportClassAttribute(typeof(int)); Assert.Equal(typeof(int).ToString(), attribute.Value); } [Fact] public void Ctor_NullImportClass_ThrowsNullReferenceException() { Assert.Throws<NullReferenceException>(() => new TypeLibImportClassAttribute(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.Runtime.InteropServices.Tests { public class TypeLibImportClassAttributeTests { [Fact] public void Ctor_ImportClass() { var attribute = new TypeLibImportClassAttribute(typeof(int)); Assert.Equal(typeof(int).ToString(), attribute.Value); } [Fact] public void Ctor_NullImportClass_ThrowsNullReferenceException() { Assert.Throws<NullReferenceException>(() => new TypeLibImportClassAttribute(null)); } } }
-1
dotnet/runtime
66,339
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator
Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
stephentoub
2022-03-08T17:15:46Z
2022-03-10T19:11:56Z
cdb1d26bcc40cd651afb5ed8898b0e7e03e95102
28580bf9fc5d40c299af9a51b20f14f6a0db113a
Use StartsWith(..., OrdinalIgnoreCase) in RegexCompiler / source generator. Fixes https://github.com/dotnet/runtime/issues/66324 Depends on https://github.com/dotnet/runtime/pull/66095 Depends on https://github.com/dotnet/runtime/issues/61048 (we have a partial temp solution in place, but that will provide the full one) When we encounter a sequence of sets representing case-insensitive ASCII, we can simplify the code generated to just call StartsWith, which both makes it more readable but also takes advantage of the new JIT optimization to lower that into efficient vectorized comparisons based on the supplied literal. This also cleans up some formatting in the source generator emitted code to make things much more concise and less noisy. Example: In `http://\w+.com` with `RegexOptions.IgnoreCase`, the generated code for the "http://" part had looked like: ```C# if ((uint)slice.Length < 7 || ((slice[0] | 0x20) != 'h') || // Match a character in the set [Hh]. ((slice[1] | 0x20) != 't') || // Match a character in the set [Tt] exactly 2 times. ((slice[2] | 0x20) != 't') || ((slice[3] | 0x20) != 'p')) // Match a character in the set [Pp]. { return false; // The input didn't match. } // Match the string "://". { if (!global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) { return false; // The input didn't match. } } ``` and with this PR looks like: ```C# if ((uint)slice.Length < 7 || !global::System.MemoryExtensions.StartsWith(slice, "http", global::System.StringComparison.OrdinalIgnoreCase) || // Match the string "http" (ordinal case-insensitive) !global::System.MemoryExtensions.StartsWith(slice.Slice(4), "://")) // Match the string "://". { return false; // The input didn't match. } ``` I've not measured perf yet and will wait for that until #66095 is merged.
./src/tests/JIT/SIMD/BoxUnbox.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.Numerics; namespace VectorMathTests { class Program { static int Main(string[] args) { { var a = new System.Numerics.Vector<int>(1); object b = a; if (b is System.Numerics.Vector<int>) { var c = (System.Numerics.Vector<int>)b; if (a != c) { return 0; } } else { return 0; } } { var a = new System.Numerics.Vector4(1); object b = a; if (b is System.Numerics.Vector4) { var c = (System.Numerics.Vector4)b; if (a != c) { return 0; } } else { return 0; } } 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; using System.Collections.Generic; using System.Numerics; namespace VectorMathTests { class Program { static int Main(string[] args) { { var a = new System.Numerics.Vector<int>(1); object b = a; if (b is System.Numerics.Vector<int>) { var c = (System.Numerics.Vector<int>)b; if (a != c) { return 0; } } else { return 0; } } { var a = new System.Numerics.Vector4(1); object b = a; if (b is System.Numerics.Vector4) { var c = (System.Numerics.Vector4)b; if (a != c) { return 0; } } else { return 0; } } return 100; } } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.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; using System.Runtime.InteropServices; using System.Security.Authentication.ExtendedProtection; using Microsoft.Win32.SafeHandles; namespace System.Net.Security { // // Used when working with SSPI APIs, like SafeSspiAuthDataHandle(). Holds the pointer to the auth data blob. // #if DEBUG internal sealed class SafeSspiAuthDataHandle : DebugSafeHandle { #else internal sealed class SafeSspiAuthDataHandle : SafeHandleZeroOrMinusOneIsInvalid { #endif public SafeSspiAuthDataHandle() : base(true) { } protected override bool ReleaseHandle() { return Interop.SspiCli.SspiFreeAuthIdentity(handle) == Interop.SECURITY_STATUS.OK; } } // // A set of Safe Handles that depend on native FreeContextBuffer finalizer. // #if DEBUG internal abstract class SafeFreeContextBuffer : DebugSafeHandle { #else internal abstract class SafeFreeContextBuffer : SafeHandleZeroOrMinusOneIsInvalid { #endif protected SafeFreeContextBuffer() : base(true) { } // This must be ONLY called from this file. internal void Set(IntPtr value) { this.handle = value; } internal static int EnumeratePackages(out int pkgnum, out SafeFreeContextBuffer pkgArray) { int res = Interop.SspiCli.EnumerateSecurityPackagesW(out pkgnum, out SafeFreeContextBuffer_SECURITY? pkgArray_SECURITY); pkgArray = pkgArray_SECURITY; if (res != 0) { pkgArray?.SetHandleAsInvalid(); } return res; } internal static SafeFreeContextBuffer CreateEmptyHandle() { return new SafeFreeContextBuffer_SECURITY(); } // // After PInvoke call the method will fix the refHandle.handle with the returned value. // The caller is responsible for creating a correct SafeHandle template or null can be passed if no handle is returned. // // This method switches between three non-interruptible helper methods. (This method can't be both non-interruptible and // reference imports from all three DLLs - doing so would cause all three DLLs to try to be bound to.) // public static unsafe int QueryContextAttributes(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte* buffer, SafeHandle? refHandle) { int status = (int)Interop.SECURITY_STATUS.InvalidHandle; try { bool ignore = false; phContext.DangerousAddRef(ref ignore); status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer); } finally { phContext.DangerousRelease(); } if (status == 0 && refHandle != null) { if (refHandle is SafeFreeContextBuffer) { ((SafeFreeContextBuffer)refHandle).Set(*(IntPtr*)buffer); } else { ((SafeFreeCertContext)refHandle).Set(*(IntPtr*)buffer); } } if (status != 0) { refHandle?.SetHandleAsInvalid(); } return status; } public static int SetContextAttributes( SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte[] buffer) { try { bool ignore = false; phContext.DangerousAddRef(ref ignore); return Interop.SspiCli.SetContextAttributesW(ref phContext._handle, contextAttribute, buffer, buffer.Length); } finally { phContext.DangerousRelease(); } } } internal sealed class SafeFreeContextBuffer_SECURITY : SafeFreeContextBuffer { public SafeFreeContextBuffer_SECURITY() : base() { } protected override bool ReleaseHandle() { return Interop.SspiCli.FreeContextBuffer(handle) == 0; } } // // Implementation of handles required CertFreeCertificateContext // #if DEBUG internal sealed class SafeFreeCertContext : DebugSafeHandle { #else internal sealed class SafeFreeCertContext : SafeHandleZeroOrMinusOneIsInvalid { #endif public SafeFreeCertContext() : base(true) { } // This must be ONLY called from this file. internal void Set(IntPtr value) { this.handle = value; } protected override bool ReleaseHandle() { Interop.Crypt32.CertFreeCertificateContext(handle); return true; } } // // Implementation of handles dependable on FreeCredentialsHandle // #if DEBUG internal abstract class SafeFreeCredentials : DebugSafeHandle { #else internal abstract class SafeFreeCredentials : SafeHandle { #endif internal Interop.SspiCli.CredHandle _handle; //should be always used as by ref in PInvokes parameters protected SafeFreeCredentials() : base(IntPtr.Zero, true) { _handle = default; } public override bool IsInvalid { get { return IsClosed || _handle.IsZero; } } #if DEBUG public new IntPtr DangerousGetHandle() { Debug.Fail("This method should never be called for this type"); throw NotImplemented.ByDesign; } #endif public static unsafe int AcquireDefaultCredential( string package, Interop.SspiCli.CredentialUse intent, out SafeFreeCredentials outCredential) { int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, IntPtr.Zero, null, null, ref outCredential._handle, out timeStamp); if (NetEventSource.Log.IsEnabled()) NetEventSource.Verbose(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public static unsafe int AcquireCredentialsHandle( string package, Interop.SspiCli.CredentialUse intent, ref SafeSspiAuthDataHandle authdata, out SafeFreeCredentials outCredential) { outCredential = new SafeFreeCredential_SECURITY(); int errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, authdata, null, null, ref outCredential._handle, out _); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public static unsafe int AcquireCredentialsHandle( string package, Interop.SspiCli.CredentialUse intent, Interop.SspiCli.SCHANNEL_CRED* authdata, out SafeFreeCredentials outCredential) { int errorCode = -1; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, authdata, null, null, ref outCredential._handle, out _); if (NetEventSource.Log.IsEnabled()) NetEventSource.Verbose(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public static unsafe int AcquireCredentialsHandle( string package, Interop.SspiCli.CredentialUse intent, Interop.SspiCli.SCH_CREDENTIALS* authdata, out SafeFreeCredentials outCredential) { long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); int errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, authdata, null, null, ref outCredential._handle, out timeStamp); if (NetEventSource.Log.IsEnabled()) NetEventSource.Verbose(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } } internal sealed class SafeFreeCredential_SECURITY : SafeFreeCredentials { public SafeFreeCredential_SECURITY() : base() { } protected override bool ReleaseHandle() { return Interop.SspiCli.FreeCredentialsHandle(ref _handle) == 0; } } // // Implementation of handles that are dependent on DeleteSecurityContext // #if DEBUG internal abstract partial class SafeDeleteContext : DebugSafeHandle { #else internal abstract partial class SafeDeleteContext : SafeHandle { #endif private const string dummyStr = " "; private static readonly IdnMapping s_idnMapping = new IdnMapping(); protected SafeFreeCredentials? _EffectiveCredential; //------------------------------------------------------------------- internal static unsafe int InitializeSecurityContext( ref SafeFreeCredentials? inCredentials, ref SafeDeleteSslContext? refContext, string? targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, InputSecurityBuffers inSecBuffers, ref SecurityBuffer outSecBuffer, ref Interop.SspiCli.ContextFlags outFlags) { ArgumentNullException.ThrowIfNull(inCredentials); Debug.Assert(inSecBuffers.Count <= 3); Interop.SspiCli.SecBufferDesc inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Count); Interop.SspiCli.SecBufferDesc outSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); // Actually, this is returned in outFlags. bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; bool isContextAbsent = true; if (refContext != null) { isContextAbsent = refContext._handle.IsZero; } // Optional output buffer that may need to be freed. IntPtr outoutBuffer = IntPtr.Zero; try { Span<Interop.SspiCli.SecBuffer> inUnmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[3]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) fixed (void* pinnedToken0 = inSecBuffers._item0.Token) fixed (void* pinnedToken1 = inSecBuffers._item1.Token) fixed (void* pinnedToken2 = inSecBuffers._item2.Token) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr; // Updated pvBuffer with pinned address. UnmanagedToken takes precedence. if (inSecBuffers.Count > 2) { inUnmanagedBuffer[2].BufferType = inSecBuffers._item2.Type; if (inSecBuffers._item2.UnmanagedToken != null) { Debug.Assert(inSecBuffers._item2.Type == SecurityBufferType.SECBUFFER_CHANNEL_BINDINGS); inUnmanagedBuffer[2].pvBuffer = (IntPtr)inSecBuffers._item2.UnmanagedToken.DangerousGetHandle(); inUnmanagedBuffer[2].cbBuffer = ((ChannelBinding)inSecBuffers._item2.UnmanagedToken).Size; } else { inUnmanagedBuffer[2].cbBuffer = inSecBuffers._item2.Token.Length; inUnmanagedBuffer[2].pvBuffer = (IntPtr)pinnedToken2; } } if (inSecBuffers.Count > 1) { inUnmanagedBuffer[1].BufferType = inSecBuffers._item1.Type; if (inSecBuffers._item1.UnmanagedToken != null) { Debug.Assert(inSecBuffers._item1.Type == SecurityBufferType.SECBUFFER_CHANNEL_BINDINGS); inUnmanagedBuffer[1].pvBuffer = (IntPtr)inSecBuffers._item1.UnmanagedToken.DangerousGetHandle(); inUnmanagedBuffer[1].cbBuffer = ((ChannelBinding)inSecBuffers._item1.UnmanagedToken).Size; } else { inUnmanagedBuffer[1].cbBuffer = inSecBuffers._item1.Token.Length; inUnmanagedBuffer[1].pvBuffer = (IntPtr)pinnedToken1; } } if (inSecBuffers.Count > 0) { inUnmanagedBuffer[0].BufferType = inSecBuffers._item0.Type; if (inSecBuffers._item0.UnmanagedToken != null) { Debug.Assert(inSecBuffers._item0.Type == SecurityBufferType.SECBUFFER_CHANNEL_BINDINGS); inUnmanagedBuffer[0].pvBuffer = (IntPtr)inSecBuffers._item0.UnmanagedToken.DangerousGetHandle(); inUnmanagedBuffer[0].cbBuffer = ((ChannelBinding)inSecBuffers._item0.UnmanagedToken).Size; } else { inUnmanagedBuffer[0].cbBuffer = inSecBuffers._item0.Token.Length; inUnmanagedBuffer[0].pvBuffer = (IntPtr)pinnedToken0; } } fixed (byte* pinnedOutBytes = outSecBuffer.token) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. Interop.SspiCli.SecBuffer outUnmanagedBuffer = default; outSecurityBufferDescriptor.pBuffers = &outUnmanagedBuffer; outUnmanagedBuffer.cbBuffer = outSecBuffer.size; outUnmanagedBuffer.BufferType = outSecBuffer.type; outUnmanagedBuffer.pvBuffer = outSecBuffer.token == null || outSecBuffer.token.Length == 0 ? IntPtr.Zero : (IntPtr)(pinnedOutBytes + outSecBuffer.offset); if (refContext == null || refContext.IsInvalid) { // Previous versions unconditionally built a new "refContext" here, but would pass // incorrect arguments to InitializeSecurityContextW in cases where an "contextHandle" was // already present and non-zero. if (isContextAbsent) refContext = new SafeDeleteSslContext(); } if (targetName == null || targetName.Length == 0) { targetName = dummyStr; } string punyCode = s_idnMapping.GetAscii(targetName); fixed (char* namePtr = punyCode) { errorCode = MustRunInitializeSecurityContext( ref inCredentials, isContextAbsent, (byte*)(((object)targetName == (object)dummyStr) ? null : namePtr), inFlags, endianness, &inSecurityBufferDescriptor, refContext!, ref outSecurityBufferDescriptor, ref outFlags, null); if (isSspiAllocated) { outoutBuffer = outUnmanagedBuffer.pvBuffer; } // Get unmanaged buffer with index 0 as the only one passed into PInvoke. outSecBuffer.size = outUnmanagedBuffer.cbBuffer; outSecBuffer.type = outUnmanagedBuffer.BufferType; outSecBuffer.token = outSecBuffer.size > 0 ? new Span<byte>((byte*)outUnmanagedBuffer.pvBuffer, outUnmanagedBuffer.cbBuffer).ToArray() : null; if (inSecBuffers.Count > 1 && inUnmanagedBuffer[1].BufferType == SecurityBufferType.SECBUFFER_EXTRA && inSecBuffers._item1.Type == SecurityBufferType.SECBUFFER_EMPTY) { // OS function did not use all provided data and turned EMPTY to EXTRA // https://docs.microsoft.com/en-us/windows/win32/secauthn/extra-buffers-returned-by-schannel int leftover = inUnmanagedBuffer[1].cbBuffer; int processed = inSecBuffers._item0.Token.Length - inUnmanagedBuffer[1].cbBuffer; /* skip over processed data and try it again. */ inUnmanagedBuffer[0].cbBuffer = leftover; inUnmanagedBuffer[0].pvBuffer = inUnmanagedBuffer[0].pvBuffer + processed; inUnmanagedBuffer[1].BufferType = SecurityBufferType.SECBUFFER_EMPTY; inUnmanagedBuffer[1].cbBuffer = 0; outUnmanagedBuffer.cbBuffer = 0; if (outoutBuffer != IntPtr.Zero) { Interop.SspiCli.FreeContextBuffer(outoutBuffer); outoutBuffer = IntPtr.Zero; } errorCode = MustRunInitializeSecurityContext( ref inCredentials, isContextAbsent, (byte*)(((object)targetName == (object)dummyStr) ? null : namePtr), inFlags, endianness, &inSecurityBufferDescriptor, refContext!, ref outSecurityBufferDescriptor, ref outFlags, null); if (isSspiAllocated) { outoutBuffer = outUnmanagedBuffer.pvBuffer; } if (outUnmanagedBuffer.cbBuffer > 0) { if (outSecBuffer.size == 0) { // We did not get anything in the first round. outSecBuffer.size = outUnmanagedBuffer.cbBuffer; outSecBuffer.type = outUnmanagedBuffer.BufferType; outSecBuffer.token = new Span<byte>((byte*)outUnmanagedBuffer.pvBuffer, outUnmanagedBuffer.cbBuffer).ToArray(); } else { byte[] buffer = new byte[outSecBuffer.size + outUnmanagedBuffer.cbBuffer]; Buffer.BlockCopy(outSecBuffer.token!, 0, buffer, 0, outSecBuffer.size); new Span<byte>((byte*)outUnmanagedBuffer.pvBuffer, outUnmanagedBuffer.cbBuffer).CopyTo(new Span<byte>(buffer, outSecBuffer.size, outUnmanagedBuffer.cbBuffer)); outSecBuffer.size = buffer.Length; outSecBuffer.token = buffer; } } if (inUnmanagedBuffer[1].BufferType == SecurityBufferType.SECBUFFER_EXTRA) { // we are left with unprocessed data again. fail with SEC_E_INCOMPLETE_MESSAGE hResult. errorCode = unchecked((int)0x80090318); } } } } } } finally { if (outoutBuffer != IntPtr.Zero) { Interop.SspiCli.FreeContextBuffer(outoutBuffer); } } return errorCode; } // // After PInvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned. // private static unsafe int MustRunInitializeSecurityContext( ref SafeFreeCredentials inCredentials, bool isContextAbsent, byte* targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, Interop.SspiCli.SecBufferDesc* inputBuffer, SafeDeleteContext outContext, ref Interop.SspiCli.SecBufferDesc outputBuffer, ref Interop.SspiCli.ContextFlags attributes, SafeFreeContextBuffer? handleTemplate) { int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; try { bool ignore = false; inCredentials.DangerousAddRef(ref ignore); outContext.DangerousAddRef(ref ignore); Interop.SspiCli.CredHandle credentialHandle = inCredentials._handle; long timeStamp; // Now that "outContext" (or "refContext" by the caller) references an actual handle (and cannot // be closed until it is released below), point "inContextPtr" to its embedded handle (or // null if the embedded handle has not yet been initialized). Interop.SspiCli.CredHandle contextHandle = outContext._handle; void* inContextPtr = contextHandle.IsZero ? null : &contextHandle; // The "isContextAbsent" supplied by the caller is generally correct but was computed without proper // synchronization. Rewrite the indicator now that the final "inContext" is known, update if necessary. isContextAbsent = (inContextPtr == null); errorCode = Interop.SspiCli.InitializeSecurityContextW( ref credentialHandle, inContextPtr, targetName, inFlags, 0, endianness, inputBuffer, 0, ref outContext._handle, ref outputBuffer, ref attributes, out timeStamp); } finally { // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle outContext._EffectiveCredential?.DangerousRelease(); outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); } // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes handleTemplate.Set(((Interop.SspiCli.SecBuffer*)outputBuffer.pBuffers)->pvBuffer); if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } if (isContextAbsent && (errorCode & 0x80000000) != 0) { // an error on the first call, need to set the out handle to invalid value outContext._handle.SetToInvalid(); } return errorCode; } //------------------------------------------------------------------- internal static unsafe int AcceptSecurityContext( ref SafeFreeCredentials? inCredentials, ref SafeDeleteSslContext? refContext, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, InputSecurityBuffers inSecBuffers, ref SecurityBuffer outSecBuffer, ref Interop.SspiCli.ContextFlags outFlags) { ArgumentNullException.ThrowIfNull(inCredentials); Debug.Assert(inSecBuffers.Count <= 3); Interop.SspiCli.SecBufferDesc inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Count); Interop.SspiCli.SecBufferDesc outSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(count: 2); // Actually, this is returned in outFlags. bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; bool isContextAbsent = true; if (refContext != null) { isContextAbsent = refContext._handle.IsZero; } Span<Interop.SspiCli.SecBuffer> outUnmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[2]; outUnmanagedBuffer[1].pvBuffer = IntPtr.Zero; try { // Allocate always maximum to allow better code optimization. Span<Interop.SspiCli.SecBuffer> inUnmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[3]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer) fixed (void* pinnedToken0 = inSecBuffers._item0.Token) fixed (void* pinnedToken1 = inSecBuffers._item1.Token) fixed (void* pinnedToken2 = inSecBuffers._item2.Token) { inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr; // Updated pvBuffer with pinned address. UnmanagedToken takes precedence. if (inSecBuffers.Count > 2) { inUnmanagedBuffer[2].BufferType = inSecBuffers._item2.Type; if (inSecBuffers._item2.UnmanagedToken != null) { Debug.Assert(inSecBuffers._item2.Type == SecurityBufferType.SECBUFFER_CHANNEL_BINDINGS); inUnmanagedBuffer[2].pvBuffer = (IntPtr)inSecBuffers._item2.UnmanagedToken.DangerousGetHandle(); inUnmanagedBuffer[2].cbBuffer = ((ChannelBinding)inSecBuffers._item2.UnmanagedToken).Size; } else { inUnmanagedBuffer[2].cbBuffer = inSecBuffers._item2.Token.Length; inUnmanagedBuffer[2].pvBuffer = (IntPtr)pinnedToken2; } } if (inSecBuffers.Count > 1) { inUnmanagedBuffer[1].BufferType = inSecBuffers._item1.Type; if (inSecBuffers._item1.UnmanagedToken != null) { Debug.Assert(inSecBuffers._item1.Type == SecurityBufferType.SECBUFFER_CHANNEL_BINDINGS); inUnmanagedBuffer[1].pvBuffer = (IntPtr)inSecBuffers._item1.UnmanagedToken.DangerousGetHandle(); inUnmanagedBuffer[1].cbBuffer = ((ChannelBinding)inSecBuffers._item1.UnmanagedToken).Size; } else { inUnmanagedBuffer[1].cbBuffer = inSecBuffers._item1.Token.Length; inUnmanagedBuffer[1].pvBuffer = (IntPtr)pinnedToken1; } } if (inSecBuffers.Count > 0) { inUnmanagedBuffer[0].BufferType = inSecBuffers._item0.Type; if (inSecBuffers._item0.UnmanagedToken != null) { Debug.Assert(inSecBuffers._item0.Type == SecurityBufferType.SECBUFFER_CHANNEL_BINDINGS); inUnmanagedBuffer[0].pvBuffer = (IntPtr)inSecBuffers._item0.UnmanagedToken.DangerousGetHandle(); inUnmanagedBuffer[0].cbBuffer = ((ChannelBinding)inSecBuffers._item0.UnmanagedToken).Size; } else { inUnmanagedBuffer[0].cbBuffer = inSecBuffers._item0.Token.Length; inUnmanagedBuffer[0].pvBuffer = (IntPtr)pinnedToken0; } } fixed (byte* pinnedOutBytes = outSecBuffer.token) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. outSecurityBufferDescriptor.pBuffers = outUnmanagedBufferPtr; // Copy the SecurityBuffer content into unmanaged place holder. outUnmanagedBuffer[0].cbBuffer = outSecBuffer.size; outUnmanagedBuffer[0].BufferType = outSecBuffer.type; outUnmanagedBuffer[0].pvBuffer = outSecBuffer.token == null || outSecBuffer.token.Length == 0 ? IntPtr.Zero : (IntPtr)(pinnedOutBytes + outSecBuffer.offset); outUnmanagedBuffer[1].cbBuffer = 0; outUnmanagedBuffer[1].BufferType = SecurityBufferType.SECBUFFER_ALERT; if (refContext == null || refContext.IsInvalid) { // Previous versions unconditionally built a new "refContext" here, but would pass // incorrect arguments to AcceptSecurityContext in cases where an "contextHandle" was // already present and non-zero. if (isContextAbsent) refContext = new SafeDeleteSslContext(); } errorCode = MustRunAcceptSecurityContext_SECURITY( ref inCredentials, isContextAbsent, &inSecurityBufferDescriptor, inFlags, endianness, refContext!, ref outSecurityBufferDescriptor, ref outFlags, null); // No data written out but there is Alert int index = outUnmanagedBuffer[0].cbBuffer == 0 && outUnmanagedBuffer[1].cbBuffer > 0 ? 1 : 0; outSecBuffer.size = outUnmanagedBuffer[index].cbBuffer; outSecBuffer.type = outUnmanagedBuffer[index].BufferType; outSecBuffer.token = outSecBuffer.size > 0 ? new Span<byte>((byte*)outUnmanagedBuffer[index].pvBuffer, outUnmanagedBuffer[0].cbBuffer).ToArray() : null; if (inSecBuffers.Count > 1 && inUnmanagedBuffer[1].BufferType == SecurityBufferType.SECBUFFER_EXTRA && inSecBuffers._item1.Type == SecurityBufferType.SECBUFFER_EMPTY) { // OS function did not use all provided data and turned EMPTY to EXTRA // https://docs.microsoft.com/en-us/windows/win32/secauthn/extra-buffers-returned-by-schannel int leftover = inUnmanagedBuffer[1].cbBuffer; int processed = inSecBuffers._item0.Token.Length - inUnmanagedBuffer[1].cbBuffer; /* skip over processed data and try it again. */ inUnmanagedBuffer[0].cbBuffer = leftover; inUnmanagedBuffer[0].pvBuffer = inUnmanagedBuffer[0].pvBuffer + processed; inUnmanagedBuffer[1].BufferType = SecurityBufferType.SECBUFFER_EMPTY; inUnmanagedBuffer[1].cbBuffer = 0; outUnmanagedBuffer[0].cbBuffer = 0; if (isSspiAllocated && outUnmanagedBuffer[0].pvBuffer != IntPtr.Zero) { Interop.SspiCli.FreeContextBuffer(outUnmanagedBuffer[0].pvBuffer); outUnmanagedBuffer[0].pvBuffer = IntPtr.Zero; } errorCode = MustRunAcceptSecurityContext_SECURITY( ref inCredentials, isContextAbsent, &inSecurityBufferDescriptor, inFlags, endianness, refContext!, ref outSecurityBufferDescriptor, ref outFlags, null); index = outUnmanagedBuffer[0].cbBuffer == 0 && outUnmanagedBuffer[1].cbBuffer > 0 ? 1 : 0; if (outUnmanagedBuffer[index].cbBuffer > 0) { if (outSecBuffer.size == 0) { // We did not get anything in the first round. outSecBuffer.size = outUnmanagedBuffer[index].cbBuffer; outSecBuffer.type = outUnmanagedBuffer[index].BufferType; outSecBuffer.token = new Span<byte>((byte*)outUnmanagedBuffer[index].pvBuffer, outUnmanagedBuffer[index].cbBuffer).ToArray(); } else { byte[] buffer = new byte[outSecBuffer.size + outUnmanagedBuffer[index].cbBuffer]; Buffer.BlockCopy(outSecBuffer.token!, 0, buffer, 0, outSecBuffer.size); new Span<byte>((byte*)outUnmanagedBuffer[index].pvBuffer, outUnmanagedBuffer[index].cbBuffer).CopyTo(new Span<byte>(buffer, outSecBuffer.size, outUnmanagedBuffer[index].cbBuffer)); outSecBuffer.size = buffer.Length; outSecBuffer.token = buffer; } } if (inUnmanagedBuffer[1].BufferType == SecurityBufferType.SECBUFFER_EXTRA) { // we are left with unprocessed data again. fail with SEC_E_INCOMPLETE_MESSAGE hResult. errorCode = unchecked((int)0x80090318); } } } } } finally { if (isSspiAllocated && outUnmanagedBuffer[0].pvBuffer != IntPtr.Zero) { Interop.SspiCli.FreeContextBuffer(outUnmanagedBuffer[0].pvBuffer); } if (outUnmanagedBuffer[1].pvBuffer != IntPtr.Zero) { Interop.SspiCli.FreeContextBuffer(outUnmanagedBuffer[1].pvBuffer); } } return errorCode; } // // After PInvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned. // private static unsafe int MustRunAcceptSecurityContext_SECURITY( ref SafeFreeCredentials inCredentials, bool isContextAbsent, Interop.SspiCli.SecBufferDesc* inputBuffer, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, SafeDeleteContext outContext, ref Interop.SspiCli.SecBufferDesc outputBuffer, ref Interop.SspiCli.ContextFlags outFlags, SafeFreeContextBuffer? handleTemplate) { int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; // Run the body of this method as a non-interruptible block. try { bool ignore = false; inCredentials.DangerousAddRef(ref ignore); outContext.DangerousAddRef(ref ignore); Interop.SspiCli.CredHandle credentialHandle = inCredentials._handle; long timeStamp; // Now that "outContext" (or "refContext" by the caller) references an actual handle (and cannot // be closed until it is released below), point "inContextPtr" to its embedded handle (or // null if the embedded handle has not yet been initialized). Interop.SspiCli.CredHandle contextHandle = outContext._handle; void* inContextPtr = contextHandle.IsZero ? null : &contextHandle; // The "isContextAbsent" supplied by the caller is generally correct but was computed without proper // synchronization. Rewrite the indicator now that the final "inContext" is known, update if necessary. isContextAbsent = (inContextPtr == null); errorCode = Interop.SspiCli.AcceptSecurityContext( ref credentialHandle, inContextPtr, inputBuffer, inFlags, endianness, ref outContext._handle, ref outputBuffer, ref outFlags, out timeStamp); } finally { // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle. outContext._EffectiveCredential?.DangerousRelease(); outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); } // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes. handleTemplate.Set(((Interop.SspiCli.SecBuffer*)outputBuffer.pBuffers)->pvBuffer); if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } if (isContextAbsent && (errorCode & 0x80000000) != 0) { // An error on the first call, need to set the out handle to invalid value. outContext._handle.SetToInvalid(); } return errorCode; } internal static unsafe int CompleteAuthToken( ref SafeDeleteSslContext? refContext, in SecurityBuffer inSecBuffer) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"refContext = {refContext}, inSecBuffer = {inSecBuffer}"); var inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; Interop.SspiCli.SecBuffer inUnmanagedBuffer = default; inSecurityBufferDescriptor.pBuffers = &inUnmanagedBuffer; fixed (byte* pinnedToken = inSecBuffer.token) { inUnmanagedBuffer.cbBuffer = inSecBuffer.size; inUnmanagedBuffer.BufferType = inSecBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. inUnmanagedBuffer.pvBuffer = inSecBuffer.unmanagedToken != null ? inSecBuffer.unmanagedToken.DangerousGetHandle() : inSecBuffer.token == null || inSecBuffer.token.Length == 0 ? IntPtr.Zero : (IntPtr)(pinnedToken + inSecBuffer.offset); Interop.SspiCli.CredHandle contextHandle = refContext != null ? refContext._handle : default; if (refContext == null || refContext.IsInvalid) { // Previous versions unconditionally built a new "refContext" here, but would pass // incorrect arguments to CompleteAuthToken in cases where a nonzero "contextHandle" was // already present. In these cases, allow the "refContext" to flow through unmodified // (which will generate an ObjectDisposedException below). In all other cases, continue to // build a new "refContext" in an attempt to maximize compat. if (contextHandle.IsZero) { refContext = new SafeDeleteSslContext(); } } bool gotRef = false; try { refContext!.DangerousAddRef(ref gotRef); errorCode = Interop.SspiCli.CompleteAuthToken(contextHandle.IsZero ? null : &contextHandle, ref inSecurityBufferDescriptor); } finally { if (gotRef) { refContext!.DangerousRelease(); } } } return errorCode; } internal static unsafe int ApplyControlToken( ref SafeDeleteContext? refContext, in SecurityBuffer inSecBuffer) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"refContext = {refContext}, inSecBuffer = {inSecBuffer}"); int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; // Fix Descriptor pointer that points to unmanaged SecurityBuffers. fixed (byte* pinnedInSecBufferToken = inSecBuffer.token) { var inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); Interop.SspiCli.SecBuffer inUnmanagedBuffer = default; inSecurityBufferDescriptor.pBuffers = &inUnmanagedBuffer; inUnmanagedBuffer.cbBuffer = inSecBuffer.size; inUnmanagedBuffer.BufferType = inSecBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. inUnmanagedBuffer.pvBuffer = inSecBuffer.unmanagedToken != null ? inSecBuffer.unmanagedToken.DangerousGetHandle() : inSecBuffer.token == null || inSecBuffer.token.Length == 0 ? IntPtr.Zero : (IntPtr)(pinnedInSecBufferToken + inSecBuffer.offset); Interop.SspiCli.CredHandle contextHandle = refContext != null ? refContext._handle : default; if (refContext == null || refContext.IsInvalid) { // Previous versions unconditionally built a new "refContext" here, but would pass // incorrect arguments to ApplyControlToken in cases where a nonzero "contextHandle" was // already present. In these cases, allow the "refContext" to flow through unmodified // (which will generate an ObjectDisposedException below). In all other cases, continue to // build a new "refContext" in an attempt to maximize compat. if (contextHandle.IsZero) { refContext = new SafeDeleteSslContext(); } } bool gotRef = false; try { refContext!.DangerousAddRef(ref gotRef); errorCode = Interop.SspiCli.ApplyControlToken(contextHandle.IsZero ? null : &contextHandle, ref inSecurityBufferDescriptor); } finally { if (gotRef) { refContext!.DangerousRelease(); } } } return errorCode; } } internal sealed class SafeDeleteSslContext : SafeDeleteContext { public SafeDeleteSslContext() : base() { } protected override bool ReleaseHandle() { this._EffectiveCredential?.DangerousRelease(); return Interop.SspiCli.DeleteSecurityContext(ref _handle) == 0; } } // Based on SafeFreeContextBuffer. internal abstract class SafeFreeContextBufferChannelBinding : ChannelBinding { private int _size; public override int Size { get { return _size; } } public override bool IsInvalid { get { return handle == new IntPtr(0) || handle == new IntPtr(-1); } } internal unsafe void Set(IntPtr value) { this.handle = value; } internal static SafeFreeContextBufferChannelBinding CreateEmptyHandle() { return new SafeFreeContextBufferChannelBinding_SECURITY(); } public static unsafe int QueryContextChannelBinding(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, SecPkgContext_Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle) { int status = (int)Interop.SECURITY_STATUS.InvalidHandle; // SCHANNEL only supports SECPKG_ATTR_ENDPOINT_BINDINGS and SECPKG_ATTR_UNIQUE_BINDINGS which // map to our enum ChannelBindingKind.Endpoint and ChannelBindingKind.Unique. if (contextAttribute != Interop.SspiCli.ContextAttribute.SECPKG_ATTR_ENDPOINT_BINDINGS && contextAttribute != Interop.SspiCli.ContextAttribute.SECPKG_ATTR_UNIQUE_BINDINGS) { return status; } try { bool ignore = false; phContext.DangerousAddRef(ref ignore); status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer); } finally { phContext.DangerousRelease(); } if (status == 0 && refHandle != null) { refHandle.Set((*buffer).Bindings); refHandle._size = (*buffer).BindingsLength; } if (status != 0) { refHandle?.SetHandleAsInvalid(); } return status; } public override string? ToString() { if (IsInvalid) { return null; } var bytes = new byte[_size]; Marshal.Copy(handle, bytes, 0, bytes.Length); return BitConverter.ToString(bytes).Replace('-', ' '); } } internal sealed class SafeFreeContextBufferChannelBinding_SECURITY : SafeFreeContextBufferChannelBinding { protected override bool ReleaseHandle() { return Interop.SspiCli.FreeContextBuffer(handle) == 0; } } }
// 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; using System.Runtime.InteropServices; using System.Security.Authentication.ExtendedProtection; using Microsoft.Win32.SafeHandles; namespace System.Net.Security { // // Used when working with SSPI APIs, like SafeSspiAuthDataHandle(). Holds the pointer to the auth data blob. // #if DEBUG internal sealed class SafeSspiAuthDataHandle : DebugSafeHandle { #else internal sealed class SafeSspiAuthDataHandle : SafeHandleZeroOrMinusOneIsInvalid { #endif public SafeSspiAuthDataHandle() : base(true) { } protected override bool ReleaseHandle() { return Interop.SspiCli.SspiFreeAuthIdentity(handle) == Interop.SECURITY_STATUS.OK; } } // // A set of Safe Handles that depend on native FreeContextBuffer finalizer. // #if DEBUG internal abstract class SafeFreeContextBuffer : DebugSafeHandle { #else internal abstract class SafeFreeContextBuffer : SafeHandleZeroOrMinusOneIsInvalid { #endif protected SafeFreeContextBuffer() : base(true) { } // This must be ONLY called from this file. internal void Set(IntPtr value) { this.handle = value; } internal static int EnumeratePackages(out int pkgnum, out SafeFreeContextBuffer pkgArray) { int res = Interop.SspiCli.EnumerateSecurityPackagesW(out pkgnum, out SafeFreeContextBuffer_SECURITY? pkgArray_SECURITY); pkgArray = pkgArray_SECURITY; if (res != 0) { pkgArray?.SetHandleAsInvalid(); } return res; } internal static SafeFreeContextBuffer CreateEmptyHandle() { return new SafeFreeContextBuffer_SECURITY(); } // // After PInvoke call the method will fix the refHandle.handle with the returned value. // The caller is responsible for creating a correct SafeHandle template or null can be passed if no handle is returned. // // This method switches between three non-interruptible helper methods. (This method can't be both non-interruptible and // reference imports from all three DLLs - doing so would cause all three DLLs to try to be bound to.) // public static unsafe int QueryContextAttributes(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte* buffer, SafeHandle? refHandle) { int status = (int)Interop.SECURITY_STATUS.InvalidHandle; try { bool ignore = false; phContext.DangerousAddRef(ref ignore); status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer); } finally { phContext.DangerousRelease(); } if (status == 0 && refHandle != null) { if (refHandle is SafeFreeContextBuffer) { ((SafeFreeContextBuffer)refHandle).Set(*(IntPtr*)buffer); } else { ((SafeFreeCertContext)refHandle).Set(*(IntPtr*)buffer); } } if (status != 0) { refHandle?.SetHandleAsInvalid(); } return status; } public static int SetContextAttributes( SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte[] buffer) { try { bool ignore = false; phContext.DangerousAddRef(ref ignore); return Interop.SspiCli.SetContextAttributesW(ref phContext._handle, contextAttribute, buffer, buffer.Length); } finally { phContext.DangerousRelease(); } } } internal sealed class SafeFreeContextBuffer_SECURITY : SafeFreeContextBuffer { public SafeFreeContextBuffer_SECURITY() : base() { } protected override bool ReleaseHandle() { return Interop.SspiCli.FreeContextBuffer(handle) == 0; } } // // Implementation of handles required CertFreeCertificateContext // #if DEBUG internal sealed class SafeFreeCertContext : DebugSafeHandle { #else internal sealed class SafeFreeCertContext : SafeHandleZeroOrMinusOneIsInvalid { #endif public SafeFreeCertContext() : base(true) { } // This must be ONLY called from this file. internal void Set(IntPtr value) { this.handle = value; } protected override bool ReleaseHandle() { Interop.Crypt32.CertFreeCertificateContext(handle); return true; } } // // Implementation of handles dependable on FreeCredentialsHandle // #if DEBUG internal abstract class SafeFreeCredentials : DebugSafeHandle { #else internal abstract class SafeFreeCredentials : SafeHandle { #endif internal DateTime _expiry; internal Interop.SspiCli.CredHandle _handle; //should be always used as by ref in PInvokes parameters protected SafeFreeCredentials() : base(IntPtr.Zero, true) { _handle = default; _expiry = DateTime.MaxValue; } public override bool IsInvalid { get { return IsClosed || _handle.IsZero; } } public DateTime Expiry => _expiry; #if DEBUG public new IntPtr DangerousGetHandle() { Debug.Fail("This method should never be called for this type"); throw NotImplemented.ByDesign; } #endif public static unsafe int AcquireDefaultCredential( string package, Interop.SspiCli.CredentialUse intent, out SafeFreeCredentials outCredential) { int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, IntPtr.Zero, null, null, ref outCredential._handle, out timeStamp); if (NetEventSource.Log.IsEnabled()) NetEventSource.Verbose(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public static unsafe int AcquireCredentialsHandle( string package, Interop.SspiCli.CredentialUse intent, ref SafeSspiAuthDataHandle authdata, out SafeFreeCredentials outCredential) { outCredential = new SafeFreeCredential_SECURITY(); int errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, authdata, null, null, ref outCredential._handle, out _); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public static unsafe int AcquireCredentialsHandle( string package, Interop.SspiCli.CredentialUse intent, Interop.SspiCli.SCHANNEL_CRED* authdata, out SafeFreeCredentials outCredential) { int errorCode = -1; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, authdata, null, null, ref outCredential._handle, out _); if (NetEventSource.Log.IsEnabled()) NetEventSource.Verbose(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public static unsafe int AcquireCredentialsHandle( string package, Interop.SspiCli.CredentialUse intent, Interop.SspiCli.SCH_CREDENTIALS* authdata, out SafeFreeCredentials outCredential) { long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); int errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, authdata, null, null, ref outCredential._handle, out timeStamp); if (NetEventSource.Log.IsEnabled()) NetEventSource.Verbose(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } } internal sealed class SafeFreeCredential_SECURITY : SafeFreeCredentials { public SafeFreeCredential_SECURITY() : base() { } protected override bool ReleaseHandle() { return Interop.SspiCli.FreeCredentialsHandle(ref _handle) == 0; } } // // Implementation of handles that are dependent on DeleteSecurityContext // #if DEBUG internal abstract partial class SafeDeleteContext : DebugSafeHandle { #else internal abstract partial class SafeDeleteContext : SafeHandle { #endif private const string dummyStr = " "; private static readonly IdnMapping s_idnMapping = new IdnMapping(); protected SafeFreeCredentials? _EffectiveCredential; //------------------------------------------------------------------- internal static unsafe int InitializeSecurityContext( ref SafeFreeCredentials? inCredentials, ref SafeDeleteSslContext? refContext, string? targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, InputSecurityBuffers inSecBuffers, ref SecurityBuffer outSecBuffer, ref Interop.SspiCli.ContextFlags outFlags) { ArgumentNullException.ThrowIfNull(inCredentials); Debug.Assert(inSecBuffers.Count <= 3); Interop.SspiCli.SecBufferDesc inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Count); Interop.SspiCli.SecBufferDesc outSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); // Actually, this is returned in outFlags. bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; bool isContextAbsent = true; if (refContext != null) { isContextAbsent = refContext._handle.IsZero; } // Optional output buffer that may need to be freed. IntPtr outoutBuffer = IntPtr.Zero; try { Span<Interop.SspiCli.SecBuffer> inUnmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[3]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) fixed (void* pinnedToken0 = inSecBuffers._item0.Token) fixed (void* pinnedToken1 = inSecBuffers._item1.Token) fixed (void* pinnedToken2 = inSecBuffers._item2.Token) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr; // Updated pvBuffer with pinned address. UnmanagedToken takes precedence. if (inSecBuffers.Count > 2) { inUnmanagedBuffer[2].BufferType = inSecBuffers._item2.Type; if (inSecBuffers._item2.UnmanagedToken != null) { Debug.Assert(inSecBuffers._item2.Type == SecurityBufferType.SECBUFFER_CHANNEL_BINDINGS); inUnmanagedBuffer[2].pvBuffer = (IntPtr)inSecBuffers._item2.UnmanagedToken.DangerousGetHandle(); inUnmanagedBuffer[2].cbBuffer = ((ChannelBinding)inSecBuffers._item2.UnmanagedToken).Size; } else { inUnmanagedBuffer[2].cbBuffer = inSecBuffers._item2.Token.Length; inUnmanagedBuffer[2].pvBuffer = (IntPtr)pinnedToken2; } } if (inSecBuffers.Count > 1) { inUnmanagedBuffer[1].BufferType = inSecBuffers._item1.Type; if (inSecBuffers._item1.UnmanagedToken != null) { Debug.Assert(inSecBuffers._item1.Type == SecurityBufferType.SECBUFFER_CHANNEL_BINDINGS); inUnmanagedBuffer[1].pvBuffer = (IntPtr)inSecBuffers._item1.UnmanagedToken.DangerousGetHandle(); inUnmanagedBuffer[1].cbBuffer = ((ChannelBinding)inSecBuffers._item1.UnmanagedToken).Size; } else { inUnmanagedBuffer[1].cbBuffer = inSecBuffers._item1.Token.Length; inUnmanagedBuffer[1].pvBuffer = (IntPtr)pinnedToken1; } } if (inSecBuffers.Count > 0) { inUnmanagedBuffer[0].BufferType = inSecBuffers._item0.Type; if (inSecBuffers._item0.UnmanagedToken != null) { Debug.Assert(inSecBuffers._item0.Type == SecurityBufferType.SECBUFFER_CHANNEL_BINDINGS); inUnmanagedBuffer[0].pvBuffer = (IntPtr)inSecBuffers._item0.UnmanagedToken.DangerousGetHandle(); inUnmanagedBuffer[0].cbBuffer = ((ChannelBinding)inSecBuffers._item0.UnmanagedToken).Size; } else { inUnmanagedBuffer[0].cbBuffer = inSecBuffers._item0.Token.Length; inUnmanagedBuffer[0].pvBuffer = (IntPtr)pinnedToken0; } } fixed (byte* pinnedOutBytes = outSecBuffer.token) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. Interop.SspiCli.SecBuffer outUnmanagedBuffer = default; outSecurityBufferDescriptor.pBuffers = &outUnmanagedBuffer; outUnmanagedBuffer.cbBuffer = outSecBuffer.size; outUnmanagedBuffer.BufferType = outSecBuffer.type; outUnmanagedBuffer.pvBuffer = outSecBuffer.token == null || outSecBuffer.token.Length == 0 ? IntPtr.Zero : (IntPtr)(pinnedOutBytes + outSecBuffer.offset); if (refContext == null || refContext.IsInvalid) { // Previous versions unconditionally built a new "refContext" here, but would pass // incorrect arguments to InitializeSecurityContextW in cases where an "contextHandle" was // already present and non-zero. if (isContextAbsent) refContext = new SafeDeleteSslContext(); } if (targetName == null || targetName.Length == 0) { targetName = dummyStr; } string punyCode = s_idnMapping.GetAscii(targetName); fixed (char* namePtr = punyCode) { errorCode = MustRunInitializeSecurityContext( ref inCredentials, isContextAbsent, (byte*)(((object)targetName == (object)dummyStr) ? null : namePtr), inFlags, endianness, &inSecurityBufferDescriptor, refContext!, ref outSecurityBufferDescriptor, ref outFlags, null); if (isSspiAllocated) { outoutBuffer = outUnmanagedBuffer.pvBuffer; } // Get unmanaged buffer with index 0 as the only one passed into PInvoke. outSecBuffer.size = outUnmanagedBuffer.cbBuffer; outSecBuffer.type = outUnmanagedBuffer.BufferType; outSecBuffer.token = outSecBuffer.size > 0 ? new Span<byte>((byte*)outUnmanagedBuffer.pvBuffer, outUnmanagedBuffer.cbBuffer).ToArray() : null; if (inSecBuffers.Count > 1 && inUnmanagedBuffer[1].BufferType == SecurityBufferType.SECBUFFER_EXTRA && inSecBuffers._item1.Type == SecurityBufferType.SECBUFFER_EMPTY) { // OS function did not use all provided data and turned EMPTY to EXTRA // https://docs.microsoft.com/en-us/windows/win32/secauthn/extra-buffers-returned-by-schannel int leftover = inUnmanagedBuffer[1].cbBuffer; int processed = inSecBuffers._item0.Token.Length - inUnmanagedBuffer[1].cbBuffer; /* skip over processed data and try it again. */ inUnmanagedBuffer[0].cbBuffer = leftover; inUnmanagedBuffer[0].pvBuffer = inUnmanagedBuffer[0].pvBuffer + processed; inUnmanagedBuffer[1].BufferType = SecurityBufferType.SECBUFFER_EMPTY; inUnmanagedBuffer[1].cbBuffer = 0; outUnmanagedBuffer.cbBuffer = 0; if (outoutBuffer != IntPtr.Zero) { Interop.SspiCli.FreeContextBuffer(outoutBuffer); outoutBuffer = IntPtr.Zero; } errorCode = MustRunInitializeSecurityContext( ref inCredentials, isContextAbsent, (byte*)(((object)targetName == (object)dummyStr) ? null : namePtr), inFlags, endianness, &inSecurityBufferDescriptor, refContext!, ref outSecurityBufferDescriptor, ref outFlags, null); if (isSspiAllocated) { outoutBuffer = outUnmanagedBuffer.pvBuffer; } if (outUnmanagedBuffer.cbBuffer > 0) { if (outSecBuffer.size == 0) { // We did not get anything in the first round. outSecBuffer.size = outUnmanagedBuffer.cbBuffer; outSecBuffer.type = outUnmanagedBuffer.BufferType; outSecBuffer.token = new Span<byte>((byte*)outUnmanagedBuffer.pvBuffer, outUnmanagedBuffer.cbBuffer).ToArray(); } else { byte[] buffer = new byte[outSecBuffer.size + outUnmanagedBuffer.cbBuffer]; Buffer.BlockCopy(outSecBuffer.token!, 0, buffer, 0, outSecBuffer.size); new Span<byte>((byte*)outUnmanagedBuffer.pvBuffer, outUnmanagedBuffer.cbBuffer).CopyTo(new Span<byte>(buffer, outSecBuffer.size, outUnmanagedBuffer.cbBuffer)); outSecBuffer.size = buffer.Length; outSecBuffer.token = buffer; } } if (inUnmanagedBuffer[1].BufferType == SecurityBufferType.SECBUFFER_EXTRA) { // we are left with unprocessed data again. fail with SEC_E_INCOMPLETE_MESSAGE hResult. errorCode = unchecked((int)0x80090318); } } } } } } finally { if (outoutBuffer != IntPtr.Zero) { Interop.SspiCli.FreeContextBuffer(outoutBuffer); } } return errorCode; } // // After PInvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned. // private static unsafe int MustRunInitializeSecurityContext( ref SafeFreeCredentials inCredentials, bool isContextAbsent, byte* targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, Interop.SspiCli.SecBufferDesc* inputBuffer, SafeDeleteContext outContext, ref Interop.SspiCli.SecBufferDesc outputBuffer, ref Interop.SspiCli.ContextFlags attributes, SafeFreeContextBuffer? handleTemplate) { int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; try { bool ignore = false; inCredentials.DangerousAddRef(ref ignore); outContext.DangerousAddRef(ref ignore); Interop.SspiCli.CredHandle credentialHandle = inCredentials._handle; long timeStamp; // Now that "outContext" (or "refContext" by the caller) references an actual handle (and cannot // be closed until it is released below), point "inContextPtr" to its embedded handle (or // null if the embedded handle has not yet been initialized). Interop.SspiCli.CredHandle contextHandle = outContext._handle; void* inContextPtr = contextHandle.IsZero ? null : &contextHandle; // The "isContextAbsent" supplied by the caller is generally correct but was computed without proper // synchronization. Rewrite the indicator now that the final "inContext" is known, update if necessary. isContextAbsent = (inContextPtr == null); errorCode = Interop.SspiCli.InitializeSecurityContextW( ref credentialHandle, inContextPtr, targetName, inFlags, 0, endianness, inputBuffer, 0, ref outContext._handle, ref outputBuffer, ref attributes, out timeStamp); } finally { // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle outContext._EffectiveCredential?.DangerousRelease(); outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); } // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes handleTemplate.Set(((Interop.SspiCli.SecBuffer*)outputBuffer.pBuffers)->pvBuffer); if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } if (isContextAbsent && (errorCode & 0x80000000) != 0) { // an error on the first call, need to set the out handle to invalid value outContext._handle.SetToInvalid(); } return errorCode; } //------------------------------------------------------------------- internal static unsafe int AcceptSecurityContext( ref SafeFreeCredentials? inCredentials, ref SafeDeleteSslContext? refContext, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, InputSecurityBuffers inSecBuffers, ref SecurityBuffer outSecBuffer, ref Interop.SspiCli.ContextFlags outFlags) { ArgumentNullException.ThrowIfNull(inCredentials); Debug.Assert(inSecBuffers.Count <= 3); Interop.SspiCli.SecBufferDesc inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Count); Interop.SspiCli.SecBufferDesc outSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(count: 2); // Actually, this is returned in outFlags. bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; bool isContextAbsent = true; if (refContext != null) { isContextAbsent = refContext._handle.IsZero; } Span<Interop.SspiCli.SecBuffer> outUnmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[2]; outUnmanagedBuffer[1].pvBuffer = IntPtr.Zero; try { // Allocate always maximum to allow better code optimization. Span<Interop.SspiCli.SecBuffer> inUnmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[3]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer) fixed (void* pinnedToken0 = inSecBuffers._item0.Token) fixed (void* pinnedToken1 = inSecBuffers._item1.Token) fixed (void* pinnedToken2 = inSecBuffers._item2.Token) { inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr; // Updated pvBuffer with pinned address. UnmanagedToken takes precedence. if (inSecBuffers.Count > 2) { inUnmanagedBuffer[2].BufferType = inSecBuffers._item2.Type; if (inSecBuffers._item2.UnmanagedToken != null) { Debug.Assert(inSecBuffers._item2.Type == SecurityBufferType.SECBUFFER_CHANNEL_BINDINGS); inUnmanagedBuffer[2].pvBuffer = (IntPtr)inSecBuffers._item2.UnmanagedToken.DangerousGetHandle(); inUnmanagedBuffer[2].cbBuffer = ((ChannelBinding)inSecBuffers._item2.UnmanagedToken).Size; } else { inUnmanagedBuffer[2].cbBuffer = inSecBuffers._item2.Token.Length; inUnmanagedBuffer[2].pvBuffer = (IntPtr)pinnedToken2; } } if (inSecBuffers.Count > 1) { inUnmanagedBuffer[1].BufferType = inSecBuffers._item1.Type; if (inSecBuffers._item1.UnmanagedToken != null) { Debug.Assert(inSecBuffers._item1.Type == SecurityBufferType.SECBUFFER_CHANNEL_BINDINGS); inUnmanagedBuffer[1].pvBuffer = (IntPtr)inSecBuffers._item1.UnmanagedToken.DangerousGetHandle(); inUnmanagedBuffer[1].cbBuffer = ((ChannelBinding)inSecBuffers._item1.UnmanagedToken).Size; } else { inUnmanagedBuffer[1].cbBuffer = inSecBuffers._item1.Token.Length; inUnmanagedBuffer[1].pvBuffer = (IntPtr)pinnedToken1; } } if (inSecBuffers.Count > 0) { inUnmanagedBuffer[0].BufferType = inSecBuffers._item0.Type; if (inSecBuffers._item0.UnmanagedToken != null) { Debug.Assert(inSecBuffers._item0.Type == SecurityBufferType.SECBUFFER_CHANNEL_BINDINGS); inUnmanagedBuffer[0].pvBuffer = (IntPtr)inSecBuffers._item0.UnmanagedToken.DangerousGetHandle(); inUnmanagedBuffer[0].cbBuffer = ((ChannelBinding)inSecBuffers._item0.UnmanagedToken).Size; } else { inUnmanagedBuffer[0].cbBuffer = inSecBuffers._item0.Token.Length; inUnmanagedBuffer[0].pvBuffer = (IntPtr)pinnedToken0; } } fixed (byte* pinnedOutBytes = outSecBuffer.token) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. outSecurityBufferDescriptor.pBuffers = outUnmanagedBufferPtr; // Copy the SecurityBuffer content into unmanaged place holder. outUnmanagedBuffer[0].cbBuffer = outSecBuffer.size; outUnmanagedBuffer[0].BufferType = outSecBuffer.type; outUnmanagedBuffer[0].pvBuffer = outSecBuffer.token == null || outSecBuffer.token.Length == 0 ? IntPtr.Zero : (IntPtr)(pinnedOutBytes + outSecBuffer.offset); outUnmanagedBuffer[1].cbBuffer = 0; outUnmanagedBuffer[1].BufferType = SecurityBufferType.SECBUFFER_ALERT; if (refContext == null || refContext.IsInvalid) { // Previous versions unconditionally built a new "refContext" here, but would pass // incorrect arguments to AcceptSecurityContext in cases where an "contextHandle" was // already present and non-zero. if (isContextAbsent) refContext = new SafeDeleteSslContext(); } errorCode = MustRunAcceptSecurityContext_SECURITY( ref inCredentials, isContextAbsent, &inSecurityBufferDescriptor, inFlags, endianness, refContext!, ref outSecurityBufferDescriptor, ref outFlags, null); // No data written out but there is Alert int index = outUnmanagedBuffer[0].cbBuffer == 0 && outUnmanagedBuffer[1].cbBuffer > 0 ? 1 : 0; outSecBuffer.size = outUnmanagedBuffer[index].cbBuffer; outSecBuffer.type = outUnmanagedBuffer[index].BufferType; outSecBuffer.token = outSecBuffer.size > 0 ? new Span<byte>((byte*)outUnmanagedBuffer[index].pvBuffer, outUnmanagedBuffer[0].cbBuffer).ToArray() : null; if (inSecBuffers.Count > 1 && inUnmanagedBuffer[1].BufferType == SecurityBufferType.SECBUFFER_EXTRA && inSecBuffers._item1.Type == SecurityBufferType.SECBUFFER_EMPTY) { // OS function did not use all provided data and turned EMPTY to EXTRA // https://docs.microsoft.com/en-us/windows/win32/secauthn/extra-buffers-returned-by-schannel int leftover = inUnmanagedBuffer[1].cbBuffer; int processed = inSecBuffers._item0.Token.Length - inUnmanagedBuffer[1].cbBuffer; /* skip over processed data and try it again. */ inUnmanagedBuffer[0].cbBuffer = leftover; inUnmanagedBuffer[0].pvBuffer = inUnmanagedBuffer[0].pvBuffer + processed; inUnmanagedBuffer[1].BufferType = SecurityBufferType.SECBUFFER_EMPTY; inUnmanagedBuffer[1].cbBuffer = 0; outUnmanagedBuffer[0].cbBuffer = 0; if (isSspiAllocated && outUnmanagedBuffer[0].pvBuffer != IntPtr.Zero) { Interop.SspiCli.FreeContextBuffer(outUnmanagedBuffer[0].pvBuffer); outUnmanagedBuffer[0].pvBuffer = IntPtr.Zero; } errorCode = MustRunAcceptSecurityContext_SECURITY( ref inCredentials, isContextAbsent, &inSecurityBufferDescriptor, inFlags, endianness, refContext!, ref outSecurityBufferDescriptor, ref outFlags, null); index = outUnmanagedBuffer[0].cbBuffer == 0 && outUnmanagedBuffer[1].cbBuffer > 0 ? 1 : 0; if (outUnmanagedBuffer[index].cbBuffer > 0) { if (outSecBuffer.size == 0) { // We did not get anything in the first round. outSecBuffer.size = outUnmanagedBuffer[index].cbBuffer; outSecBuffer.type = outUnmanagedBuffer[index].BufferType; outSecBuffer.token = new Span<byte>((byte*)outUnmanagedBuffer[index].pvBuffer, outUnmanagedBuffer[index].cbBuffer).ToArray(); } else { byte[] buffer = new byte[outSecBuffer.size + outUnmanagedBuffer[index].cbBuffer]; Buffer.BlockCopy(outSecBuffer.token!, 0, buffer, 0, outSecBuffer.size); new Span<byte>((byte*)outUnmanagedBuffer[index].pvBuffer, outUnmanagedBuffer[index].cbBuffer).CopyTo(new Span<byte>(buffer, outSecBuffer.size, outUnmanagedBuffer[index].cbBuffer)); outSecBuffer.size = buffer.Length; outSecBuffer.token = buffer; } } if (inUnmanagedBuffer[1].BufferType == SecurityBufferType.SECBUFFER_EXTRA) { // we are left with unprocessed data again. fail with SEC_E_INCOMPLETE_MESSAGE hResult. errorCode = unchecked((int)0x80090318); } } } } } finally { if (isSspiAllocated && outUnmanagedBuffer[0].pvBuffer != IntPtr.Zero) { Interop.SspiCli.FreeContextBuffer(outUnmanagedBuffer[0].pvBuffer); } if (outUnmanagedBuffer[1].pvBuffer != IntPtr.Zero) { Interop.SspiCli.FreeContextBuffer(outUnmanagedBuffer[1].pvBuffer); } } return errorCode; } // // After PInvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned. // private static unsafe int MustRunAcceptSecurityContext_SECURITY( ref SafeFreeCredentials inCredentials, bool isContextAbsent, Interop.SspiCli.SecBufferDesc* inputBuffer, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, SafeDeleteContext outContext, ref Interop.SspiCli.SecBufferDesc outputBuffer, ref Interop.SspiCli.ContextFlags outFlags, SafeFreeContextBuffer? handleTemplate) { int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; // Run the body of this method as a non-interruptible block. try { bool ignore = false; inCredentials.DangerousAddRef(ref ignore); outContext.DangerousAddRef(ref ignore); Interop.SspiCli.CredHandle credentialHandle = inCredentials._handle; long timeStamp; // Now that "outContext" (or "refContext" by the caller) references an actual handle (and cannot // be closed until it is released below), point "inContextPtr" to its embedded handle (or // null if the embedded handle has not yet been initialized). Interop.SspiCli.CredHandle contextHandle = outContext._handle; void* inContextPtr = contextHandle.IsZero ? null : &contextHandle; // The "isContextAbsent" supplied by the caller is generally correct but was computed without proper // synchronization. Rewrite the indicator now that the final "inContext" is known, update if necessary. isContextAbsent = (inContextPtr == null); errorCode = Interop.SspiCli.AcceptSecurityContext( ref credentialHandle, inContextPtr, inputBuffer, inFlags, endianness, ref outContext._handle, ref outputBuffer, ref outFlags, out timeStamp); } finally { // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle. outContext._EffectiveCredential?.DangerousRelease(); outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); } // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes. handleTemplate.Set(((Interop.SspiCli.SecBuffer*)outputBuffer.pBuffers)->pvBuffer); if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } if (isContextAbsent && (errorCode & 0x80000000) != 0) { // An error on the first call, need to set the out handle to invalid value. outContext._handle.SetToInvalid(); } return errorCode; } internal static unsafe int CompleteAuthToken( ref SafeDeleteSslContext? refContext, in SecurityBuffer inSecBuffer) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"refContext = {refContext}, inSecBuffer = {inSecBuffer}"); var inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; Interop.SspiCli.SecBuffer inUnmanagedBuffer = default; inSecurityBufferDescriptor.pBuffers = &inUnmanagedBuffer; fixed (byte* pinnedToken = inSecBuffer.token) { inUnmanagedBuffer.cbBuffer = inSecBuffer.size; inUnmanagedBuffer.BufferType = inSecBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. inUnmanagedBuffer.pvBuffer = inSecBuffer.unmanagedToken != null ? inSecBuffer.unmanagedToken.DangerousGetHandle() : inSecBuffer.token == null || inSecBuffer.token.Length == 0 ? IntPtr.Zero : (IntPtr)(pinnedToken + inSecBuffer.offset); Interop.SspiCli.CredHandle contextHandle = refContext != null ? refContext._handle : default; if (refContext == null || refContext.IsInvalid) { // Previous versions unconditionally built a new "refContext" here, but would pass // incorrect arguments to CompleteAuthToken in cases where a nonzero "contextHandle" was // already present. In these cases, allow the "refContext" to flow through unmodified // (which will generate an ObjectDisposedException below). In all other cases, continue to // build a new "refContext" in an attempt to maximize compat. if (contextHandle.IsZero) { refContext = new SafeDeleteSslContext(); } } bool gotRef = false; try { refContext!.DangerousAddRef(ref gotRef); errorCode = Interop.SspiCli.CompleteAuthToken(contextHandle.IsZero ? null : &contextHandle, ref inSecurityBufferDescriptor); } finally { if (gotRef) { refContext!.DangerousRelease(); } } } return errorCode; } internal static unsafe int ApplyControlToken( ref SafeDeleteContext? refContext, in SecurityBuffer inSecBuffer) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"refContext = {refContext}, inSecBuffer = {inSecBuffer}"); int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; // Fix Descriptor pointer that points to unmanaged SecurityBuffers. fixed (byte* pinnedInSecBufferToken = inSecBuffer.token) { var inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); Interop.SspiCli.SecBuffer inUnmanagedBuffer = default; inSecurityBufferDescriptor.pBuffers = &inUnmanagedBuffer; inUnmanagedBuffer.cbBuffer = inSecBuffer.size; inUnmanagedBuffer.BufferType = inSecBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. inUnmanagedBuffer.pvBuffer = inSecBuffer.unmanagedToken != null ? inSecBuffer.unmanagedToken.DangerousGetHandle() : inSecBuffer.token == null || inSecBuffer.token.Length == 0 ? IntPtr.Zero : (IntPtr)(pinnedInSecBufferToken + inSecBuffer.offset); Interop.SspiCli.CredHandle contextHandle = refContext != null ? refContext._handle : default; if (refContext == null || refContext.IsInvalid) { // Previous versions unconditionally built a new "refContext" here, but would pass // incorrect arguments to ApplyControlToken in cases where a nonzero "contextHandle" was // already present. In these cases, allow the "refContext" to flow through unmodified // (which will generate an ObjectDisposedException below). In all other cases, continue to // build a new "refContext" in an attempt to maximize compat. if (contextHandle.IsZero) { refContext = new SafeDeleteSslContext(); } } bool gotRef = false; try { refContext!.DangerousAddRef(ref gotRef); errorCode = Interop.SspiCli.ApplyControlToken(contextHandle.IsZero ? null : &contextHandle, ref inSecurityBufferDescriptor); } finally { if (gotRef) { refContext!.DangerousRelease(); } } } return errorCode; } } internal sealed class SafeDeleteSslContext : SafeDeleteContext { public SafeDeleteSslContext() : base() { } protected override bool ReleaseHandle() { this._EffectiveCredential?.DangerousRelease(); return Interop.SspiCli.DeleteSecurityContext(ref _handle) == 0; } } // Based on SafeFreeContextBuffer. internal abstract class SafeFreeContextBufferChannelBinding : ChannelBinding { private int _size; public override int Size { get { return _size; } } public override bool IsInvalid { get { return handle == new IntPtr(0) || handle == new IntPtr(-1); } } internal unsafe void Set(IntPtr value) { this.handle = value; } internal static SafeFreeContextBufferChannelBinding CreateEmptyHandle() { return new SafeFreeContextBufferChannelBinding_SECURITY(); } public static unsafe int QueryContextChannelBinding(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, SecPkgContext_Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle) { int status = (int)Interop.SECURITY_STATUS.InvalidHandle; // SCHANNEL only supports SECPKG_ATTR_ENDPOINT_BINDINGS and SECPKG_ATTR_UNIQUE_BINDINGS which // map to our enum ChannelBindingKind.Endpoint and ChannelBindingKind.Unique. if (contextAttribute != Interop.SspiCli.ContextAttribute.SECPKG_ATTR_ENDPOINT_BINDINGS && contextAttribute != Interop.SspiCli.ContextAttribute.SECPKG_ATTR_UNIQUE_BINDINGS) { return status; } try { bool ignore = false; phContext.DangerousAddRef(ref ignore); status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer); } finally { phContext.DangerousRelease(); } if (status == 0 && refHandle != null) { refHandle.Set((*buffer).Bindings); refHandle._size = (*buffer).BindingsLength; } if (status != 0) { refHandle?.SetHandleAsInvalid(); } return status; } public override string? ToString() { if (IsInvalid) { return null; } var bytes = new byte[_size]; Marshal.Copy(handle, bytes, 0, bytes.Length); return BitConverter.ToString(bytes).Replace('-', ' '); } } internal sealed class SafeFreeContextBufferChannelBinding_SECURITY : SafeFreeContextBufferChannelBinding { protected override bool ReleaseHandle() { return Interop.SspiCli.FreeContextBuffer(handle) == 0; } } }
1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/Common/src/System/Net/Security/Unix/SafeFreeCredentials.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.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; namespace System.Net.Security { // // Implementation of handles dependable on FreeCredentialsHandle // #if DEBUG internal abstract class SafeFreeCredentials : DebugSafeHandle { #else internal abstract class SafeFreeCredentials : SafeHandle { #endif protected SafeFreeCredentials(IntPtr handle, bool ownsHandle) : base(handle, ownsHandle) { } } }
// 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.ConstrainedExecution; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; namespace System.Net.Security { // // Implementation of handles dependable on FreeCredentialsHandle // #if DEBUG internal abstract class SafeFreeCredentials : DebugSafeHandle { #else internal abstract class SafeFreeCredentials : SafeHandle { #endif internal DateTime _expiry; public DateTime Expiry => _expiry; protected SafeFreeCredentials(IntPtr handle, bool ownsHandle) : base(handle, ownsHandle) { _expiry = DateTime.MaxValue; } } }
1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Net.Security/src/System/Net/Security/SecureChannel.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.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Security; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace System.Net.Security { // SecureChannel - a wrapper on SSPI based functionality. // Provides an additional abstraction layer over SSPI for SslStream. internal sealed class SecureChannel { private SafeFreeCredentials? _credentialsHandle; private SafeDeleteSslContext? _securityContext; private SslConnectionInfo? _connectionInfo; private X509Certificate? _selectedClientCertificate; private X509Certificate2? _remoteCertificate; private bool _remoteCertificateExposed; // These are the MAX encrypt buffer output sizes, not the actual sizes. private int _headerSize = 5; //ATTN must be set to at least 5 by default private int _trailerSize = 16; private int _maxDataSize = 16354; private bool _refreshCredentialNeeded; private readonly SslAuthenticationOptions _sslAuthenticationOptions; private SslApplicationProtocol _negotiatedApplicationProtocol; private static readonly Oid s_serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.1"); private static readonly Oid s_clientAuthOid = new Oid("1.3.6.1.5.5.7.3.2", "1.3.6.1.5.5.7.3.2"); private SslStream? _ssl; internal SecureChannel(SslAuthenticationOptions sslAuthenticationOptions, SslStream sslStream) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.SecureChannelCtor(this, sslStream, sslAuthenticationOptions.TargetHost!, sslAuthenticationOptions.ClientCertificates, sslAuthenticationOptions.EncryptionPolicy); SslStreamPal.VerifyPackageInfo(); Debug.Assert(sslAuthenticationOptions.TargetHost != null, "sslAuthenticationOptions.TargetHost == null"); _securityContext = null; _refreshCredentialNeeded = true; _sslAuthenticationOptions = sslAuthenticationOptions; _ssl = sslStream; } // // SecureChannel properties // // LocalServerCertificate - local certificate for server mode channel // LocalClientCertificate - selected certificated used in the client channel mode otherwise null // IsRemoteCertificateAvailable - true if the remote side has provided a certificate // HeaderSize - Header & trailer sizes used in the TLS stream // TrailerSize - // internal X509Certificate? LocalServerCertificate { get { return _sslAuthenticationOptions.CertificateContext?.Certificate; } } internal X509Certificate? LocalClientCertificate { get { return _selectedClientCertificate; } } internal bool IsRemoteCertificateAvailable { get { return _remoteCertificate != null; } } internal X509Certificate? RemoteCertificate { get { _remoteCertificateExposed = true; return _remoteCertificate; } } internal ChannelBinding? GetChannelBinding(ChannelBindingKind kind) { ChannelBinding? result = null; if (_securityContext != null) { result = SslStreamPal.QueryContextChannelBinding(_securityContext, kind); } return result; } internal X509RevocationMode CheckCertRevocationStatus { get { return _sslAuthenticationOptions.CertificateRevocationCheckMode; } } internal int MaxDataSize { get { return _maxDataSize; } } internal SslConnectionInfo? ConnectionInfo { get { return _connectionInfo; } } internal bool IsValidContext { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return !(_securityContext == null || _securityContext.IsInvalid); } } internal bool IsServer { get { return _sslAuthenticationOptions.IsServer; } } internal bool RemoteCertRequired { get { return _sslAuthenticationOptions.RemoteCertRequired; } } internal SslApplicationProtocol NegotiatedApplicationProtocol { get { return _negotiatedApplicationProtocol; } } internal void SetRefreshCredentialNeeded() { _refreshCredentialNeeded = true; } internal void Close() { if (!_remoteCertificateExposed) { _remoteCertificate?.Dispose(); _remoteCertificate = null; } _securityContext?.Dispose(); _credentialsHandle?.Dispose(); _ssl = null; GC.SuppressFinalize(this); } // // SECURITY: we open a private key container on behalf of the caller // and we require the caller to have permission associated with that operation. // internal static X509Certificate2? FindCertificateWithPrivateKey(object instance, bool isServer, X509Certificate certificate) { if (certificate == null) { return null; } if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.LocatingPrivateKey(certificate, instance); try { // Protecting from X509Certificate2 derived classes. X509Certificate2? certEx = MakeEx(certificate); if (certEx != null) { if (certEx.HasPrivateKey) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.CertIsType2(instance); return certEx; } if (!object.ReferenceEquals(certificate, certEx)) { certEx.Dispose(); } } X509Certificate2Collection collectionEx; string certHash = certEx!.Thumbprint; // ELSE Try the MY user and machine stores for private key check. // For server side mode MY machine store takes priority. X509Store? store = CertificateValidationPal.EnsureStoreOpened(isServer); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.FoundCertInStore(isServer, instance); return collectionEx[0]; } } store = CertificateValidationPal.EnsureStoreOpened(!isServer); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.FoundCertInStore(!isServer, instance); return collectionEx[0]; } } } catch (CryptographicException) { } if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.NotFoundCertInStore(instance); return null; } private static X509Certificate2? MakeEx(X509Certificate certificate) { Debug.Assert(certificate != null, "certificate != null"); if (certificate.GetType() == typeof(X509Certificate2)) { return (X509Certificate2)certificate; } X509Certificate2? certificateEx = null; try { if (certificate.Handle != IntPtr.Zero) { certificateEx = new X509Certificate2(certificate); } } catch (SecurityException) { } catch (CryptographicException) { } return certificateEx; } // // Get certificate_authorities list, according to RFC 5246, Section 7.4.4. // Used only by client SSL code, never returns null. // private string[] GetRequestCertificateAuthorities() { string[] issuers = Array.Empty<string>(); if (IsValidContext) { issuers = CertificateValidationPal.GetRequestCertificateAuthorities(_securityContext!); } return issuers; } internal X509Certificate2? SelectClientCertificate(out bool sessionRestartAttempt) { sessionRestartAttempt = false; X509Certificate? clientCertificate = null; // candidate certificate that can come from the user callback or be guessed when targeting a session restart. X509Certificate2? selectedCert = null; // final selected cert (ensured that it does have private key with it). List<X509Certificate>? filteredCerts = null; // This is an intermediate client certs collection that try to use if no selectedCert is available yet. string[] issuers; // This is a list of issuers sent by the server, only valid if we do know what the server cert is. if (_sslAuthenticationOptions.CertSelectionDelegate != null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Calling CertificateSelectionCallback"); X509Certificate2? remoteCert = null; try { issuers = GetRequestCertificateAuthorities(); remoteCert = CertificateValidationPal.GetRemoteCertificate(_securityContext!); if (_sslAuthenticationOptions.ClientCertificates == null) { _sslAuthenticationOptions.ClientCertificates = new X509CertificateCollection(); } clientCertificate = _sslAuthenticationOptions.CertSelectionDelegate(_sslAuthenticationOptions.TargetHost!, _sslAuthenticationOptions.ClientCertificates, remoteCert, issuers); } finally { remoteCert?.Dispose(); } if (clientCertificate != null) { if (_credentialsHandle == null) { sessionRestartAttempt = true; } EnsureInitialized(ref filteredCerts).Add(clientCertificate); if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.CertificateFromDelegate(this); } else { if (_sslAuthenticationOptions.ClientCertificates == null || _sslAuthenticationOptions.ClientCertificates.Count == 0) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.NoDelegateNoClientCert(this); sessionRestartAttempt = true; } else { if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.NoDelegateButClientCert(this); } } } else if (_credentialsHandle == null && _sslAuthenticationOptions.ClientCertificates != null && _sslAuthenticationOptions.ClientCertificates.Count > 0) { // This is where we attempt to restart a session by picking the FIRST cert from the collection. // Otherwise it is either server sending a client cert request or the session is renegotiated. clientCertificate = _sslAuthenticationOptions.ClientCertificates[0]; sessionRestartAttempt = true; if (clientCertificate != null) { EnsureInitialized(ref filteredCerts).Add(clientCertificate); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.AttemptingRestartUsingCert(clientCertificate, this); } else if (_sslAuthenticationOptions.ClientCertificates != null && _sslAuthenticationOptions.ClientCertificates.Count > 0) { // // This should be a server request for the client cert sent over currently anonymous sessions. // issuers = GetRequestCertificateAuthorities(); if (NetEventSource.Log.IsEnabled()) { if (issuers == null || issuers.Length == 0) { NetEventSource.Log.NoIssuersTryAllCerts(this); } else { NetEventSource.Log.LookForMatchingCerts(issuers.Length, this); } } for (int i = 0; i < _sslAuthenticationOptions.ClientCertificates.Count; ++i) { // // Make sure we add only if the cert matches one of the issuers. // If no issuers were sent and then try all client certs starting with the first one. // if (issuers != null && issuers.Length != 0) { X509Certificate2? certificateEx = null; X509Chain? chain = null; try { certificateEx = MakeEx(_sslAuthenticationOptions.ClientCertificates[i]); if (certificateEx == null) { continue; } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Root cert: {certificateEx}"); chain = new X509Chain(); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreInvalidName; chain.Build(certificateEx); bool found = false; // // We ignore any errors happened with chain. // if (chain.ChainElements.Count > 0) { int elementsCount = chain.ChainElements.Count; for (int ii = 0; ii < elementsCount; ++ii) { string issuer = chain.ChainElements[ii].Certificate!.Issuer; found = Array.IndexOf(issuers, issuer) != -1; if (found) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Matched {issuer}"); break; } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"No match: {issuer}"); } } if (!found) { continue; } } finally { if (chain != null) { chain.Dispose(); int elementsCount = chain.ChainElements.Count; for (int element = 0; element < elementsCount; element++) { chain.ChainElements[element].Certificate!.Dispose(); } } if (certificateEx != null && (object)certificateEx != (object)_sslAuthenticationOptions.ClientCertificates[i]) { certificateEx.Dispose(); } } } if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.SelectedCert(_sslAuthenticationOptions.ClientCertificates[i], this); EnsureInitialized(ref filteredCerts).Add(_sslAuthenticationOptions.ClientCertificates[i]); } } clientCertificate = null; if (NetEventSource.Log.IsEnabled()) { if (filteredCerts != null && filteredCerts.Count != 0) { NetEventSource.Log.CertsAfterFiltering(filteredCerts.Count, this); NetEventSource.Log.FindingMatchingCerts(this); } else { NetEventSource.Log.CertsAfterFiltering(0, this); NetEventSource.Info(this, "No client certificate to choose from"); } } // // ATTN: When the client cert was returned by the user callback OR it was guessed AND it has no private key, // THEN anonymous (no client cert) credential will be used. // // SECURITY: Accessing X509 cert Credential is disabled for semitrust. // We no longer need to demand for unmanaged code permissions. // FindCertificateWithPrivateKey should do the right demand for us. if (filteredCerts != null) { for (int i = 0; i < filteredCerts.Count; ++i) { clientCertificate = filteredCerts[i]; if ((selectedCert = FindCertificateWithPrivateKey(this, _sslAuthenticationOptions.IsServer, clientCertificate)) != null) { break; } clientCertificate = null; selectedCert = null; } } Debug.Assert((object?)clientCertificate == (object?)selectedCert || clientCertificate!.Equals(selectedCert), "'selectedCert' does not match 'clientCertificate'."); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Selected cert = {selectedCert}"); _selectedClientCertificate = clientCertificate; return selectedCert; } /*++ AcquireCredentials - Attempts to find Client Credential Information, that can be sent to the server. In our case, this is only Client Certificates, that we have Credential Info. How it works: case 0: Cert Selection delegate is present Always use its result as the client cert answer. Try to use cached credential handle whenever feasible. Do not use cached anonymous creds if the delegate has returned null and the collection is not empty (allow responding with the cert later). case 1: Certs collection is empty Always use the same statically acquired anonymous SSL Credential case 2: Before our Connection with the Server If we have a cached credential handle keyed by first X509Certificate **content** in the passed collection, then we use that cached credential and hoping to restart a session. Otherwise create a new anonymous (allow responding with the cert later). case 3: After our Connection with the Server (i.e. during handshake or re-handshake) The server has requested that we send it a Certificate then we Enumerate a list of server sent Issuers trying to match against our list of Certificates, the first match is sent to the server. Once we got a cert we again try to match cached credential handle if possible. This will not restart a session but helps minimizing the number of handles we create. In the case of an error getting a Certificate or checking its private Key we fall back to the behavior of having no certs, case 1. Returns: True if cached creds were used, false otherwise. --*/ private bool AcquireClientCredentials(ref byte[]? thumbPrint) { // Acquire possible Client Certificate information and set it on the handle. bool sessionRestartAttempt; // If true and no cached creds we will use anonymous creds. bool cachedCred = false; // this is a return result from this method. X509Certificate2? selectedCert = SelectClientCertificate(out sessionRestartAttempt); try { // Try to locate cached creds first. // // SECURITY: selectedCert ref if not null is a safe object that does not depend on possible **user** inherited X509Certificate type. // byte[]? guessedThumbPrint = selectedCert?.GetCertHash(); SafeFreeCredentials? cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy); // We can probably do some optimization here. If the selectedCert is returned by the delegate // we can always go ahead and use the certificate to create our credential // (instead of going anonymous as we do here). if (sessionRestartAttempt && cachedCredentialHandle == null && selectedCert != null && SslStreamPal.StartMutualAuthAsAnonymous) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Reset to anonymous session."); // IIS does not renegotiate a restarted session if client cert is needed. // So we don't want to reuse **anonymous** cached credential for a new SSL connection if the client has passed some certificate. // The following block happens if client did specify a certificate but no cached creds were found in the cache. // Since we don't restart a session the server side can still challenge for a client cert. if ((object?)_selectedClientCertificate != (object?)selectedCert) { selectedCert.Dispose(); } guessedThumbPrint = null; selectedCert = null; _selectedClientCertificate = null; } if (cachedCredentialHandle != null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.UsingCachedCredential(this); _credentialsHandle = cachedCredentialHandle; cachedCred = true; if (selectedCert != null) { _sslAuthenticationOptions.CertificateContext = SslStreamCertificateContext.Create(selectedCert!); } } else { if (selectedCert != null) { _sslAuthenticationOptions.CertificateContext = SslStreamCertificateContext.Create(selectedCert!); } _credentialsHandle = SslStreamPal.AcquireCredentialsHandle(_sslAuthenticationOptions.CertificateContext, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.EncryptionPolicy, _sslAuthenticationOptions.IsServer); thumbPrint = guessedThumbPrint; // Delay until here in case something above threw. } } finally { if (selectedCert != null && _sslAuthenticationOptions.CertificateContext != null) { _sslAuthenticationOptions.CertificateContext = SslStreamCertificateContext.Create(selectedCert); } } return cachedCred; } private static List<T> EnsureInitialized<T>(ref List<T>? list) => list ?? (list = new List<T>()); // // Acquire Server Side Certificate information and set it on the class. // private bool AcquireServerCredentials(ref byte[]? thumbPrint) { X509Certificate? localCertificate = null; X509Certificate2? selectedCert = null; bool cachedCred = false; // There are three options for selecting the server certificate. When // selecting which to use, we prioritize the new ServerCertSelectionDelegate // API. If the new API isn't used we call LocalCertSelectionCallback (for compat // with .NET Framework), and if neither is set we fall back to using CertificateContext. if (_sslAuthenticationOptions.ServerCertSelectionDelegate != null) { localCertificate = _sslAuthenticationOptions.ServerCertSelectionDelegate(_sslAuthenticationOptions.TargetHost); if (localCertificate == null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"ServerCertSelectionDelegate returned no certificaete for '{_sslAuthenticationOptions.TargetHost}'."); throw new AuthenticationException(SR.net_ssl_io_no_server_cert); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "ServerCertSelectionDelegate selected Cert"); } else if (_sslAuthenticationOptions.CertSelectionDelegate != null) { X509CertificateCollection tempCollection = new X509CertificateCollection(); tempCollection.Add(_sslAuthenticationOptions.CertificateContext!.Certificate!); // We pass string.Empty here to maintain strict compatibility with .NET Framework. localCertificate = _sslAuthenticationOptions.CertSelectionDelegate(string.Empty, tempCollection, null, Array.Empty<string>()); if (localCertificate == null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"CertSelectionDelegate returned no certificaete for '{_sslAuthenticationOptions.TargetHost}'."); throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "CertSelectionDelegate selected Cert"); } else if (_sslAuthenticationOptions.CertificateContext != null) { selectedCert = _sslAuthenticationOptions.CertificateContext.Certificate; } if (selectedCert == null) { // We will get here if certificate was selected via legacy callback using X509Certificate // Fail immediately if no certificate was given. if (localCertificate == null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, "Certiticate callback returned no certificaete."); throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } // SECURITY: Accessing X509 cert Credential is disabled for semitrust. // We no longer need to demand for unmanaged code permissions. // EnsurePrivateKey should do the right demand for us. selectedCert = FindCertificateWithPrivateKey(this, _sslAuthenticationOptions.IsServer, localCertificate); if (selectedCert == null) { throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } Debug.Assert(localCertificate.Equals(selectedCert), "'selectedCert' does not match 'localCertificate'."); _sslAuthenticationOptions.CertificateContext = SslStreamCertificateContext.Create(selectedCert); } Debug.Assert(_sslAuthenticationOptions.CertificateContext != null); // // Note selectedCert is a safe ref possibly cloned from the user passed Cert object // byte[] guessedThumbPrint = selectedCert.GetCertHash(); bool sendTrustedList = _sslAuthenticationOptions.CertificateContext!.Trust?._sendTrustInHandshake ?? false; SafeFreeCredentials? cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy, sendTrustedList); if (cachedCredentialHandle != null) { _credentialsHandle = cachedCredentialHandle; cachedCred = true; } else { _credentialsHandle = SslStreamPal.AcquireCredentialsHandle(_sslAuthenticationOptions.CertificateContext, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.EncryptionPolicy, _sslAuthenticationOptions.IsServer); thumbPrint = guessedThumbPrint; } return cachedCred; } // internal ProtocolToken NextMessage(ReadOnlySpan<byte> incomingBuffer) { byte[]? nextmsg = null; SecurityStatusPal status = GenerateToken(incomingBuffer, ref nextmsg); if (!_sslAuthenticationOptions.IsServer && status.ErrorCode == SecurityStatusPalErrorCode.CredentialsNeeded) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "NextMessage() returned SecurityStatusPal.CredentialsNeeded"); SetRefreshCredentialNeeded(); status = GenerateToken(incomingBuffer, ref nextmsg); } ProtocolToken token = new ProtocolToken(nextmsg, status); if (NetEventSource.Log.IsEnabled()) { if (token.Failed) { NetEventSource.Error(this, $"Authentication failed. Status: {status}, Exception message: {token.GetException()!.Message}"); } } return token; } /*++ GenerateToken - Called after each successive state in the Client - Server handshake. This function generates a set of bytes that will be sent next to the server. The server responds, each response, is pass then into this function, again, and the cycle repeats until successful connection, or failure. Input: input - bytes from the wire output - ref to byte [], what we will send to the server in response Return: status - error information --*/ private SecurityStatusPal GenerateToken(ReadOnlySpan<byte> inputBuffer, ref byte[]? output) { byte[]? result = Array.Empty<byte>(); SecurityStatusPal status = default; bool cachedCreds = false; bool sendTrustList = false; byte[]? thumbPrint = null; // // Looping through ASC or ISC with potentially cached credential that could have been // already disposed from a different thread before ISC or ASC dir increment a cred ref count. // try { do { thumbPrint = null; if (_refreshCredentialNeeded) { cachedCreds = _sslAuthenticationOptions.IsServer ? AcquireServerCredentials(ref thumbPrint) : AcquireClientCredentials(ref thumbPrint); if (cachedCreds && _sslAuthenticationOptions.IsServer) { sendTrustList = _sslAuthenticationOptions.CertificateContext?.Trust?._sendTrustInHandshake ?? false; } } if (_sslAuthenticationOptions.IsServer) { status = SslStreamPal.AcceptSecurityContext( this, ref _credentialsHandle!, ref _securityContext, inputBuffer, ref result, _sslAuthenticationOptions); } else { status = SslStreamPal.InitializeSecurityContext( this, ref _credentialsHandle!, ref _securityContext, _sslAuthenticationOptions.TargetHost, inputBuffer, ref result, _sslAuthenticationOptions); } } while (cachedCreds && _credentialsHandle == null); } finally { if (_refreshCredentialNeeded) { _refreshCredentialNeeded = false; // // Assuming the ISC or ASC has referenced the credential, // we want to call dispose so to decrement the effective ref count. // _credentialsHandle?.Dispose(); // // This call may bump up the credential reference count further. // Note that thumbPrint is retrieved from a safe cert object that was possible cloned from the user passed cert. // if (!cachedCreds && _securityContext != null && !_securityContext.IsInvalid && _credentialsHandle != null && !_credentialsHandle.IsInvalid) { SslSessionsCache.CacheCredential(_credentialsHandle, thumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy, sendTrustList); } } } output = result; return status; } internal SecurityStatusPal Renegotiate(out byte[]? output) { return SslStreamPal.Renegotiate( this, ref _credentialsHandle!, ref _securityContext, _sslAuthenticationOptions, out output); } /*++ ProcessHandshakeSuccess - Called on successful completion of Handshake - used to set header/trailer sizes for encryption use Fills in the information about established protocol --*/ internal void ProcessHandshakeSuccess() { if (_negotiatedApplicationProtocol == default) { // try to get ALPN info unless we already have it. (renegotiation) byte[]? alpnResult = SslStreamPal.GetNegotiatedApplicationProtocol(_securityContext!); _negotiatedApplicationProtocol = alpnResult == null ? default : new SslApplicationProtocol(alpnResult, false); } SslStreamPal.QueryContextStreamSizes(_securityContext!, out StreamSizes streamSizes); _headerSize = streamSizes.Header; _trailerSize = streamSizes.Trailer; _maxDataSize = checked(streamSizes.MaximumMessage - (_headerSize + _trailerSize)); Debug.Assert(_maxDataSize > 0, "_maxDataSize > 0"); SslStreamPal.QueryContextConnectionInfo(_securityContext!, out _connectionInfo); } /*++ Encrypt - Encrypts our bytes before we send them over the wire PERF: make more efficient, this does an extra copy when the offset is non-zero. Input: buffer - bytes for sending offset - size - output - Encrypted bytes --*/ internal SecurityStatusPal Encrypt(ReadOnlyMemory<byte> buffer, ref byte[] output, out int resultSize) { if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(this, buffer.Span); byte[] writeBuffer = output; SecurityStatusPal secStatus = SslStreamPal.EncryptMessage( _securityContext!, buffer, _headerSize, _trailerSize, ref writeBuffer, out resultSize); if (secStatus.ErrorCode != SecurityStatusPalErrorCode.OK) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"ERROR {secStatus}"); } else { output = writeBuffer; } return secStatus; } internal SecurityStatusPal Decrypt(Span<byte> buffer, out int outputOffset, out int outputCount) { SecurityStatusPal status = SslStreamPal.DecryptMessage(_securityContext!, buffer, out outputOffset, out outputCount); if (NetEventSource.Log.IsEnabled() && status.ErrorCode == SecurityStatusPalErrorCode.OK) { NetEventSource.DumpBuffer(this, buffer.Slice(outputOffset, outputCount)); } return status; } /*++ VerifyRemoteCertificate - Validates the content of a Remote Certificate checkCRL if true, checks the certificate revocation list for validity. checkCertName, if true checks the CN field of the certificate --*/ //This method validates a remote certificate. internal bool VerifyRemoteCertificate(RemoteCertificateValidationCallback? remoteCertValidationCallback, SslCertificateTrust? trust, ref ProtocolToken? alertToken, out SslPolicyErrors sslPolicyErrors, out X509ChainStatusFlags chainStatus) { sslPolicyErrors = SslPolicyErrors.None; chainStatus = X509ChainStatusFlags.NoError; // We don't catch exceptions in this method, so it's safe for "accepted" be initialized with true. bool success = false; X509Chain? chain = null; X509Certificate2Collection? remoteCertificateStore = null; try { X509Certificate2? certificate = CertificateValidationPal.GetRemoteCertificate(_securityContext, out remoteCertificateStore); if (_remoteCertificate != null && certificate != null && certificate.RawDataMemory.Span.SequenceEqual(_remoteCertificate.RawDataMemory.Span)) { // This is renegotiation or TLS 1.3 and the certificate did not change. // There is no reason to process callback again as we already established trust. return true; } _remoteCertificate = certificate; if (_remoteCertificate == null) { if (NetEventSource.Log.IsEnabled() && RemoteCertRequired) NetEventSource.Error(this, $"Remote certificate required, but no remote certificate received"); sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable; } else { chain = new X509Chain(); chain.ChainPolicy.RevocationMode = _sslAuthenticationOptions.CertificateRevocationCheckMode; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; // Authenticate the remote party: (e.g. when operating in server mode, authenticate the client). chain.ChainPolicy.ApplicationPolicy.Add(_sslAuthenticationOptions.IsServer ? s_clientAuthOid : s_serverAuthOid); if (remoteCertificateStore != null) { chain.ChainPolicy.ExtraStore.AddRange(remoteCertificateStore); } if (trust != null) { chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; if (trust._store != null) { chain.ChainPolicy.CustomTrustStore.AddRange(trust._store.Certificates); } if (trust._trustList != null) { chain.ChainPolicy.CustomTrustStore.AddRange(trust._trustList); } } sslPolicyErrors |= CertificateValidationPal.VerifyCertificateProperties( _securityContext!, chain, _remoteCertificate, _sslAuthenticationOptions.CheckCertName, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.TargetHost); } if (remoteCertValidationCallback != null) { object? sender = _ssl; if (sender == null) { throw new ObjectDisposedException(nameof(SslStream)); } success = remoteCertValidationCallback(sender, _remoteCertificate, chain, sslPolicyErrors); } else { if (!RemoteCertRequired) { sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNotAvailable; } success = (sslPolicyErrors == SslPolicyErrors.None); } if (NetEventSource.Log.IsEnabled()) { LogCertificateValidation(remoteCertValidationCallback, sslPolicyErrors, success, chain!); NetEventSource.Info(this, $"Cert validation, remote cert = {_remoteCertificate}"); } if (!success) { alertToken = CreateFatalHandshakeAlertToken(sslPolicyErrors, chain!); if (chain != null) { foreach (X509ChainStatus status in chain.ChainStatus) { chainStatus |= status.Status; } } } } finally { // At least on Win2k server the chain is found to have dependencies on the original cert context. // So it should be closed first. if (chain != null) { int elementsCount = chain.ChainElements.Count; for (int i = 0; i < elementsCount; i++) { chain.ChainElements[i].Certificate!.Dispose(); } chain.Dispose(); } if (remoteCertificateStore != null) { int certCount = remoteCertificateStore.Count; for (int i = 0; i < certCount; i++) { remoteCertificateStore[i].Dispose(); } } } return success; } public ProtocolToken? CreateFatalHandshakeAlertToken(SslPolicyErrors sslPolicyErrors, X509Chain chain) { TlsAlertMessage alertMessage; switch (sslPolicyErrors) { case SslPolicyErrors.RemoteCertificateChainErrors: alertMessage = GetAlertMessageFromChain(chain); break; case SslPolicyErrors.RemoteCertificateNameMismatch: alertMessage = TlsAlertMessage.BadCertificate; break; case SslPolicyErrors.RemoteCertificateNotAvailable: default: alertMessage = TlsAlertMessage.CertificateUnknown; break; } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"alertMessage:{alertMessage}"); SecurityStatusPal status; status = SslStreamPal.ApplyAlertToken(ref _credentialsHandle, _securityContext, TlsAlertType.Fatal, alertMessage); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"ApplyAlertToken() returned {status.ErrorCode}"); if (status.Exception != null) { ExceptionDispatchInfo.Throw(status.Exception); } return null; } return GenerateAlertToken(); } public ProtocolToken? CreateShutdownToken() { SecurityStatusPal status; status = SslStreamPal.ApplyShutdownToken(ref _credentialsHandle, _securityContext!); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"ApplyAlertToken() returned {status.ErrorCode}"); if (status.Exception != null) { ExceptionDispatchInfo.Throw(status.Exception); } return null; } return GenerateAlertToken(); } private ProtocolToken GenerateAlertToken() { byte[]? nextmsg = null; SecurityStatusPal status; status = GenerateToken(default, ref nextmsg); return new ProtocolToken(nextmsg, status); } private static TlsAlertMessage GetAlertMessageFromChain(X509Chain chain) { foreach (X509ChainStatus chainStatus in chain.ChainStatus) { if (chainStatus.Status == X509ChainStatusFlags.NoError) { continue; } if ((chainStatus.Status & (X509ChainStatusFlags.UntrustedRoot | X509ChainStatusFlags.PartialChain | X509ChainStatusFlags.Cyclic)) != 0) { return TlsAlertMessage.UnknownCA; } if ((chainStatus.Status & (X509ChainStatusFlags.Revoked | X509ChainStatusFlags.OfflineRevocation)) != 0) { return TlsAlertMessage.CertificateRevoked; } if ((chainStatus.Status & (X509ChainStatusFlags.CtlNotTimeValid | X509ChainStatusFlags.NotTimeNested | X509ChainStatusFlags.NotTimeValid)) != 0) { return TlsAlertMessage.CertificateExpired; } if ((chainStatus.Status & X509ChainStatusFlags.CtlNotValidForUsage) != 0) { return TlsAlertMessage.UnsupportedCert; } if ((chainStatus.Status & (X509ChainStatusFlags.CtlNotSignatureValid | X509ChainStatusFlags.InvalidExtension | X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.InvalidPolicyConstraints) | X509ChainStatusFlags.NoIssuanceChainPolicy | X509ChainStatusFlags.NotValidForUsage) != 0) { return TlsAlertMessage.BadCertificate; } // All other errors: return TlsAlertMessage.CertificateUnknown; } return TlsAlertMessage.BadCertificate; } private void LogCertificateValidation(RemoteCertificateValidationCallback? remoteCertValidationCallback, SslPolicyErrors sslPolicyErrors, bool success, X509Chain chain) { if (!NetEventSource.Log.IsEnabled()) return; if (sslPolicyErrors != SslPolicyErrors.None) { NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_has_errors); if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0) { NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_not_available); } if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) { NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_name_mismatch); } if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0) { string chainStatusString = "ChainStatus: "; foreach (X509ChainStatus chainStatus in chain.ChainStatus) { chainStatusString += "\t" + chainStatus.StatusInformation; } NetEventSource.Log.RemoteCertificateError(this, chainStatusString); } } if (success) { if (remoteCertValidationCallback != null) { NetEventSource.Log.RemoteCertDeclaredValid(this); } else { NetEventSource.Log.RemoteCertHasNoErrors(this); } } else { if (remoteCertValidationCallback != null) { NetEventSource.Log.RemoteCertUserDeclaredInvalid(this); } } } } // ProtocolToken - used to process and handle the return codes from the SSPI wrapper internal sealed class ProtocolToken { internal SecurityStatusPal Status; internal byte[]? Payload; internal int Size; internal bool Failed { get { return ((Status.ErrorCode != SecurityStatusPalErrorCode.OK) && (Status.ErrorCode != SecurityStatusPalErrorCode.ContinueNeeded)); } } internal bool Done { get { return (Status.ErrorCode == SecurityStatusPalErrorCode.OK); } } internal bool Renegotiate { get { return (Status.ErrorCode == SecurityStatusPalErrorCode.Renegotiate); } } internal bool CloseConnection { get { return (Status.ErrorCode == SecurityStatusPalErrorCode.ContextExpired); } } internal ProtocolToken(byte[]? data, SecurityStatusPal status) { Status = status; Payload = data; Size = data != null ? data.Length : 0; } internal Exception? GetException() { // If it's not done, then there's got to be an error, even if it's // a Handshake message up, and we only have a Warning message. return Done ? null : SslStreamPal.GetException(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.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Security; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace System.Net.Security { // SecureChannel - a wrapper on SSPI based functionality. // Provides an additional abstraction layer over SSPI for SslStream. internal sealed class SecureChannel { private SafeFreeCredentials? _credentialsHandle; private SafeDeleteSslContext? _securityContext; private SslConnectionInfo? _connectionInfo; private X509Certificate? _selectedClientCertificate; private X509Certificate2? _remoteCertificate; private bool _remoteCertificateExposed; // These are the MAX encrypt buffer output sizes, not the actual sizes. private int _headerSize = 5; //ATTN must be set to at least 5 by default private int _trailerSize = 16; private int _maxDataSize = 16354; private bool _refreshCredentialNeeded; private readonly SslAuthenticationOptions _sslAuthenticationOptions; private SslApplicationProtocol _negotiatedApplicationProtocol; private static readonly Oid s_serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.1"); private static readonly Oid s_clientAuthOid = new Oid("1.3.6.1.5.5.7.3.2", "1.3.6.1.5.5.7.3.2"); private SslStream? _ssl; internal SecureChannel(SslAuthenticationOptions sslAuthenticationOptions, SslStream sslStream) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.SecureChannelCtor(this, sslStream, sslAuthenticationOptions.TargetHost!, sslAuthenticationOptions.ClientCertificates, sslAuthenticationOptions.EncryptionPolicy); SslStreamPal.VerifyPackageInfo(); Debug.Assert(sslAuthenticationOptions.TargetHost != null, "sslAuthenticationOptions.TargetHost == null"); _securityContext = null; _refreshCredentialNeeded = true; _sslAuthenticationOptions = sslAuthenticationOptions; _ssl = sslStream; } // // SecureChannel properties // // LocalServerCertificate - local certificate for server mode channel // LocalClientCertificate - selected certificated used in the client channel mode otherwise null // IsRemoteCertificateAvailable - true if the remote side has provided a certificate // HeaderSize - Header & trailer sizes used in the TLS stream // TrailerSize - // internal X509Certificate? LocalServerCertificate { get { return _sslAuthenticationOptions.CertificateContext?.Certificate; } } internal X509Certificate? LocalClientCertificate { get { return _selectedClientCertificate; } } internal bool IsRemoteCertificateAvailable { get { return _remoteCertificate != null; } } internal X509Certificate? RemoteCertificate { get { _remoteCertificateExposed = true; return _remoteCertificate; } } internal ChannelBinding? GetChannelBinding(ChannelBindingKind kind) { ChannelBinding? result = null; if (_securityContext != null) { result = SslStreamPal.QueryContextChannelBinding(_securityContext, kind); } return result; } internal X509RevocationMode CheckCertRevocationStatus { get { return _sslAuthenticationOptions.CertificateRevocationCheckMode; } } internal int MaxDataSize { get { return _maxDataSize; } } internal SslConnectionInfo? ConnectionInfo { get { return _connectionInfo; } } internal bool IsValidContext { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return !(_securityContext == null || _securityContext.IsInvalid); } } internal bool IsServer { get { return _sslAuthenticationOptions.IsServer; } } internal bool RemoteCertRequired { get { return _sslAuthenticationOptions.RemoteCertRequired; } } internal SslApplicationProtocol NegotiatedApplicationProtocol { get { return _negotiatedApplicationProtocol; } } internal void SetRefreshCredentialNeeded() { _refreshCredentialNeeded = true; } internal void Close() { if (!_remoteCertificateExposed) { _remoteCertificate?.Dispose(); _remoteCertificate = null; } _securityContext?.Dispose(); _credentialsHandle?.Dispose(); _ssl = null; GC.SuppressFinalize(this); } // // SECURITY: we open a private key container on behalf of the caller // and we require the caller to have permission associated with that operation. // internal static X509Certificate2? FindCertificateWithPrivateKey(object instance, bool isServer, X509Certificate certificate) { if (certificate == null) { return null; } if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.LocatingPrivateKey(certificate, instance); try { // Protecting from X509Certificate2 derived classes. X509Certificate2? certEx = MakeEx(certificate); if (certEx != null) { if (certEx.HasPrivateKey) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.CertIsType2(instance); return certEx; } if (!object.ReferenceEquals(certificate, certEx)) { certEx.Dispose(); } } X509Certificate2Collection collectionEx; string certHash = certEx!.Thumbprint; // ELSE Try the MY user and machine stores for private key check. // For server side mode MY machine store takes priority. X509Store? store = CertificateValidationPal.EnsureStoreOpened(isServer); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.FoundCertInStore(isServer, instance); return collectionEx[0]; } } store = CertificateValidationPal.EnsureStoreOpened(!isServer); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.FoundCertInStore(!isServer, instance); return collectionEx[0]; } } } catch (CryptographicException) { } if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.NotFoundCertInStore(instance); return null; } private static X509Certificate2? MakeEx(X509Certificate certificate) { Debug.Assert(certificate != null, "certificate != null"); if (certificate.GetType() == typeof(X509Certificate2)) { return (X509Certificate2)certificate; } X509Certificate2? certificateEx = null; try { if (certificate.Handle != IntPtr.Zero) { certificateEx = new X509Certificate2(certificate); } } catch (SecurityException) { } catch (CryptographicException) { } return certificateEx; } // // Get certificate_authorities list, according to RFC 5246, Section 7.4.4. // Used only by client SSL code, never returns null. // private string[] GetRequestCertificateAuthorities() { string[] issuers = Array.Empty<string>(); if (IsValidContext) { issuers = CertificateValidationPal.GetRequestCertificateAuthorities(_securityContext!); } return issuers; } internal X509Certificate2? SelectClientCertificate(out bool sessionRestartAttempt) { sessionRestartAttempt = false; X509Certificate? clientCertificate = null; // candidate certificate that can come from the user callback or be guessed when targeting a session restart. X509Certificate2? selectedCert = null; // final selected cert (ensured that it does have private key with it). List<X509Certificate>? filteredCerts = null; // This is an intermediate client certs collection that try to use if no selectedCert is available yet. string[] issuers; // This is a list of issuers sent by the server, only valid if we do know what the server cert is. if (_sslAuthenticationOptions.CertSelectionDelegate != null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Calling CertificateSelectionCallback"); X509Certificate2? remoteCert = null; try { issuers = GetRequestCertificateAuthorities(); remoteCert = CertificateValidationPal.GetRemoteCertificate(_securityContext!); if (_sslAuthenticationOptions.ClientCertificates == null) { _sslAuthenticationOptions.ClientCertificates = new X509CertificateCollection(); } clientCertificate = _sslAuthenticationOptions.CertSelectionDelegate(_sslAuthenticationOptions.TargetHost!, _sslAuthenticationOptions.ClientCertificates, remoteCert, issuers); } finally { remoteCert?.Dispose(); } if (clientCertificate != null) { if (_credentialsHandle == null) { sessionRestartAttempt = true; } EnsureInitialized(ref filteredCerts).Add(clientCertificate); if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.CertificateFromDelegate(this); } else { if (_sslAuthenticationOptions.ClientCertificates == null || _sslAuthenticationOptions.ClientCertificates.Count == 0) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.NoDelegateNoClientCert(this); sessionRestartAttempt = true; } else { if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.NoDelegateButClientCert(this); } } } else if (_credentialsHandle == null && _sslAuthenticationOptions.ClientCertificates != null && _sslAuthenticationOptions.ClientCertificates.Count > 0) { // This is where we attempt to restart a session by picking the FIRST cert from the collection. // Otherwise it is either server sending a client cert request or the session is renegotiated. clientCertificate = _sslAuthenticationOptions.ClientCertificates[0]; sessionRestartAttempt = true; if (clientCertificate != null) { EnsureInitialized(ref filteredCerts).Add(clientCertificate); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.AttemptingRestartUsingCert(clientCertificate, this); } else if (_sslAuthenticationOptions.ClientCertificates != null && _sslAuthenticationOptions.ClientCertificates.Count > 0) { // // This should be a server request for the client cert sent over currently anonymous sessions. // issuers = GetRequestCertificateAuthorities(); if (NetEventSource.Log.IsEnabled()) { if (issuers == null || issuers.Length == 0) { NetEventSource.Log.NoIssuersTryAllCerts(this); } else { NetEventSource.Log.LookForMatchingCerts(issuers.Length, this); } } for (int i = 0; i < _sslAuthenticationOptions.ClientCertificates.Count; ++i) { // // Make sure we add only if the cert matches one of the issuers. // If no issuers were sent and then try all client certs starting with the first one. // if (issuers != null && issuers.Length != 0) { X509Certificate2? certificateEx = null; X509Chain? chain = null; try { certificateEx = MakeEx(_sslAuthenticationOptions.ClientCertificates[i]); if (certificateEx == null) { continue; } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Root cert: {certificateEx}"); chain = new X509Chain(); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreInvalidName; chain.Build(certificateEx); bool found = false; // // We ignore any errors happened with chain. // if (chain.ChainElements.Count > 0) { int elementsCount = chain.ChainElements.Count; for (int ii = 0; ii < elementsCount; ++ii) { string issuer = chain.ChainElements[ii].Certificate!.Issuer; found = Array.IndexOf(issuers, issuer) != -1; if (found) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Matched {issuer}"); break; } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"No match: {issuer}"); } } if (!found) { continue; } } finally { if (chain != null) { chain.Dispose(); int elementsCount = chain.ChainElements.Count; for (int element = 0; element < elementsCount; element++) { chain.ChainElements[element].Certificate!.Dispose(); } } if (certificateEx != null && (object)certificateEx != (object)_sslAuthenticationOptions.ClientCertificates[i]) { certificateEx.Dispose(); } } } if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.SelectedCert(_sslAuthenticationOptions.ClientCertificates[i], this); EnsureInitialized(ref filteredCerts).Add(_sslAuthenticationOptions.ClientCertificates[i]); } } clientCertificate = null; if (NetEventSource.Log.IsEnabled()) { if (filteredCerts != null && filteredCerts.Count != 0) { NetEventSource.Log.CertsAfterFiltering(filteredCerts.Count, this); NetEventSource.Log.FindingMatchingCerts(this); } else { NetEventSource.Log.CertsAfterFiltering(0, this); NetEventSource.Info(this, "No client certificate to choose from"); } } // // ATTN: When the client cert was returned by the user callback OR it was guessed AND it has no private key, // THEN anonymous (no client cert) credential will be used. // // SECURITY: Accessing X509 cert Credential is disabled for semitrust. // We no longer need to demand for unmanaged code permissions. // FindCertificateWithPrivateKey should do the right demand for us. if (filteredCerts != null) { for (int i = 0; i < filteredCerts.Count; ++i) { clientCertificate = filteredCerts[i]; if ((selectedCert = FindCertificateWithPrivateKey(this, _sslAuthenticationOptions.IsServer, clientCertificate)) != null) { break; } clientCertificate = null; selectedCert = null; } } Debug.Assert((object?)clientCertificate == (object?)selectedCert || clientCertificate!.Equals(selectedCert), "'selectedCert' does not match 'clientCertificate'."); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Selected cert = {selectedCert}"); _selectedClientCertificate = clientCertificate; return selectedCert; } /*++ AcquireCredentials - Attempts to find Client Credential Information, that can be sent to the server. In our case, this is only Client Certificates, that we have Credential Info. How it works: case 0: Cert Selection delegate is present Always use its result as the client cert answer. Try to use cached credential handle whenever feasible. Do not use cached anonymous creds if the delegate has returned null and the collection is not empty (allow responding with the cert later). case 1: Certs collection is empty Always use the same statically acquired anonymous SSL Credential case 2: Before our Connection with the Server If we have a cached credential handle keyed by first X509Certificate **content** in the passed collection, then we use that cached credential and hoping to restart a session. Otherwise create a new anonymous (allow responding with the cert later). case 3: After our Connection with the Server (i.e. during handshake or re-handshake) The server has requested that we send it a Certificate then we Enumerate a list of server sent Issuers trying to match against our list of Certificates, the first match is sent to the server. Once we got a cert we again try to match cached credential handle if possible. This will not restart a session but helps minimizing the number of handles we create. In the case of an error getting a Certificate or checking its private Key we fall back to the behavior of having no certs, case 1. Returns: True if cached creds were used, false otherwise. --*/ private bool AcquireClientCredentials(ref byte[]? thumbPrint) { // Acquire possible Client Certificate information and set it on the handle. bool sessionRestartAttempt; // If true and no cached creds we will use anonymous creds. bool cachedCred = false; // this is a return result from this method. X509Certificate2? selectedCert = SelectClientCertificate(out sessionRestartAttempt); try { // Try to locate cached creds first. // // SECURITY: selectedCert ref if not null is a safe object that does not depend on possible **user** inherited X509Certificate type. // byte[]? guessedThumbPrint = selectedCert?.GetCertHash(); SafeFreeCredentials? cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy); // We can probably do some optimization here. If the selectedCert is returned by the delegate // we can always go ahead and use the certificate to create our credential // (instead of going anonymous as we do here). if (sessionRestartAttempt && cachedCredentialHandle == null && selectedCert != null && SslStreamPal.StartMutualAuthAsAnonymous) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Reset to anonymous session."); // IIS does not renegotiate a restarted session if client cert is needed. // So we don't want to reuse **anonymous** cached credential for a new SSL connection if the client has passed some certificate. // The following block happens if client did specify a certificate but no cached creds were found in the cache. // Since we don't restart a session the server side can still challenge for a client cert. if ((object?)_selectedClientCertificate != (object?)selectedCert) { selectedCert.Dispose(); } guessedThumbPrint = null; selectedCert = null; _selectedClientCertificate = null; } if (cachedCredentialHandle != null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.UsingCachedCredential(this); _credentialsHandle = cachedCredentialHandle; cachedCred = true; if (selectedCert != null) { _sslAuthenticationOptions.CertificateContext = SslStreamCertificateContext.Create(selectedCert!); } } else { if (selectedCert != null) { _sslAuthenticationOptions.CertificateContext = SslStreamCertificateContext.Create(selectedCert!); } _credentialsHandle = AcquireCredentialsHandle(_sslAuthenticationOptions); thumbPrint = guessedThumbPrint; // Delay until here in case something above threw. } } finally { if (selectedCert != null && _sslAuthenticationOptions.CertificateContext != null) { _sslAuthenticationOptions.CertificateContext = SslStreamCertificateContext.Create(selectedCert); } } return cachedCred; } private static List<T> EnsureInitialized<T>(ref List<T>? list) => list ?? (list = new List<T>()); // // Acquire Server Side Certificate information and set it on the class. // private bool AcquireServerCredentials(ref byte[]? thumbPrint) { X509Certificate? localCertificate = null; X509Certificate2? selectedCert = null; bool cachedCred = false; // There are three options for selecting the server certificate. When // selecting which to use, we prioritize the new ServerCertSelectionDelegate // API. If the new API isn't used we call LocalCertSelectionCallback (for compat // with .NET Framework), and if neither is set we fall back to using CertificateContext. if (_sslAuthenticationOptions.ServerCertSelectionDelegate != null) { localCertificate = _sslAuthenticationOptions.ServerCertSelectionDelegate(_sslAuthenticationOptions.TargetHost); if (localCertificate == null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"ServerCertSelectionDelegate returned no certificaete for '{_sslAuthenticationOptions.TargetHost}'."); throw new AuthenticationException(SR.net_ssl_io_no_server_cert); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "ServerCertSelectionDelegate selected Cert"); } else if (_sslAuthenticationOptions.CertSelectionDelegate != null) { X509CertificateCollection tempCollection = new X509CertificateCollection(); tempCollection.Add(_sslAuthenticationOptions.CertificateContext!.Certificate!); // We pass string.Empty here to maintain strict compatibility with .NET Framework. localCertificate = _sslAuthenticationOptions.CertSelectionDelegate(string.Empty, tempCollection, null, Array.Empty<string>()); if (localCertificate == null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"CertSelectionDelegate returned no certificaete for '{_sslAuthenticationOptions.TargetHost}'."); throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "CertSelectionDelegate selected Cert"); } else if (_sslAuthenticationOptions.CertificateContext != null) { selectedCert = _sslAuthenticationOptions.CertificateContext.Certificate; } if (selectedCert == null) { // We will get here if certificate was selected via legacy callback using X509Certificate // Fail immediately if no certificate was given. if (localCertificate == null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, "Certiticate callback returned no certificaete."); throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } // SECURITY: Accessing X509 cert Credential is disabled for semitrust. // We no longer need to demand for unmanaged code permissions. // EnsurePrivateKey should do the right demand for us. selectedCert = FindCertificateWithPrivateKey(this, _sslAuthenticationOptions.IsServer, localCertificate); if (selectedCert == null) { throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } Debug.Assert(localCertificate.Equals(selectedCert), "'selectedCert' does not match 'localCertificate'."); _sslAuthenticationOptions.CertificateContext = SslStreamCertificateContext.Create(selectedCert); } Debug.Assert(_sslAuthenticationOptions.CertificateContext != null); // // Note selectedCert is a safe ref possibly cloned from the user passed Cert object // byte[] guessedThumbPrint = selectedCert.GetCertHash(); bool sendTrustedList = _sslAuthenticationOptions.CertificateContext!.Trust?._sendTrustInHandshake ?? false; SafeFreeCredentials? cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy, sendTrustedList); if (cachedCredentialHandle != null) { _credentialsHandle = cachedCredentialHandle; cachedCred = true; } else { _credentialsHandle = AcquireCredentialsHandle(_sslAuthenticationOptions); thumbPrint = guessedThumbPrint; } return cachedCred; } private static SafeFreeCredentials AcquireCredentialsHandle(SslAuthenticationOptions sslAuthenticationOptions) { SafeFreeCredentials cred = SslStreamPal.AcquireCredentialsHandle(sslAuthenticationOptions.CertificateContext, sslAuthenticationOptions.EnabledSslProtocols, sslAuthenticationOptions.EncryptionPolicy, sslAuthenticationOptions.IsServer); if (sslAuthenticationOptions.CertificateContext != null) { // // Since the SafeFreeCredentials can be cached and reused, it may happen on long running processes that some cert on // the chain expires and all subsequent connections would send expired intermediate certificates. Find the earliest // NotAfter timestamp on the chain and use it as expiration timestamp for the credentials. // This provides an opportunity to recreate the credentials with an alternative (and still valid) // certificate chain. // SslStreamCertificateContext certificateContext = sslAuthenticationOptions.CertificateContext; cred._expiry = GetExpiryTimestamp(certificateContext); if (cred._expiry < DateTime.UtcNow) { // // The CertificateContext from auth options is recreated just before creating the SafeFreeCredentials. However, in case when // it was provided by the user code, it may still contain the (now expired) certificate chain. Such expiration timestamp would // effectively disable caching as it would lead to creating new credentials for each connection. We attempt to recover by creating // a temporary certificate context (which builds a new chain with hopefully more recent chain). // certificateContext = SslStreamCertificateContext.Create( certificateContext.Certificate, new X509Certificate2Collection(certificateContext.IntermediateCertificates), trust: certificateContext.Trust); cred._expiry = GetExpiryTimestamp(certificateContext); } static DateTime GetExpiryTimestamp(SslStreamCertificateContext certificateContext) { DateTime expiry = certificateContext.Certificate.NotAfter; foreach (X509Certificate2 cert in certificateContext.IntermediateCertificates) { if (cert.NotAfter < expiry) { expiry = cert.NotAfter; } } return expiry.ToUniversalTime(); } } return cred; } // internal ProtocolToken NextMessage(ReadOnlySpan<byte> incomingBuffer) { byte[]? nextmsg = null; SecurityStatusPal status = GenerateToken(incomingBuffer, ref nextmsg); if (!_sslAuthenticationOptions.IsServer && status.ErrorCode == SecurityStatusPalErrorCode.CredentialsNeeded) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "NextMessage() returned SecurityStatusPal.CredentialsNeeded"); SetRefreshCredentialNeeded(); status = GenerateToken(incomingBuffer, ref nextmsg); } ProtocolToken token = new ProtocolToken(nextmsg, status); if (NetEventSource.Log.IsEnabled()) { if (token.Failed) { NetEventSource.Error(this, $"Authentication failed. Status: {status}, Exception message: {token.GetException()!.Message}"); } } return token; } /*++ GenerateToken - Called after each successive state in the Client - Server handshake. This function generates a set of bytes that will be sent next to the server. The server responds, each response, is pass then into this function, again, and the cycle repeats until successful connection, or failure. Input: input - bytes from the wire output - ref to byte [], what we will send to the server in response Return: status - error information --*/ private SecurityStatusPal GenerateToken(ReadOnlySpan<byte> inputBuffer, ref byte[]? output) { byte[]? result = Array.Empty<byte>(); SecurityStatusPal status = default; bool cachedCreds = false; bool sendTrustList = false; byte[]? thumbPrint = null; // // Looping through ASC or ISC with potentially cached credential that could have been // already disposed from a different thread before ISC or ASC dir increment a cred ref count. // try { do { thumbPrint = null; if (_refreshCredentialNeeded) { cachedCreds = _sslAuthenticationOptions.IsServer ? AcquireServerCredentials(ref thumbPrint) : AcquireClientCredentials(ref thumbPrint); if (cachedCreds && _sslAuthenticationOptions.IsServer) { sendTrustList = _sslAuthenticationOptions.CertificateContext?.Trust?._sendTrustInHandshake ?? false; } } if (_sslAuthenticationOptions.IsServer) { status = SslStreamPal.AcceptSecurityContext( this, ref _credentialsHandle!, ref _securityContext, inputBuffer, ref result, _sslAuthenticationOptions); } else { status = SslStreamPal.InitializeSecurityContext( this, ref _credentialsHandle!, ref _securityContext, _sslAuthenticationOptions.TargetHost, inputBuffer, ref result, _sslAuthenticationOptions); } } while (cachedCreds && _credentialsHandle == null); } finally { if (_refreshCredentialNeeded) { _refreshCredentialNeeded = false; // // Assuming the ISC or ASC has referenced the credential, // we want to call dispose so to decrement the effective ref count. // _credentialsHandle?.Dispose(); // // This call may bump up the credential reference count further. // Note that thumbPrint is retrieved from a safe cert object that was possible cloned from the user passed cert. // if (!cachedCreds && _securityContext != null && !_securityContext.IsInvalid && _credentialsHandle != null && !_credentialsHandle.IsInvalid) { SslSessionsCache.CacheCredential(_credentialsHandle, thumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy, sendTrustList); } } } output = result; return status; } internal SecurityStatusPal Renegotiate(out byte[]? output) { return SslStreamPal.Renegotiate( this, ref _credentialsHandle!, ref _securityContext, _sslAuthenticationOptions, out output); } /*++ ProcessHandshakeSuccess - Called on successful completion of Handshake - used to set header/trailer sizes for encryption use Fills in the information about established protocol --*/ internal void ProcessHandshakeSuccess() { if (_negotiatedApplicationProtocol == default) { // try to get ALPN info unless we already have it. (renegotiation) byte[]? alpnResult = SslStreamPal.GetNegotiatedApplicationProtocol(_securityContext!); _negotiatedApplicationProtocol = alpnResult == null ? default : new SslApplicationProtocol(alpnResult, false); } SslStreamPal.QueryContextStreamSizes(_securityContext!, out StreamSizes streamSizes); _headerSize = streamSizes.Header; _trailerSize = streamSizes.Trailer; _maxDataSize = checked(streamSizes.MaximumMessage - (_headerSize + _trailerSize)); Debug.Assert(_maxDataSize > 0, "_maxDataSize > 0"); SslStreamPal.QueryContextConnectionInfo(_securityContext!, out _connectionInfo); } /*++ Encrypt - Encrypts our bytes before we send them over the wire PERF: make more efficient, this does an extra copy when the offset is non-zero. Input: buffer - bytes for sending offset - size - output - Encrypted bytes --*/ internal SecurityStatusPal Encrypt(ReadOnlyMemory<byte> buffer, ref byte[] output, out int resultSize) { if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(this, buffer.Span); byte[] writeBuffer = output; SecurityStatusPal secStatus = SslStreamPal.EncryptMessage( _securityContext!, buffer, _headerSize, _trailerSize, ref writeBuffer, out resultSize); if (secStatus.ErrorCode != SecurityStatusPalErrorCode.OK) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"ERROR {secStatus}"); } else { output = writeBuffer; } return secStatus; } internal SecurityStatusPal Decrypt(Span<byte> buffer, out int outputOffset, out int outputCount) { SecurityStatusPal status = SslStreamPal.DecryptMessage(_securityContext!, buffer, out outputOffset, out outputCount); if (NetEventSource.Log.IsEnabled() && status.ErrorCode == SecurityStatusPalErrorCode.OK) { NetEventSource.DumpBuffer(this, buffer.Slice(outputOffset, outputCount)); } return status; } /*++ VerifyRemoteCertificate - Validates the content of a Remote Certificate checkCRL if true, checks the certificate revocation list for validity. checkCertName, if true checks the CN field of the certificate --*/ //This method validates a remote certificate. internal bool VerifyRemoteCertificate(RemoteCertificateValidationCallback? remoteCertValidationCallback, SslCertificateTrust? trust, ref ProtocolToken? alertToken, out SslPolicyErrors sslPolicyErrors, out X509ChainStatusFlags chainStatus) { sslPolicyErrors = SslPolicyErrors.None; chainStatus = X509ChainStatusFlags.NoError; // We don't catch exceptions in this method, so it's safe for "accepted" be initialized with true. bool success = false; X509Chain? chain = null; X509Certificate2Collection? remoteCertificateStore = null; try { X509Certificate2? certificate = CertificateValidationPal.GetRemoteCertificate(_securityContext, out remoteCertificateStore); if (_remoteCertificate != null && certificate != null && certificate.RawDataMemory.Span.SequenceEqual(_remoteCertificate.RawDataMemory.Span)) { // This is renegotiation or TLS 1.3 and the certificate did not change. // There is no reason to process callback again as we already established trust. return true; } _remoteCertificate = certificate; if (_remoteCertificate == null) { if (NetEventSource.Log.IsEnabled() && RemoteCertRequired) NetEventSource.Error(this, $"Remote certificate required, but no remote certificate received"); sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable; } else { chain = new X509Chain(); chain.ChainPolicy.RevocationMode = _sslAuthenticationOptions.CertificateRevocationCheckMode; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; // Authenticate the remote party: (e.g. when operating in server mode, authenticate the client). chain.ChainPolicy.ApplicationPolicy.Add(_sslAuthenticationOptions.IsServer ? s_clientAuthOid : s_serverAuthOid); if (remoteCertificateStore != null) { chain.ChainPolicy.ExtraStore.AddRange(remoteCertificateStore); } if (trust != null) { chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; if (trust._store != null) { chain.ChainPolicy.CustomTrustStore.AddRange(trust._store.Certificates); } if (trust._trustList != null) { chain.ChainPolicy.CustomTrustStore.AddRange(trust._trustList); } } sslPolicyErrors |= CertificateValidationPal.VerifyCertificateProperties( _securityContext!, chain, _remoteCertificate, _sslAuthenticationOptions.CheckCertName, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.TargetHost); } if (remoteCertValidationCallback != null) { object? sender = _ssl; if (sender == null) { throw new ObjectDisposedException(nameof(SslStream)); } success = remoteCertValidationCallback(sender, _remoteCertificate, chain, sslPolicyErrors); } else { if (!RemoteCertRequired) { sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNotAvailable; } success = (sslPolicyErrors == SslPolicyErrors.None); } if (NetEventSource.Log.IsEnabled()) { LogCertificateValidation(remoteCertValidationCallback, sslPolicyErrors, success, chain!); NetEventSource.Info(this, $"Cert validation, remote cert = {_remoteCertificate}"); } if (!success) { alertToken = CreateFatalHandshakeAlertToken(sslPolicyErrors, chain!); if (chain != null) { foreach (X509ChainStatus status in chain.ChainStatus) { chainStatus |= status.Status; } } } } finally { // At least on Win2k server the chain is found to have dependencies on the original cert context. // So it should be closed first. if (chain != null) { int elementsCount = chain.ChainElements.Count; for (int i = 0; i < elementsCount; i++) { chain.ChainElements[i].Certificate!.Dispose(); } chain.Dispose(); } if (remoteCertificateStore != null) { int certCount = remoteCertificateStore.Count; for (int i = 0; i < certCount; i++) { remoteCertificateStore[i].Dispose(); } } } return success; } public ProtocolToken? CreateFatalHandshakeAlertToken(SslPolicyErrors sslPolicyErrors, X509Chain chain) { TlsAlertMessage alertMessage; switch (sslPolicyErrors) { case SslPolicyErrors.RemoteCertificateChainErrors: alertMessage = GetAlertMessageFromChain(chain); break; case SslPolicyErrors.RemoteCertificateNameMismatch: alertMessage = TlsAlertMessage.BadCertificate; break; case SslPolicyErrors.RemoteCertificateNotAvailable: default: alertMessage = TlsAlertMessage.CertificateUnknown; break; } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"alertMessage:{alertMessage}"); SecurityStatusPal status; status = SslStreamPal.ApplyAlertToken(ref _credentialsHandle, _securityContext, TlsAlertType.Fatal, alertMessage); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"ApplyAlertToken() returned {status.ErrorCode}"); if (status.Exception != null) { ExceptionDispatchInfo.Throw(status.Exception); } return null; } return GenerateAlertToken(); } public ProtocolToken? CreateShutdownToken() { SecurityStatusPal status; status = SslStreamPal.ApplyShutdownToken(ref _credentialsHandle, _securityContext!); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"ApplyAlertToken() returned {status.ErrorCode}"); if (status.Exception != null) { ExceptionDispatchInfo.Throw(status.Exception); } return null; } return GenerateAlertToken(); } private ProtocolToken GenerateAlertToken() { byte[]? nextmsg = null; SecurityStatusPal status; status = GenerateToken(default, ref nextmsg); return new ProtocolToken(nextmsg, status); } private static TlsAlertMessage GetAlertMessageFromChain(X509Chain chain) { foreach (X509ChainStatus chainStatus in chain.ChainStatus) { if (chainStatus.Status == X509ChainStatusFlags.NoError) { continue; } if ((chainStatus.Status & (X509ChainStatusFlags.UntrustedRoot | X509ChainStatusFlags.PartialChain | X509ChainStatusFlags.Cyclic)) != 0) { return TlsAlertMessage.UnknownCA; } if ((chainStatus.Status & (X509ChainStatusFlags.Revoked | X509ChainStatusFlags.OfflineRevocation)) != 0) { return TlsAlertMessage.CertificateRevoked; } if ((chainStatus.Status & (X509ChainStatusFlags.CtlNotTimeValid | X509ChainStatusFlags.NotTimeNested | X509ChainStatusFlags.NotTimeValid)) != 0) { return TlsAlertMessage.CertificateExpired; } if ((chainStatus.Status & X509ChainStatusFlags.CtlNotValidForUsage) != 0) { return TlsAlertMessage.UnsupportedCert; } if ((chainStatus.Status & (X509ChainStatusFlags.CtlNotSignatureValid | X509ChainStatusFlags.InvalidExtension | X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.InvalidPolicyConstraints) | X509ChainStatusFlags.NoIssuanceChainPolicy | X509ChainStatusFlags.NotValidForUsage) != 0) { return TlsAlertMessage.BadCertificate; } // All other errors: return TlsAlertMessage.CertificateUnknown; } return TlsAlertMessage.BadCertificate; } private void LogCertificateValidation(RemoteCertificateValidationCallback? remoteCertValidationCallback, SslPolicyErrors sslPolicyErrors, bool success, X509Chain chain) { if (!NetEventSource.Log.IsEnabled()) return; if (sslPolicyErrors != SslPolicyErrors.None) { NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_has_errors); if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0) { NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_not_available); } if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) { NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_name_mismatch); } if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0) { string chainStatusString = "ChainStatus: "; foreach (X509ChainStatus chainStatus in chain.ChainStatus) { chainStatusString += "\t" + chainStatus.StatusInformation; } NetEventSource.Log.RemoteCertificateError(this, chainStatusString); } } if (success) { if (remoteCertValidationCallback != null) { NetEventSource.Log.RemoteCertDeclaredValid(this); } else { NetEventSource.Log.RemoteCertHasNoErrors(this); } } else { if (remoteCertValidationCallback != null) { NetEventSource.Log.RemoteCertUserDeclaredInvalid(this); } } } } // ProtocolToken - used to process and handle the return codes from the SSPI wrapper internal sealed class ProtocolToken { internal SecurityStatusPal Status; internal byte[]? Payload; internal int Size; internal bool Failed { get { return ((Status.ErrorCode != SecurityStatusPalErrorCode.OK) && (Status.ErrorCode != SecurityStatusPalErrorCode.ContinueNeeded)); } } internal bool Done { get { return (Status.ErrorCode == SecurityStatusPalErrorCode.OK); } } internal bool Renegotiate { get { return (Status.ErrorCode == SecurityStatusPalErrorCode.Renegotiate); } } internal bool CloseConnection { get { return (Status.ErrorCode == SecurityStatusPalErrorCode.ContextExpired); } } internal ProtocolToken(byte[]? data, SecurityStatusPal status) { Status = status; Payload = data; Size = data != null ? data.Length : 0; } internal Exception? GetException() { // If it's not done, then there's got to be an error, even if it's // a Handshake message up, and we only have a Warning message. return Done ? null : SslStreamPal.GetException(Status); } } }
1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Net.Security/src/System/Net/Security/SslSessionsCache.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.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Security.Authentication; namespace System.Net.Security { // Implements SSL session caching mechanism based on a static table of SSL credentials. internal static class SslSessionsCache { private const int CheckExpiredModulo = 32; private static readonly ConcurrentDictionary<SslCredKey, SafeCredentialReference> s_cachedCreds = new ConcurrentDictionary<SslCredKey, SafeCredentialReference>(); // // Uses certificate thumb-print comparison. // private readonly struct SslCredKey : IEquatable<SslCredKey> { private readonly byte[] _thumbPrint; private readonly int _allowedProtocols; private readonly EncryptionPolicy _encryptionPolicy; private readonly bool _isServerMode; private readonly bool _sendTrustList; // // SECURITY: X509Certificate.GetCertHash() is virtual hence before going here, // the caller of this ctor has to ensure that a user cert object was inspected and // optionally cloned. // internal SslCredKey(byte[]? thumbPrint, int allowedProtocols, bool isServerMode, EncryptionPolicy encryptionPolicy, bool sendTrustList) { _thumbPrint = thumbPrint ?? Array.Empty<byte>(); _allowedProtocols = allowedProtocols; _encryptionPolicy = encryptionPolicy; _isServerMode = isServerMode; _sendTrustList = sendTrustList; } public override int GetHashCode() { int hashCode = 0; if (_thumbPrint.Length > 0) { hashCode ^= _thumbPrint[0]; if (1 < _thumbPrint.Length) { hashCode ^= (_thumbPrint[1] << 8); } if (2 < _thumbPrint.Length) { hashCode ^= (_thumbPrint[2] << 16); } if (3 < _thumbPrint.Length) { hashCode ^= (_thumbPrint[3] << 24); } } hashCode ^= _allowedProtocols; hashCode ^= (int)_encryptionPolicy; hashCode ^= _isServerMode ? 0x10000 : 0x20000; hashCode ^= _sendTrustList ? 0x40000 : 0x80000; return hashCode; } public override bool Equals([NotNullWhen(true)] object? obj) => (obj is SslCredKey && Equals((SslCredKey)obj)); public bool Equals(SslCredKey other) { byte[] thumbPrint = _thumbPrint; byte[] otherThumbPrint = other._thumbPrint; if (thumbPrint.Length != otherThumbPrint.Length) { return false; } if (_encryptionPolicy != other._encryptionPolicy) { return false; } if (_allowedProtocols != other._allowedProtocols) { return false; } if (_isServerMode != other._isServerMode) { return false; } if (_sendTrustList != other._sendTrustList) { return false; } for (int i = 0; i < thumbPrint.Length; ++i) { if (thumbPrint[i] != otherThumbPrint[i]) { return false; } } return true; } } // // Returns null or previously cached cred handle. // // ATTN: The returned handle can be invalid, the callers of InitializeSecurityContext and AcceptSecurityContext // must be prepared to execute a back-out code if the call fails. // internal static SafeFreeCredentials? TryCachedCredential(byte[]? thumbPrint, SslProtocols sslProtocols, bool isServer, EncryptionPolicy encryptionPolicy, bool sendTrustList = false) { if (s_cachedCreds.IsEmpty) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Not found, Current Cache Count = {s_cachedCreds.Count}"); return null; } var key = new SslCredKey(thumbPrint, (int)sslProtocols, isServer, encryptionPolicy, sendTrustList); //SafeCredentialReference? cached; SafeFreeCredentials? credentials = GetCachedCredential(key); if (credentials == null || credentials.IsClosed || credentials.IsInvalid) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Not found or invalid, Current Cache Coun = {s_cachedCreds.Count}"); return null; } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Found a cached Handle = {credentials}"); return credentials; } private static SafeFreeCredentials? GetCachedCredential(SslCredKey key) { return s_cachedCreds.TryGetValue(key, out SafeCredentialReference? cached) ? cached.Target : null; } // // The app is calling this method after starting an SSL handshake. // // ATTN: The thumbPrint must be from inspected and possibly cloned user Cert object or we get a security hole in SslCredKey ctor. // internal static void CacheCredential(SafeFreeCredentials creds, byte[]? thumbPrint, SslProtocols sslProtocols, bool isServer, EncryptionPolicy encryptionPolicy, bool sendTrustList = false) { Debug.Assert(creds != null, "creds == null"); if (creds.IsInvalid) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Refused to cache an Invalid Handle {creds}, Current Cache Count = {s_cachedCreds.Count}"); return; } SslCredKey key = new SslCredKey(thumbPrint, (int)sslProtocols, isServer, encryptionPolicy, sendTrustList); SafeFreeCredentials? credentials = GetCachedCredential(key); if (credentials == null || credentials.IsClosed || credentials.IsInvalid) { lock (s_cachedCreds) { credentials = GetCachedCredential(key); if (credentials == null || credentials.IsClosed || credentials.IsInvalid) { SafeCredentialReference? cached = SafeCredentialReference.CreateReference(creds); if (cached == null) { // Means the handle got closed in between, return it back and let caller deal with the issue. return; } s_cachedCreds[key] = cached; if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Caching New Handle = {creds}, Current Cache Count = {s_cachedCreds.Count}"); ShrinkCredentialCache(); } else { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"CacheCredential() (locked retry) Found already cached Handle = {credentials}"); } } } else { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"CacheCredential() Ignoring incoming handle = {creds} since found already cached Handle = {credentials}"); } static void ShrinkCredentialCache() { // // A simplest way of preventing infinite cache grows. // // Security relief (DoS): // A number of active creds is never greater than a number of _outstanding_ // security sessions, i.e. SSL connections. // So we will try to shrink cache to the number of active creds once in a while. // // We won't shrink cache in the case when NO new handles are coming to it. // if ((s_cachedCreds.Count % CheckExpiredModulo) == 0) { KeyValuePair<SslCredKey, SafeCredentialReference>[] toRemoveAttempt = s_cachedCreds.ToArray(); for (int i = 0; i < toRemoveAttempt.Length; ++i) { SafeCredentialReference? cached = toRemoveAttempt[i].Value; SafeFreeCredentials? creds = cached.Target; if (creds == null) { s_cachedCreds.TryRemove(toRemoveAttempt[i].Key, out _); continue; } cached.Dispose(); cached = SafeCredentialReference.CreateReference(creds); if (cached != null) { s_cachedCreds[toRemoveAttempt[i].Key] = cached; } else { s_cachedCreds.TryRemove(toRemoveAttempt[i].Key, out _); } } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Scavenged cache, New Cache Count = {s_cachedCreds.Count}"); } } } } }
// 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.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Security.Authentication; namespace System.Net.Security { // Implements SSL session caching mechanism based on a static table of SSL credentials. internal static class SslSessionsCache { private const int CheckExpiredModulo = 32; private static readonly ConcurrentDictionary<SslCredKey, SafeCredentialReference> s_cachedCreds = new ConcurrentDictionary<SslCredKey, SafeCredentialReference>(); // // Uses certificate thumb-print comparison. // private readonly struct SslCredKey : IEquatable<SslCredKey> { private readonly byte[] _thumbPrint; private readonly int _allowedProtocols; private readonly EncryptionPolicy _encryptionPolicy; private readonly bool _isServerMode; private readonly bool _sendTrustList; // // SECURITY: X509Certificate.GetCertHash() is virtual hence before going here, // the caller of this ctor has to ensure that a user cert object was inspected and // optionally cloned. // internal SslCredKey(byte[]? thumbPrint, int allowedProtocols, bool isServerMode, EncryptionPolicy encryptionPolicy, bool sendTrustList) { _thumbPrint = thumbPrint ?? Array.Empty<byte>(); _allowedProtocols = allowedProtocols; _encryptionPolicy = encryptionPolicy; _isServerMode = isServerMode; _sendTrustList = sendTrustList; } public override int GetHashCode() { int hashCode = 0; if (_thumbPrint.Length > 0) { hashCode ^= _thumbPrint[0]; if (1 < _thumbPrint.Length) { hashCode ^= (_thumbPrint[1] << 8); } if (2 < _thumbPrint.Length) { hashCode ^= (_thumbPrint[2] << 16); } if (3 < _thumbPrint.Length) { hashCode ^= (_thumbPrint[3] << 24); } } hashCode ^= _allowedProtocols; hashCode ^= (int)_encryptionPolicy; hashCode ^= _isServerMode ? 0x10000 : 0x20000; hashCode ^= _sendTrustList ? 0x40000 : 0x80000; return hashCode; } public override bool Equals([NotNullWhen(true)] object? obj) => (obj is SslCredKey && Equals((SslCredKey)obj)); public bool Equals(SslCredKey other) { byte[] thumbPrint = _thumbPrint; byte[] otherThumbPrint = other._thumbPrint; if (thumbPrint.Length != otherThumbPrint.Length) { return false; } if (_encryptionPolicy != other._encryptionPolicy) { return false; } if (_allowedProtocols != other._allowedProtocols) { return false; } if (_isServerMode != other._isServerMode) { return false; } if (_sendTrustList != other._sendTrustList) { return false; } for (int i = 0; i < thumbPrint.Length; ++i) { if (thumbPrint[i] != otherThumbPrint[i]) { return false; } } return true; } } // // Returns null or previously cached cred handle. // // ATTN: The returned handle can be invalid, the callers of InitializeSecurityContext and AcceptSecurityContext // must be prepared to execute a back-out code if the call fails. // internal static SafeFreeCredentials? TryCachedCredential(byte[]? thumbPrint, SslProtocols sslProtocols, bool isServer, EncryptionPolicy encryptionPolicy, bool sendTrustList = false) { if (s_cachedCreds.IsEmpty) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Not found, Current Cache Count = {s_cachedCreds.Count}"); return null; } var key = new SslCredKey(thumbPrint, (int)sslProtocols, isServer, encryptionPolicy, sendTrustList); //SafeCredentialReference? cached; SafeFreeCredentials? credentials = GetCachedCredential(key); if (credentials == null || credentials.IsClosed || credentials.IsInvalid || credentials.Expiry < DateTime.UtcNow) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Not found or invalid, Current Cache Count = {s_cachedCreds.Count}"); return null; } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Found a cached Handle = {credentials}"); return credentials; } private static SafeFreeCredentials? GetCachedCredential(SslCredKey key) { return s_cachedCreds.TryGetValue(key, out SafeCredentialReference? cached) ? cached.Target : null; } // // The app is calling this method after starting an SSL handshake. // // ATTN: The thumbPrint must be from inspected and possibly cloned user Cert object or we get a security hole in SslCredKey ctor. // internal static void CacheCredential(SafeFreeCredentials creds, byte[]? thumbPrint, SslProtocols sslProtocols, bool isServer, EncryptionPolicy encryptionPolicy, bool sendTrustList = false) { Debug.Assert(creds != null, "creds == null"); if (creds.IsInvalid) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Refused to cache an Invalid Handle {creds}, Current Cache Count = {s_cachedCreds.Count}"); return; } SslCredKey key = new SslCredKey(thumbPrint, (int)sslProtocols, isServer, encryptionPolicy, sendTrustList); SafeFreeCredentials? credentials = GetCachedCredential(key); DateTime utcNow = DateTime.UtcNow; if (credentials == null || credentials.IsClosed || credentials.IsInvalid || credentials.Expiry < utcNow) { lock (s_cachedCreds) { credentials = GetCachedCredential(key); if (credentials == null || credentials.IsClosed || credentials.IsInvalid || credentials.Expiry < utcNow) { SafeCredentialReference? cached = SafeCredentialReference.CreateReference(creds); if (cached == null) { // Means the handle got closed in between, return it back and let caller deal with the issue. return; } s_cachedCreds[key] = cached; if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Caching New Handle = {creds}, Current Cache Count = {s_cachedCreds.Count}"); ShrinkCredentialCache(); } else { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"CacheCredential() (locked retry) Found already cached Handle = {credentials}"); } } } else { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"CacheCredential() Ignoring incoming handle = {creds} since found already cached Handle = {credentials}"); } static void ShrinkCredentialCache() { // // A simplest way of preventing infinite cache grows. // // Security relief (DoS): // A number of active creds is never greater than a number of _outstanding_ // security sessions, i.e. SSL connections. // So we will try to shrink cache to the number of active creds once in a while. // // We won't shrink cache in the case when NO new handles are coming to it. // if ((s_cachedCreds.Count % CheckExpiredModulo) == 0) { KeyValuePair<SslCredKey, SafeCredentialReference>[] toRemoveAttempt = s_cachedCreds.ToArray(); for (int i = 0; i < toRemoveAttempt.Length; ++i) { SafeCredentialReference? cached = toRemoveAttempt[i].Value; SafeFreeCredentials? creds = cached.Target; if (creds == null) { s_cachedCreds.TryRemove(toRemoveAttempt[i].Key, out _); continue; } cached.Dispose(); cached = SafeCredentialReference.CreateReference(creds); if (cached != null) { s_cachedCreds[toRemoveAttempt[i].Key] = cached; } else { s_cachedCreds.TryRemove(toRemoveAttempt[i].Key, out _); } } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Scavenged cache, New Cache Count = {s_cachedCreds.Count}"); } } } } }
1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/tests/JIT/Regression/CLR-x86-JIT/v1-m08/b12668/b12668.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace DefaultNamespace { using System; internal abstract class baseObject { private static int s_count = 0; private static int s_id = 1; public virtual void changeCount(int amount) { if ((s_count + amount) < 0) throw new ArgumentException(); s_count += amount; } internal abstract int getId(); internal abstract float getArea(); public virtual int readId() { return s_id; } public virtual int readcount() { return s_count; } } // baseObject internal class Rectangle : baseObject { public static int count = 0; // same name as base member internal static int id = 2; private float _dimension1; private float _dimension2; internal Rectangle(float d1, float d2) { _dimension1 = _dimension2 = (float)0.0; if ((d1 <= 0.0) || (d2 <= 0.0)) throw new ArgumentException(); _dimension1 = d1; _dimension2 = d2; changeCount(1); } public override void changeCount(int amount) { base.changeCount(amount); if ((count + amount) < 0) throw new ArgumentException(); count += amount; } internal override float getArea() { float area; area = _dimension1 * _dimension2; return area; } public virtual void remove() { changeCount(-1); } internal override int getId() { return Rectangle.id; } } // class Rectangle internal class Circle : baseObject { private float _radius = (float)0.0; public int count = 0; // same name as base member internal int id = 3; internal Circle(float r) { if (r <= 0.0) throw new ArgumentException(); _radius = r; changeCount(1); } public override void changeCount(int amount) { if ((count + amount) < 0) throw new ArgumentException(); count += amount; base.changeCount(amount); } internal override float getArea() { float area; area = (float)(3.14 * _radius * _radius); return area; } internal override int getId() { return id; } virtual public void remove() { changeCount(-1); } } // class Circle public class EAObject { public static int Main(String[] args) { int successes = 0; int result; float area; baseObject[] aObjects = new baseObject[10]; Rectangle rRectangle; Circle rCircle; aObjects[0] = new Rectangle((float)5.0, (float)7.0); result = aObjects[0].getId(); if (result != 2) { return 1; } else successes = 1; area = aObjects[0].getArea(); if (area != 35.0) { return 1; } else successes++; result = aObjects[0].readId(); if (result != 1) { return 1; } else successes++; result = aObjects[0].readcount(); if (result != 1) { return 1; } else successes++; aObjects[1] = new Circle((float)4.0); result = aObjects[1].getId(); if (result != 3) { return 1; } else successes++; area = aObjects[1].getArea(); if (area != (float)(4.0 * 4.0 * 3.14)) { return 1; } else successes++; result = aObjects[1].readcount(); if (result != 2) { return 1; } else successes++; rRectangle = (Rectangle)aObjects[0]; result = Rectangle.count; if (result != 1) { return 1; } else successes++; rCircle = (Circle)aObjects[1]; result = rCircle.count; if (result != 1) { return 1; } else successes++; bool ok = true; int tryvar = 1; try { aObjects[5] = new Rectangle((float)0.0, (float)7.0); tryvar = 2; } catch (ArgumentException /*ae*/ ) { if (tryvar != 1) { return 1; } tryvar = 3; } finally { ok = tryvar == 3; } if (!ok) { return 1; } tryvar = 1; try { aObjects[5] = new Circle((float)0.0); tryvar = 2; } catch (ArgumentException /*ae*/ ) { if (tryvar != 1) { return 1; } tryvar = 3; } finally { ok = tryvar == 3; } if (!ok) { return 1; } try { tryvar = 1; rRectangle.changeCount(-5); } catch (ArgumentException /*ae1*/ ) { tryvar = 2; } finally { ok = tryvar == 2; } if (!ok) { return 1; } aObjects[2] = new Rectangle((float)2.0, (float)3.0); result = aObjects[2].getId(); if (result != 2) { return 1; } else successes++; area = aObjects[2].getArea(); if (area != 6.0) { return 1; } else successes++; result = aObjects[2].readId(); if (result != 1) { return 1; } else successes++; result = aObjects[2].readcount(); if (result != 3) { return 1; } else successes++; aObjects[3] = new Circle((float)8.0); result = aObjects[3].getId(); if (result != 3) { return 1; } else successes++; area = aObjects[3].getArea(); if (area != (float)(8.0 * 8.0 * 3.14)) { return 1; } else successes++; result = aObjects[3].readcount(); if (result != 4) { return 1; } else successes++; rRectangle = (Rectangle)aObjects[0]; result = Rectangle.count; if (result != 2) { return 1; } else successes++; rCircle = (Circle)aObjects[3]; result = rCircle.count; return 100; } // end main() } // end class EAObject }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace DefaultNamespace { using System; internal abstract class baseObject { private static int s_count = 0; private static int s_id = 1; public virtual void changeCount(int amount) { if ((s_count + amount) < 0) throw new ArgumentException(); s_count += amount; } internal abstract int getId(); internal abstract float getArea(); public virtual int readId() { return s_id; } public virtual int readcount() { return s_count; } } // baseObject internal class Rectangle : baseObject { public static int count = 0; // same name as base member internal static int id = 2; private float _dimension1; private float _dimension2; internal Rectangle(float d1, float d2) { _dimension1 = _dimension2 = (float)0.0; if ((d1 <= 0.0) || (d2 <= 0.0)) throw new ArgumentException(); _dimension1 = d1; _dimension2 = d2; changeCount(1); } public override void changeCount(int amount) { base.changeCount(amount); if ((count + amount) < 0) throw new ArgumentException(); count += amount; } internal override float getArea() { float area; area = _dimension1 * _dimension2; return area; } public virtual void remove() { changeCount(-1); } internal override int getId() { return Rectangle.id; } } // class Rectangle internal class Circle : baseObject { private float _radius = (float)0.0; public int count = 0; // same name as base member internal int id = 3; internal Circle(float r) { if (r <= 0.0) throw new ArgumentException(); _radius = r; changeCount(1); } public override void changeCount(int amount) { if ((count + amount) < 0) throw new ArgumentException(); count += amount; base.changeCount(amount); } internal override float getArea() { float area; area = (float)(3.14 * _radius * _radius); return area; } internal override int getId() { return id; } virtual public void remove() { changeCount(-1); } } // class Circle public class EAObject { public static int Main(String[] args) { int successes = 0; int result; float area; baseObject[] aObjects = new baseObject[10]; Rectangle rRectangle; Circle rCircle; aObjects[0] = new Rectangle((float)5.0, (float)7.0); result = aObjects[0].getId(); if (result != 2) { return 1; } else successes = 1; area = aObjects[0].getArea(); if (area != 35.0) { return 1; } else successes++; result = aObjects[0].readId(); if (result != 1) { return 1; } else successes++; result = aObjects[0].readcount(); if (result != 1) { return 1; } else successes++; aObjects[1] = new Circle((float)4.0); result = aObjects[1].getId(); if (result != 3) { return 1; } else successes++; area = aObjects[1].getArea(); if (area != (float)(4.0 * 4.0 * 3.14)) { return 1; } else successes++; result = aObjects[1].readcount(); if (result != 2) { return 1; } else successes++; rRectangle = (Rectangle)aObjects[0]; result = Rectangle.count; if (result != 1) { return 1; } else successes++; rCircle = (Circle)aObjects[1]; result = rCircle.count; if (result != 1) { return 1; } else successes++; bool ok = true; int tryvar = 1; try { aObjects[5] = new Rectangle((float)0.0, (float)7.0); tryvar = 2; } catch (ArgumentException /*ae*/ ) { if (tryvar != 1) { return 1; } tryvar = 3; } finally { ok = tryvar == 3; } if (!ok) { return 1; } tryvar = 1; try { aObjects[5] = new Circle((float)0.0); tryvar = 2; } catch (ArgumentException /*ae*/ ) { if (tryvar != 1) { return 1; } tryvar = 3; } finally { ok = tryvar == 3; } if (!ok) { return 1; } try { tryvar = 1; rRectangle.changeCount(-5); } catch (ArgumentException /*ae1*/ ) { tryvar = 2; } finally { ok = tryvar == 2; } if (!ok) { return 1; } aObjects[2] = new Rectangle((float)2.0, (float)3.0); result = aObjects[2].getId(); if (result != 2) { return 1; } else successes++; area = aObjects[2].getArea(); if (area != 6.0) { return 1; } else successes++; result = aObjects[2].readId(); if (result != 1) { return 1; } else successes++; result = aObjects[2].readcount(); if (result != 3) { return 1; } else successes++; aObjects[3] = new Circle((float)8.0); result = aObjects[3].getId(); if (result != 3) { return 1; } else successes++; area = aObjects[3].getArea(); if (area != (float)(8.0 * 8.0 * 3.14)) { return 1; } else successes++; result = aObjects[3].readcount(); if (result != 4) { return 1; } else successes++; rRectangle = (Rectangle)aObjects[0]; result = Rectangle.count; if (result != 2) { return 1; } else successes++; rCircle = (Circle)aObjects[3]; result = rCircle.count; return 100; } // end main() } // end class EAObject }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // System.Net.HttpStreamAsyncResult // // Authors: // Gonzalo Paniagua Javier ([email protected]) // // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Threading; using System.Threading.Tasks; namespace System.Net { internal sealed class HttpStreamAsyncResult : IAsyncResult { private object _locker = new object(); private ManualResetEvent? _handle; private bool _completed; internal readonly object _parent; internal byte[]? _buffer; internal int _offset; internal int _count; internal AsyncCallback? _callback; internal object? _state; internal int _synchRead; internal Exception? _error; internal bool _endCalled; internal HttpStreamAsyncResult(object parent) { _parent = parent; } public void Complete(Exception e) { _error = e; Complete(); } public void Complete() { lock (_locker) { if (_completed) return; _completed = true; if (_handle != null) _handle.Set(); if (_callback != null) Task.Run(() => _callback(this)); } } public object? AsyncState { get { return _state; } } public WaitHandle AsyncWaitHandle { get { lock (_locker) { if (_handle == null) _handle = new ManualResetEvent(_completed); } return _handle; } } public bool CompletedSynchronously => false; public bool IsCompleted { get { lock (_locker) { return _completed; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // System.Net.HttpStreamAsyncResult // // Authors: // Gonzalo Paniagua Javier ([email protected]) // // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Threading; using System.Threading.Tasks; namespace System.Net { internal sealed class HttpStreamAsyncResult : IAsyncResult { private object _locker = new object(); private ManualResetEvent? _handle; private bool _completed; internal readonly object _parent; internal byte[]? _buffer; internal int _offset; internal int _count; internal AsyncCallback? _callback; internal object? _state; internal int _synchRead; internal Exception? _error; internal bool _endCalled; internal HttpStreamAsyncResult(object parent) { _parent = parent; } public void Complete(Exception e) { _error = e; Complete(); } public void Complete() { lock (_locker) { if (_completed) return; _completed = true; if (_handle != null) _handle.Set(); if (_callback != null) Task.Run(() => _callback(this)); } } public object? AsyncState { get { return _state; } } public WaitHandle AsyncWaitHandle { get { lock (_locker) { if (_handle == null) _handle = new ManualResetEvent(_completed); } return _handle; } } public bool CompletedSynchronously => false; public bool IsCompleted { get { lock (_locker) { return _completed; } } } } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigC14NTransform.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; using System.Xml; namespace System.Security.Cryptography.Xml { public class XmlDsigC14NTransform : Transform { private readonly Type[] _inputTypes = { typeof(Stream), typeof(XmlDocument), typeof(XmlNodeList) }; private readonly Type[] _outputTypes = { typeof(Stream) }; private CanonicalXml _cXml; private readonly bool _includeComments; public XmlDsigC14NTransform() { Algorithm = SignedXml.XmlDsigC14NTransformUrl; } public XmlDsigC14NTransform(bool includeComments) { _includeComments = includeComments; Algorithm = (includeComments ? SignedXml.XmlDsigC14NWithCommentsTransformUrl : SignedXml.XmlDsigC14NTransformUrl); } public override Type[] InputTypes { get { return _inputTypes; } } public override Type[] OutputTypes { get { return _outputTypes; } } public override void LoadInnerXml(XmlNodeList nodeList) { if (nodeList != null && nodeList.Count > 0) throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); } protected override XmlNodeList GetInnerXml() { return null; } public override void LoadInput(object obj) { XmlResolver resolver = (ResolverSet ? _xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), BaseURI)); if (obj is Stream) { _cXml = new CanonicalXml((Stream)obj, _includeComments, resolver, BaseURI); return; } if (obj is XmlDocument) { _cXml = new CanonicalXml((XmlDocument)obj, resolver, _includeComments); return; } if (obj is XmlNodeList) { _cXml = new CanonicalXml((XmlNodeList)obj, resolver, _includeComments); } else { throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(obj)); } } public override object GetOutput() { return new MemoryStream(_cXml.GetBytes()); } public override object GetOutput(Type type) { if (type != typeof(Stream) && !type.IsSubclassOf(typeof(Stream))) throw new ArgumentException(SR.Cryptography_Xml_TransformIncorrectInputType, nameof(type)); return new MemoryStream(_cXml.GetBytes()); } public override byte[] GetDigestedOutput(HashAlgorithm hash) { return _cXml.GetDigestedBytes(hash); } } }
// 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; using System.Xml; namespace System.Security.Cryptography.Xml { public class XmlDsigC14NTransform : Transform { private readonly Type[] _inputTypes = { typeof(Stream), typeof(XmlDocument), typeof(XmlNodeList) }; private readonly Type[] _outputTypes = { typeof(Stream) }; private CanonicalXml _cXml; private readonly bool _includeComments; public XmlDsigC14NTransform() { Algorithm = SignedXml.XmlDsigC14NTransformUrl; } public XmlDsigC14NTransform(bool includeComments) { _includeComments = includeComments; Algorithm = (includeComments ? SignedXml.XmlDsigC14NWithCommentsTransformUrl : SignedXml.XmlDsigC14NTransformUrl); } public override Type[] InputTypes { get { return _inputTypes; } } public override Type[] OutputTypes { get { return _outputTypes; } } public override void LoadInnerXml(XmlNodeList nodeList) { if (nodeList != null && nodeList.Count > 0) throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); } protected override XmlNodeList GetInnerXml() { return null; } public override void LoadInput(object obj) { XmlResolver resolver = (ResolverSet ? _xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), BaseURI)); if (obj is Stream) { _cXml = new CanonicalXml((Stream)obj, _includeComments, resolver, BaseURI); return; } if (obj is XmlDocument) { _cXml = new CanonicalXml((XmlDocument)obj, resolver, _includeComments); return; } if (obj is XmlNodeList) { _cXml = new CanonicalXml((XmlNodeList)obj, resolver, _includeComments); } else { throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(obj)); } } public override object GetOutput() { return new MemoryStream(_cXml.GetBytes()); } public override object GetOutput(Type type) { if (type != typeof(Stream) && !type.IsSubclassOf(typeof(Stream))) throw new ArgumentException(SR.Cryptography_Xml_TransformIncorrectInputType, nameof(type)); return new MemoryStream(_cXml.GetBytes()); } public override byte[] GetDigestedOutput(HashAlgorithm hash) { return _cXml.GetDigestedBytes(hash); } } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Private.Xml/src/System/Xml/Core/ValidationType.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 { // Specifies the type of validation to perform in XmlValidatingReader or in XmlReaderSettings. public enum ValidationType { // No validation will be performed. None, // In XmlValidatingReader ValidationType.Auto does the following: // 1) If there is no DTD or schema, it will parse the XML without validation. // 2) If there is a DTD defined in a <!DOCTYPE ...> declaration, it will load the DTD and // process the DTD declarations such that default attributes and general entities will // be made available. General entities are only loaded and parsed if they are used (expanded). // 3) If there is no <!DOCTYPE ...> declaration but there is an XSD "schemaLocation" attribute, // it will load and process those XSD schemas and it will return any default attributes defined in those schemas. // 4) If there is no <!DOCTYPE ...&> declaration and no XSD "schemaLocation" attribute but there are some namespaces // using the MSXML "x-schema:" URN prefix, it will load and process those schemas and it will return any default // attributes defined in those schemas. [Obsolete("ValidationType.Auto has been deprecated. Use DTD or Schema instead.")] Auto, // Validate according to DTD. DTD, // Validate according to XDR. [Obsolete("XDR Validation through XmlValidatingReader has been deprecated and is not supported.")] XDR, // Validate according to W3C XSD schemas, including inline schemas. An error is returned if both XDR and XSD schemas // are referenced from the same document. Schema } }
// 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 { // Specifies the type of validation to perform in XmlValidatingReader or in XmlReaderSettings. public enum ValidationType { // No validation will be performed. None, // In XmlValidatingReader ValidationType.Auto does the following: // 1) If there is no DTD or schema, it will parse the XML without validation. // 2) If there is a DTD defined in a <!DOCTYPE ...> declaration, it will load the DTD and // process the DTD declarations such that default attributes and general entities will // be made available. General entities are only loaded and parsed if they are used (expanded). // 3) If there is no <!DOCTYPE ...> declaration but there is an XSD "schemaLocation" attribute, // it will load and process those XSD schemas and it will return any default attributes defined in those schemas. // 4) If there is no <!DOCTYPE ...&> declaration and no XSD "schemaLocation" attribute but there are some namespaces // using the MSXML "x-schema:" URN prefix, it will load and process those schemas and it will return any default // attributes defined in those schemas. [Obsolete("ValidationType.Auto has been deprecated. Use DTD or Schema instead.")] Auto, // Validate according to DTD. DTD, // Validate according to XDR. [Obsolete("XDR Validation through XmlValidatingReader has been deprecated and is not supported.")] XDR, // Validate according to W3C XSD schemas, including inline schemas. An error is returned if both XDR and XSD schemas // are referenced from the same document. Schema } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/Common/src/Interop/Windows/Crypt32/Interop.CertControlStore.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.InteropServices; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Crypt32 { [LibraryImport(Libraries.Crypt32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool CertControlStore(SafeCertStoreHandle hCertStore, CertControlStoreFlags dwFlags, CertControlStoreType dwControlType, IntPtr pvCtrlPara); } }
// 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.InteropServices; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Crypt32 { [LibraryImport(Libraries.Crypt32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool CertControlStore(SafeCertStoreHandle hCertStore, CertControlStoreFlags dwFlags, CertControlStoreType dwControlType, IntPtr pvCtrlPara); } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Speech/src/Recognition/IRecognizerInternal.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.Speech.Recognition { // Interface that all recognizers must implement in order to connect to Grammar and RecognitionResult. internal interface IRecognizerInternal { #region Internal Methods void SetGrammarState(Grammar grammar, bool enabled); void SetGrammarWeight(Grammar grammar, float weight); void SetGrammarPriority(Grammar grammar, int priority); Grammar GetGrammarFromId(ulong id); void SetDictationContext(Grammar grammar, string precedingText, string subsequentText); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Speech.Recognition { // Interface that all recognizers must implement in order to connect to Grammar and RecognitionResult. internal interface IRecognizerInternal { #region Internal Methods void SetGrammarState(Grammar grammar, bool enabled); void SetGrammarWeight(Grammar grammar, float weight); void SetGrammarPriority(Grammar grammar, int priority); Grammar GetGrammarFromId(ulong id); void SetDictationContext(Grammar grammar, string precedingText, string subsequentText); #endregion } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.ComponentModel.TypeConverter/tests/Timers/TimersDescriptionAttributeTests.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 Xunit; namespace System.Timers.Tests { public class TimersDescriptionAttributeTests { [Theory] [InlineData("")] [InlineData("description")] public void Ctor_String(string description) { var attribute = new TimersDescriptionAttribute(description); Assert.Equal(description, attribute.Description); Assert.Same(attribute.Description, attribute.Description); } [Fact] public void Ctor_String_String() { PropertyInfo autoResetProperty = typeof(Timer).GetProperty(nameof(Timer.AutoReset)); TimersDescriptionAttribute attribute = autoResetProperty.GetCustomAttribute<TimersDescriptionAttribute>(); Assert.NotEmpty(attribute.Description); Assert.Same(attribute.Description, attribute.Description); } [Fact] public void Description_GetWithNullDescription_ThrowsArgumentNullException() { var attribute = new TimersDescriptionAttribute(null); AssertExtensions.Throws<ArgumentNullException>("format", "name", () => attribute.Description); // Only the first call fails. Assert.Null(attribute.Description); } } }
// 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 Xunit; namespace System.Timers.Tests { public class TimersDescriptionAttributeTests { [Theory] [InlineData("")] [InlineData("description")] public void Ctor_String(string description) { var attribute = new TimersDescriptionAttribute(description); Assert.Equal(description, attribute.Description); Assert.Same(attribute.Description, attribute.Description); } [Fact] public void Ctor_String_String() { PropertyInfo autoResetProperty = typeof(Timer).GetProperty(nameof(Timer.AutoReset)); TimersDescriptionAttribute attribute = autoResetProperty.GetCustomAttribute<TimersDescriptionAttribute>(); Assert.NotEmpty(attribute.Description); Assert.Same(attribute.Description, attribute.Description); } [Fact] public void Description_GetWithNullDescription_ThrowsArgumentNullException() { var attribute = new TimersDescriptionAttribute(null); AssertExtensions.Throws<ArgumentNullException>("format", "name", () => attribute.Description); // Only the first call fails. Assert.Null(attribute.Description); } } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/tests/JIT/HardwareIntrinsics/General/Vector64_1/GetAndWithElement.Int16.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\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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementInt163() { var test = new VectorGetAndWithElement__GetAndWithElementInt163(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementInt163 { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 3, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Int16[] values = new Int16[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetInt16(); } Vector64<Int16> value = Vector64.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { Int16 result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Int16.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Int16 insertedValue = TestLibrary.Generator.GetInt16(); try { Vector64<Int16> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Int16.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 3, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Int16[] values = new Int16[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetInt16(); } Vector64<Int16> value = Vector64.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector64) .GetMethod(nameof(Vector64.GetElement)) .MakeGenericMethod(typeof(Int16)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((Int16)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Int16.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Int16 insertedValue = TestLibrary.Generator.GetInt16(); try { object result2 = typeof(Vector64) .GetMethod(nameof(Vector64.WithElement)) .MakeGenericMethod(typeof(Int16)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector64<Int16>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Int16.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(3 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(3 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(3 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(3 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(Int16 result, Int16[] values, [CallerMemberName] string method = "") { if (result != values[3]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector64<Int16.GetElement(3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector64<Int16> result, Int16[] values, Int16 insertedValue, [CallerMemberName] string method = "") { Int16[] resultElements = new Int16[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(Int16[] result, Int16[] values, Int16 insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 3) && (result[i] != values[i])) { succeeded = false; break; } } if (result[3] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Int16.WithElement(3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); 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\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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementInt163() { var test = new VectorGetAndWithElement__GetAndWithElementInt163(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementInt163 { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 3, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Int16[] values = new Int16[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetInt16(); } Vector64<Int16> value = Vector64.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { Int16 result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Int16.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Int16 insertedValue = TestLibrary.Generator.GetInt16(); try { Vector64<Int16> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Int16.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 3, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Int16[] values = new Int16[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetInt16(); } Vector64<Int16> value = Vector64.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector64) .GetMethod(nameof(Vector64.GetElement)) .MakeGenericMethod(typeof(Int16)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((Int16)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Int16.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Int16 insertedValue = TestLibrary.Generator.GetInt16(); try { object result2 = typeof(Vector64) .GetMethod(nameof(Vector64.WithElement)) .MakeGenericMethod(typeof(Int16)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector64<Int16>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Int16.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(3 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(3 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(3 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(3 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(Int16 result, Int16[] values, [CallerMemberName] string method = "") { if (result != values[3]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector64<Int16.GetElement(3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector64<Int16> result, Int16[] values, Int16 insertedValue, [CallerMemberName] string method = "") { Int16[] resultElements = new Int16[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(Int16[] result, Int16[] values, Int16 insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 3) && (result[i] != values[i])) { succeeded = false; break; } } if (result[3] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Int16.WithElement(3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/Common/tests/Tests/System/IO/PathInternal.Tests.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; using System.Text; using Xunit; namespace Tests.System.IO { public class PathInternal_Windows_Tests { [Theory, InlineData("", "", true, 0), InlineData("", "", false, 0), InlineData("a", "", true, 0), InlineData("a", "", false, 0), InlineData("", "b", true, 0), InlineData("", "b", false, 0), InlineData("\0", "\0", true, 1), InlineData("\0", "\0", false, 1), InlineData("ABcd", "ABCD", true, 4), InlineData("ABCD", "ABcd", true, 4), InlineData("ABcd", "ABCD", false, 2), InlineData("ABCD", "ABcd", false, 2), InlineData("AB\0cd", "AB\0CD", true, 5), InlineData("AB\0CD", "AB\0cd", true, 5), InlineData("AB\0cd", "AB\0CD", false, 3), InlineData("AB\0CD", "AB\0cd", false, 3), InlineData("ABc\0", "ABC\0", true, 4), InlineData("ABC\0", "ABc\0", true, 4), InlineData("ABc\0", "ABC\0", false, 2), InlineData("ABC\0", "ABc\0", false, 2), InlineData("ABcdxyzl", "ABCDpdq", true, 4), InlineData("ABCDxyz", "ABcdpdql", true, 4), InlineData("ABcdxyz", "ABCDpdq", false, 2), InlineData("ABCDxyzoo", "ABcdpdq", false, 2)] public void EqualStartingCharacterCount(string first, string second, bool ignoreCase, int expected) { Assert.Equal(expected, PathInternal.EqualStartingCharacterCount(first, second, ignoreCase)); } [Theory, InlineData(@"", @"", true, 0), InlineData(@"", @"", false, 0), InlineData(@"a", @"A", true, 1), InlineData(@"A", @"a", true, 1), InlineData(@"a", @"A", false, 0), InlineData(@"A", @"a", false, 0), InlineData(@"foo", @"foobar", true, 0), InlineData(@"foo", @"foobar", false, 0), InlineData(@"foo", @"foo/bar", true, 3), InlineData(@"foo", @"foo/bar", false, 3), InlineData(@"foo/", @"foo/bar", true, 4), InlineData(@"foo/", @"foo/bar", false, 4), InlineData(@"foo/bar", @"foo/bar", true, 7), InlineData(@"foo/bar", @"foo/bar", false, 7), InlineData(@"foo/bar", @"foo/BAR", true, 7), InlineData(@"foo/bar", @"foo/BAR", false, 4), InlineData(@"foo/bar", @"foo/barb", true, 4), InlineData(@"foo/bar", @"foo/barb", false, 4)] public void GetCommonPathLength(string first, string second, bool ignoreCase, int expected) { Assert.Equal(expected, PathInternal.GetCommonPathLength(first, second, ignoreCase)); } public static TheoryData<string, int, string> RemoveRelativeSegmentsData => new TheoryData<string, int, string> { { @"C:\git\runtime", 2, @"C:\git\runtime"}, { @"C:\\git\runtime", 2, @"C:\git\runtime"}, { @"C:\git\\runtime", 2, @"C:\git\runtime"}, { @"C:\git\.\runtime\.\\", 2, @"C:\git\runtime\"}, { @"C:\git\runtime", 2, @"C:\git\runtime"}, { @"C:\git\..\runtime", 2, @"C:\runtime"}, { @"C:\git\runtime\..\", 2, @"C:\git\"}, { @"C:\git\runtime\..\..\..\", 2, @"C:\"}, { @"C:\git\runtime\..\..\.\", 2, @"C:\"}, { @"C:\git\..\.\runtime\temp\..", 2, @"C:\runtime"}, { @"C:\git\..\\\.\..\runtime", 2, @"C:\runtime"}, { @"C:\git\runtime\", 2, @"C:\git\runtime\"}, { @"C:\git\temp\..\runtime\", 2, @"C:\git\runtime\"}, { @"C:\.", 3, @"C:\"}, { @"C:\..", 3, @"C:\"}, { @"C:\..\..", 3, @"C:\"}, { @"C:\.", 2, @"C:"}, { @"C:\..", 2, @"C:"}, { @"C:\..\..", 2, @"C:"}, { @"C:A\.", 2, @"C:A"}, { @"C:A\..", 2, @"C:"}, { @"C:A\..\..", 2, @"C:"}, { @"C:A\..\..\..", 2, @"C:"}, { @"C:\tmp\home", 3, @"C:\tmp\home" }, { @"C:\tmp\..", 3, @"C:\" }, { @"C:\tmp\home\..\.\.\", 3, @"C:\tmp\" }, { @"C:\tmp\..\..\..\", 3, @"C:\" }, { @"C:\tmp\\home", 3, @"C:\tmp\home" }, { @"C:\.\tmp\\home", 3, @"C:\tmp\home" }, { @"C:\..\tmp\home", 3, @"C:\tmp\home" }, { @"C:\..\..\..\tmp\.\home", 3, @"C:\tmp\home" }, { @"C:\\tmp\\\home", 3, @"C:\tmp\home" }, { @"C:\tmp\home\git\.\..\.\git\runtime\..\", 3, @"C:\tmp\home\git\" }, { @"C:\.\tmp\home", 3, @"C:\tmp\home" }, { @"C:\tmp\home", 6, @"C:\tmp\home" }, { @"C:\tmp\..", 6, @"C:\tmp" }, { @"C:\tmp\home\..\.\.\", 5, @"C:\tmp\" }, { @"C:\tmp\..\..\..\", 6, @"C:\tmp\" }, { @"C:\tmp\\home", 5, @"C:\tmp\home" }, { @"C:\.\tmp\\home", 4, @"C:\.\tmp\home" }, { @"C:\..\tmp\home", 5, @"C:\..\tmp\home" }, { @"C:\..\..\..\tmp\.\home", 6, @"C:\..\tmp\home" }, { @"C:\\tmp\\\home", 7, @"C:\\tmp\home" }, { @"C:\tmp\home\git\.\..\.\git\runtime\..\", 7, @"C:\tmp\home\git\" }, { @"C:\.\tmp\home", 5, @"C:\.\tmp\home" }, { @"C:\tmp\..", 2, @"C:\" }, { @"C:\tmp\home\..\..\.\", 2, @"C:\" }, { @"C:\tmp\..\..\..\", 2, @"C:\" }, { @"C:\tmp\\home", 2, @"C:\tmp\home" }, { @"C:\.\tmp\\home", 2, @"C:\tmp\home" }, { @"C:\..\tmp\home", 2, @"C:\tmp\home" }, { @"C:\..\..\..\tmp\.\home", 2, @"C:\tmp\home" }, { @"C:\\tmp\\\home", 2, @"C:\tmp\home" }, { @"C:\tmp\home\git\.\..\.\git\runtime\..\", 2, @"C:\tmp\home\git\" }, { @"C:\.\tmp\home", 2, @"C:\tmp\home" }, { @"C:\tmp\..\..\", 10, @"C:\tmp\..\" }, { @"C:\tmp\home\..\.\.\", 12, @"C:\tmp\home\" }, { @"C:\tmp\..\..\..\", 10, @"C:\tmp\..\" }, { @"C:\tmp\\home\..\.\\", 13, @"C:\tmp\\home\" }, { @"C:\.\tmp\\home\git\git", 9, @"C:\.\tmp\home\git\git" }, { @"C:\..\tmp\.\home", 10, @"C:\..\tmp\home" }, { @"C:\..\..\..\tmp\.\home", 10, @"C:\..\..\..\tmp\home" }, { @"C:\\tmp\\\home\..", 7, @"C:\\tmp\" }, { @"C:\tmp\home\git\.\..\.\git\runtime\..\", 18, @"C:\tmp\home\git\.\git\" }, { @"C:\.\tmp\home\.\.\", 9, @"C:\.\tmp\home\" }, }; public static TheoryData<string, int, string> RemoveRelativeSegmentsFirstRelativeSegment => new TheoryData<string, int, string> { { @"C:\\git\runtime", 2, @"C:\git\runtime"}, { @"C:\.\git\runtime", 2, @"C:\git\runtime"}, { @"C:\\.\git\.\runtime", 2, @"C:\git\runtime"}, { @"C:\..\git\runtime", 2, @"C:\git\runtime"}, { @"C:\.\git\..\runtime", 2, @"C:\runtime"}, { @"C:\.\git\runtime\..\", 2, @"C:\git\"}, { @"C:\.\git\runtime\..\..\..\", 2, @"C:\"}, { @"C:\.\git\runtime\..\..\.\", 2, @"C:\"}, { @"C:\.\git\..\.\runtime\temp\..", 2, @"C:\runtime"}, { @"C:\.\git\..\\\.\..\runtime", 2, @"C:\runtime"}, { @"C:\.\git\runtime\", 2, @"C:\git\runtime\"}, { @"C:\.\git\temp\..\runtime\", 2, @"C:\git\runtime\"}, { @"C:\\..\..", 3, @"C:\"} }; public static TheoryData<string, int, string> RemoveRelativeSegmentsSkipAboveRoot => new TheoryData<string, int, string> { { @"C:\temp\..\" , 7, @"C:\temp\" }, { @"C:\temp\..\git" , 7, @"C:\temp\git" }, { @"C:\temp\..\git" , 8, @"C:\temp\git" }, { @"C:\temp\..\.\" , 8, @"C:\temp\" }, { @"C:\temp\..\" , 9, @"C:\temp\..\" }, { @"C:\temp\..\git" , 9, @"C:\temp\..\git" }, { @"C:\git\..\temp\..\" , 15, @"C:\git\..\temp\" }, { @"C:\\\.\..\..\temp\..\" , 17, @"C:\\\.\..\..\temp\" }, }; public static TheoryData<string, int, string> RemoveRelativeSegmentsFirstRelativeSegmentRoot => new TheoryData<string, int, string> { { @"C:\\git\runtime", 3, @"C:\git\runtime"}, { @"C:\.\git\runtime", 3, @"C:\git\runtime"}, { @"C:\\.\git\.\runtime", 3, @"C:\git\runtime"}, { @"C:\..\git\runtime", 3, @"C:\git\runtime"}, { @"C:\.\git\..\runtime", 3, @"C:\runtime"}, { @"C:\.\git\runtime\..\", 3, @"C:\git\"}, { @"C:\.\git\runtime\..\..\..\", 3, @"C:\"}, { @"C:\.\git\runtime\..\..\.\", 3, @"C:\"}, { @"C:\.\git\..\.\runtime\temp\..", 3, @"C:\runtime"}, { @"C:\.\git\..\\\.\..\runtime", 3, @"C:\runtime"}, { @"C:\.\git\runtime\", 3, @"C:\git\runtime\"}, { @"C:\.\git\temp\..\runtime\", 3, @"C:\git\runtime\"}, }; [Theory, MemberData(nameof(RemoveRelativeSegmentsData)), MemberData(nameof(RemoveRelativeSegmentsFirstRelativeSegment)), MemberData(nameof(RemoveRelativeSegmentsFirstRelativeSegmentRoot)), MemberData(nameof(RemoveRelativeSegmentsSkipAboveRoot))] [PlatformSpecific(TestPlatforms.Windows)] public void RemoveRelativeSegmentsTest(string path, int skip, string expected) { Assert.Equal(expected, PathInternal.RemoveRelativeSegments(path, skip)); Assert.Equal(@"\\.\" + expected, PathInternal.RemoveRelativeSegments(@"\\.\" + path, skip + 4)); Assert.Equal(@"\\?\" + expected, PathInternal.RemoveRelativeSegments(@"\\?\" + path, skip + 4)); } public static TheoryData<string, int, string> RemoveRelativeSegmentsUncData => new TheoryData<string, int, string> { { @"Server\Share\git\runtime", 12, @"Server\Share\git\runtime"}, { @"Server\Share\\git\runtime", 12, @"Server\Share\git\runtime"}, { @"Server\Share\git\\runtime", 12, @"Server\Share\git\runtime"}, { @"Server\Share\git\.\runtime\.\\", 12, @"Server\Share\git\runtime\"}, { @"Server\Share\git\runtime", 12, @"Server\Share\git\runtime"}, { @"Server\Share\git\..\runtime", 12, @"Server\Share\runtime"}, { @"Server\Share\git\runtime\..\", 12, @"Server\Share\git\"}, { @"Server\Share\git\runtime\..\..\..\", 12, @"Server\Share\"}, { @"Server\Share\git\runtime\..\..\.\", 12, @"Server\Share\"}, { @"Server\Share\git\..\.\runtime\temp\..", 12, @"Server\Share\runtime"}, { @"Server\Share\git\..\\\.\..\runtime", 12, @"Server\Share\runtime"}, { @"Server\Share\git\runtime\", 12, @"Server\Share\git\runtime\"}, { @"Server\Share\git\temp\..\runtime\", 12, @"Server\Share\git\runtime\"}, }; [Theory, MemberData(nameof(RemoveRelativeSegmentsUncData))] [PlatformSpecific(TestPlatforms.Windows)] public void RemoveRelativeSegmentsUncTest(string path, int skip, string expected) { Assert.Equal(@"\\" + expected, PathInternal.RemoveRelativeSegments(@"\\" + path, skip + 2)); Assert.Equal(@"\\.\UNC\" + expected, PathInternal.RemoveRelativeSegments(@"\\.\UNC\" + path, skip + 8)); Assert.Equal(@"\\?\UNC\" + expected, PathInternal.RemoveRelativeSegments(@"\\?\UNC\" + path, skip + 8)); } public static TheoryData<string, int, string> RemoveRelativeSegmentsDeviceData => new TheoryData<string, int, string> { { @"\\.\git\runtime", 7, @"\\.\git\runtime"}, { @"\\.\git\runtime", 7, @"\\.\git\runtime"}, { @"\\.\git\\runtime", 7, @"\\.\git\runtime"}, { @"\\.\git\.\runtime\.\\", 7, @"\\.\git\runtime\"}, { @"\\.\git\runtime", 7, @"\\.\git\runtime"}, { @"\\.\git\..\runtime", 7, @"\\.\git\runtime"}, { @"\\.\git\runtime\..\", 7, @"\\.\git\"}, { @"\\.\git\runtime\..\..\..\", 7, @"\\.\git\"}, { @"\\.\git\runtime\..\..\.\", 7, @"\\.\git\"}, { @"\\.\git\..\.\runtime\temp\..", 7, @"\\.\git\runtime"}, { @"\\.\git\..\\\.\..\runtime", 7, @"\\.\git\runtime"}, { @"\\.\git\runtime\", 7, @"\\.\git\runtime\"}, { @"\\.\git\temp\..\runtime\", 7, @"\\.\git\runtime\"}, { @"\\.\.\runtime", 5, @"\\.\.\runtime"}, { @"\\.\.\runtime", 5, @"\\.\.\runtime"}, { @"\\.\.\\runtime", 5, @"\\.\.\runtime"}, { @"\\.\.\.\runtime\.\\", 5, @"\\.\.\runtime\"}, { @"\\.\.\runtime", 5, @"\\.\.\runtime"}, { @"\\.\.\..\runtime", 5, @"\\.\.\runtime"}, { @"\\.\.\runtime\..\", 5, @"\\.\.\"}, { @"\\.\.\runtime\..\..\..\", 5, @"\\.\.\"}, { @"\\.\.\runtime\..\..\.\", 5, @"\\.\.\"}, { @"\\.\.\..\.\runtime\temp\..", 5, @"\\.\.\runtime"}, { @"\\.\.\..\\\.\..\runtime", 5, @"\\.\.\runtime"}, { @"\\.\.\runtime\", 5, @"\\.\.\runtime\"}, { @"\\.\.\temp\..\runtime\", 5, @"\\.\.\runtime\"}, { @"\\.\..\runtime", 6, @"\\.\..\runtime"}, { @"\\.\..\runtime", 6, @"\\.\..\runtime"}, { @"\\.\..\\runtime", 6, @"\\.\..\runtime"}, { @"\\.\..\.\runtime\.\\", 6, @"\\.\..\runtime\"}, { @"\\.\..\runtime", 6, @"\\.\..\runtime"}, { @"\\.\..\..\runtime", 6, @"\\.\..\runtime"}, { @"\\.\..\runtime\..\", 6, @"\\.\..\"}, { @"\\.\..\runtime\..\..\..\", 6, @"\\.\..\"}, { @"\\.\..\runtime\..\..\.\", 6, @"\\.\..\"}, { @"\\.\..\..\.\runtime\temp\..", 6, @"\\.\..\runtime"}, { @"\\.\..\..\\\.\..\runtime", 6, @"\\.\..\runtime"}, { @"\\.\..\runtime\", 6, @"\\.\..\runtime\"}, { @"\\.\..\temp\..\runtime\", 6, @"\\.\..\runtime\"}, { @"\\.\\runtime", 4, @"\\.\runtime"}, { @"\\.\\runtime", 4, @"\\.\runtime"}, { @"\\.\\\runtime", 4, @"\\.\runtime"}, { @"\\.\\.\runtime\.\\", 4, @"\\.\runtime\"}, { @"\\.\\runtime", 4, @"\\.\runtime"}, { @"\\.\\..\runtime", 4, @"\\.\runtime"}, { @"\\.\\runtime\..\", 4, @"\\.\"}, { @"\\.\\runtime\..\..\..\", 4, @"\\.\"}, { @"\\.\\runtime\..\..\.\", 4, @"\\.\"}, { @"\\.\\..\.\runtime\temp\..", 4, @"\\.\runtime"}, { @"\\.\\..\\\.\..\runtime", 4, @"\\.\runtime"}, { @"\\.\\runtime\", 4, @"\\.\runtime\"}, { @"\\.\\temp\..\runtime\", 4, @"\\.\runtime\"}, }; public static TheoryData<string, int, string> RemoveRelativeSegmentsDeviceRootData => new TheoryData<string, int, string> { { @"\\.\git\runtime", 8, @"\\.\git\runtime"}, { @"\\.\git\runtime", 8, @"\\.\git\runtime"}, { @"\\.\git\\runtime", 8, @"\\.\git\runtime"}, { @"\\.\git\.\runtime\.\\", 8, @"\\.\git\runtime\"}, { @"\\.\git\runtime", 8, @"\\.\git\runtime"}, { @"\\.\git\..\runtime", 8, @"\\.\git\runtime"}, { @"\\.\git\runtime\..\", 8, @"\\.\git\"}, { @"\\.\git\runtime\..\..\..\", 8, @"\\.\git\"}, { @"\\.\git\runtime\..\..\.\", 8, @"\\.\git\"}, { @"\\.\git\..\.\runtime\temp\..", 8, @"\\.\git\runtime"}, { @"\\.\git\..\\\.\..\runtime", 8, @"\\.\git\runtime"}, { @"\\.\git\runtime\", 8, @"\\.\git\runtime\"}, { @"\\.\git\temp\..\runtime\", 8, @"\\.\git\runtime\"}, { @"\\.\.\runtime", 6, @"\\.\.\runtime"}, { @"\\.\.\runtime", 6, @"\\.\.\runtime"}, { @"\\.\.\\runtime", 6, @"\\.\.\runtime"}, { @"\\.\.\.\runtime\.\\", 6, @"\\.\.\runtime\"}, { @"\\.\.\runtime", 6, @"\\.\.\runtime"}, { @"\\.\.\..\runtime", 6, @"\\.\.\runtime"}, { @"\\.\.\runtime\..\", 6, @"\\.\.\"}, { @"\\.\.\runtime\..\..\..\", 6, @"\\.\.\"}, { @"\\.\.\runtime\..\..\.\", 6, @"\\.\.\"}, { @"\\.\.\..\.\runtime\temp\..", 6, @"\\.\.\runtime"}, { @"\\.\.\..\\\.\..\runtime", 6, @"\\.\.\runtime"}, { @"\\.\.\runtime\", 6, @"\\.\.\runtime\"}, { @"\\.\.\temp\..\runtime\", 6, @"\\.\.\runtime\"}, { @"\\.\..\runtime", 7, @"\\.\..\runtime"}, { @"\\.\..\runtime", 7, @"\\.\..\runtime"}, { @"\\.\..\\runtime", 7, @"\\.\..\runtime"}, { @"\\.\..\.\runtime\.\\", 7, @"\\.\..\runtime\"}, { @"\\.\..\runtime", 7, @"\\.\..\runtime"}, { @"\\.\..\..\runtime", 7, @"\\.\..\runtime"}, { @"\\.\..\runtime\..\", 7, @"\\.\..\"}, { @"\\.\..\runtime\..\..\..\", 7, @"\\.\..\"}, { @"\\.\..\runtime\..\..\.\", 7, @"\\.\..\"}, { @"\\.\..\..\.\runtime\temp\..", 7, @"\\.\..\runtime"}, { @"\\.\..\..\\\.\..\runtime", 7, @"\\.\..\runtime"}, { @"\\.\..\runtime\", 7, @"\\.\..\runtime\"}, { @"\\.\..\temp\..\runtime\", 7, @"\\.\..\runtime\"}, { @"\\.\\runtime", 5, @"\\.\\runtime"}, { @"\\.\\runtime", 5, @"\\.\\runtime"}, { @"\\.\\\runtime", 5, @"\\.\\runtime"}, { @"\\.\\.\runtime\.\\", 5, @"\\.\\runtime\"}, { @"\\.\\runtime", 5, @"\\.\\runtime"}, { @"\\.\\..\runtime", 5, @"\\.\\runtime"}, { @"\\.\\runtime\..\", 5, @"\\.\\"}, { @"\\.\\runtime\..\..\..\", 5, @"\\.\\"}, { @"\\.\\runtime\..\..\.\", 5, @"\\.\\"}, { @"\\.\\..\.\runtime\temp\..", 5, @"\\.\\runtime"}, { @"\\.\\..\\\.\..\runtime", 5, @"\\.\\runtime"}, { @"\\.\\runtime\", 5, @"\\.\\runtime\"}, { @"\\.\\temp\..\runtime\", 5, @"\\.\\runtime\"}, }; [Theory, MemberData(nameof(RemoveRelativeSegmentsDeviceData)), MemberData(nameof(RemoveRelativeSegmentsDeviceRootData))] [PlatformSpecific(TestPlatforms.Windows)] public void RemoveRelativeSegmentsDeviceTest(string path, int skip, string expected) { Assert.Equal(expected, PathInternal.RemoveRelativeSegments(path, skip)); StringBuilder sb = new StringBuilder(expected); sb.Replace('.', '?', 0, 4); expected = sb.ToString(); sb = new StringBuilder(path); sb.Replace('.', '?', 0, 4); path = sb.ToString(); Assert.Equal(expected, PathInternal.RemoveRelativeSegments(path, skip)); } public static TheoryData<string, int, string> RemoveRelativeSegmentUnixData => new TheoryData<string, int, string> { { "/tmp/home", 1, "/tmp/home" }, { "/tmp/..", 1, "/" }, { "/tmp/home/../././", 1, "/tmp/" }, { "/tmp/../../../", 1, "/" }, { "/tmp//home", 1, "/tmp/home" }, { "/./tmp//home", 1, "/tmp/home" }, { "/../tmp/home", 1, "/tmp/home" }, { "/../../../tmp/./home", 1, "/tmp/home" }, { "//tmp///home", 1, "/tmp/home" }, { "/tmp/home/git/./.././git/runtime/../", 1, "/tmp/home/git/" }, { "/./tmp/home", 1, "/tmp/home" }, { "/tmp/home", 4, "/tmp/home" }, { "/tmp/..", 4, "/tmp" }, { "/tmp/home/../././", 4, "/tmp/" }, { "/tmp/../../../", 4, "/tmp/" }, { "/tmp//home", 4, "/tmp/home" }, { "/./tmp//home", 2, "/./tmp/home" }, { "/../tmp/home", 3, "/../tmp/home" }, { "/../../../tmp/./home", 4, "/../tmp/home" }, { "//tmp///home", 5, "//tmp/home" }, { "/tmp/home/git/./.././git/runtime/../", 5, "/tmp/home/git/" }, { "/./tmp/home", 3, "/./tmp/home" }, { "/tmp/../../", 8, "/tmp/../" }, { "/tmp/home/../././", 10, "/tmp/home/" }, { "/tmp/../../../", 8, "/tmp/../" }, { "/tmp//home/.././/", 11, "/tmp//home/" }, { "/./tmp//home/git/git", 7, "/./tmp/home/git/git" }, { "/../tmp/./home", 8, "/../tmp/home" }, { "/../../../tmp/./home", 8, "/../../../tmp/home" }, { "//tmp///home/..", 5, "//tmp/" }, { "/tmp/home/git/./.././git/runtime/../", 16, "/tmp/home/git/./git/" }, { "/./tmp/home/././", 7, "/./tmp/home/" }, }; [Theory, MemberData(nameof(RemoveRelativeSegmentUnixData))] [PlatformSpecific(TestPlatforms.AnyUnix)] public void RemoveRelativeSegmentsUnix(string path, int skip, string expected) { Assert.Equal(expected, PathInternal.RemoveRelativeSegments(path, skip)); } } }
// 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; using System.Text; using Xunit; namespace Tests.System.IO { public class PathInternal_Windows_Tests { [Theory, InlineData("", "", true, 0), InlineData("", "", false, 0), InlineData("a", "", true, 0), InlineData("a", "", false, 0), InlineData("", "b", true, 0), InlineData("", "b", false, 0), InlineData("\0", "\0", true, 1), InlineData("\0", "\0", false, 1), InlineData("ABcd", "ABCD", true, 4), InlineData("ABCD", "ABcd", true, 4), InlineData("ABcd", "ABCD", false, 2), InlineData("ABCD", "ABcd", false, 2), InlineData("AB\0cd", "AB\0CD", true, 5), InlineData("AB\0CD", "AB\0cd", true, 5), InlineData("AB\0cd", "AB\0CD", false, 3), InlineData("AB\0CD", "AB\0cd", false, 3), InlineData("ABc\0", "ABC\0", true, 4), InlineData("ABC\0", "ABc\0", true, 4), InlineData("ABc\0", "ABC\0", false, 2), InlineData("ABC\0", "ABc\0", false, 2), InlineData("ABcdxyzl", "ABCDpdq", true, 4), InlineData("ABCDxyz", "ABcdpdql", true, 4), InlineData("ABcdxyz", "ABCDpdq", false, 2), InlineData("ABCDxyzoo", "ABcdpdq", false, 2)] public void EqualStartingCharacterCount(string first, string second, bool ignoreCase, int expected) { Assert.Equal(expected, PathInternal.EqualStartingCharacterCount(first, second, ignoreCase)); } [Theory, InlineData(@"", @"", true, 0), InlineData(@"", @"", false, 0), InlineData(@"a", @"A", true, 1), InlineData(@"A", @"a", true, 1), InlineData(@"a", @"A", false, 0), InlineData(@"A", @"a", false, 0), InlineData(@"foo", @"foobar", true, 0), InlineData(@"foo", @"foobar", false, 0), InlineData(@"foo", @"foo/bar", true, 3), InlineData(@"foo", @"foo/bar", false, 3), InlineData(@"foo/", @"foo/bar", true, 4), InlineData(@"foo/", @"foo/bar", false, 4), InlineData(@"foo/bar", @"foo/bar", true, 7), InlineData(@"foo/bar", @"foo/bar", false, 7), InlineData(@"foo/bar", @"foo/BAR", true, 7), InlineData(@"foo/bar", @"foo/BAR", false, 4), InlineData(@"foo/bar", @"foo/barb", true, 4), InlineData(@"foo/bar", @"foo/barb", false, 4)] public void GetCommonPathLength(string first, string second, bool ignoreCase, int expected) { Assert.Equal(expected, PathInternal.GetCommonPathLength(first, second, ignoreCase)); } public static TheoryData<string, int, string> RemoveRelativeSegmentsData => new TheoryData<string, int, string> { { @"C:\git\runtime", 2, @"C:\git\runtime"}, { @"C:\\git\runtime", 2, @"C:\git\runtime"}, { @"C:\git\\runtime", 2, @"C:\git\runtime"}, { @"C:\git\.\runtime\.\\", 2, @"C:\git\runtime\"}, { @"C:\git\runtime", 2, @"C:\git\runtime"}, { @"C:\git\..\runtime", 2, @"C:\runtime"}, { @"C:\git\runtime\..\", 2, @"C:\git\"}, { @"C:\git\runtime\..\..\..\", 2, @"C:\"}, { @"C:\git\runtime\..\..\.\", 2, @"C:\"}, { @"C:\git\..\.\runtime\temp\..", 2, @"C:\runtime"}, { @"C:\git\..\\\.\..\runtime", 2, @"C:\runtime"}, { @"C:\git\runtime\", 2, @"C:\git\runtime\"}, { @"C:\git\temp\..\runtime\", 2, @"C:\git\runtime\"}, { @"C:\.", 3, @"C:\"}, { @"C:\..", 3, @"C:\"}, { @"C:\..\..", 3, @"C:\"}, { @"C:\.", 2, @"C:"}, { @"C:\..", 2, @"C:"}, { @"C:\..\..", 2, @"C:"}, { @"C:A\.", 2, @"C:A"}, { @"C:A\..", 2, @"C:"}, { @"C:A\..\..", 2, @"C:"}, { @"C:A\..\..\..", 2, @"C:"}, { @"C:\tmp\home", 3, @"C:\tmp\home" }, { @"C:\tmp\..", 3, @"C:\" }, { @"C:\tmp\home\..\.\.\", 3, @"C:\tmp\" }, { @"C:\tmp\..\..\..\", 3, @"C:\" }, { @"C:\tmp\\home", 3, @"C:\tmp\home" }, { @"C:\.\tmp\\home", 3, @"C:\tmp\home" }, { @"C:\..\tmp\home", 3, @"C:\tmp\home" }, { @"C:\..\..\..\tmp\.\home", 3, @"C:\tmp\home" }, { @"C:\\tmp\\\home", 3, @"C:\tmp\home" }, { @"C:\tmp\home\git\.\..\.\git\runtime\..\", 3, @"C:\tmp\home\git\" }, { @"C:\.\tmp\home", 3, @"C:\tmp\home" }, { @"C:\tmp\home", 6, @"C:\tmp\home" }, { @"C:\tmp\..", 6, @"C:\tmp" }, { @"C:\tmp\home\..\.\.\", 5, @"C:\tmp\" }, { @"C:\tmp\..\..\..\", 6, @"C:\tmp\" }, { @"C:\tmp\\home", 5, @"C:\tmp\home" }, { @"C:\.\tmp\\home", 4, @"C:\.\tmp\home" }, { @"C:\..\tmp\home", 5, @"C:\..\tmp\home" }, { @"C:\..\..\..\tmp\.\home", 6, @"C:\..\tmp\home" }, { @"C:\\tmp\\\home", 7, @"C:\\tmp\home" }, { @"C:\tmp\home\git\.\..\.\git\runtime\..\", 7, @"C:\tmp\home\git\" }, { @"C:\.\tmp\home", 5, @"C:\.\tmp\home" }, { @"C:\tmp\..", 2, @"C:\" }, { @"C:\tmp\home\..\..\.\", 2, @"C:\" }, { @"C:\tmp\..\..\..\", 2, @"C:\" }, { @"C:\tmp\\home", 2, @"C:\tmp\home" }, { @"C:\.\tmp\\home", 2, @"C:\tmp\home" }, { @"C:\..\tmp\home", 2, @"C:\tmp\home" }, { @"C:\..\..\..\tmp\.\home", 2, @"C:\tmp\home" }, { @"C:\\tmp\\\home", 2, @"C:\tmp\home" }, { @"C:\tmp\home\git\.\..\.\git\runtime\..\", 2, @"C:\tmp\home\git\" }, { @"C:\.\tmp\home", 2, @"C:\tmp\home" }, { @"C:\tmp\..\..\", 10, @"C:\tmp\..\" }, { @"C:\tmp\home\..\.\.\", 12, @"C:\tmp\home\" }, { @"C:\tmp\..\..\..\", 10, @"C:\tmp\..\" }, { @"C:\tmp\\home\..\.\\", 13, @"C:\tmp\\home\" }, { @"C:\.\tmp\\home\git\git", 9, @"C:\.\tmp\home\git\git" }, { @"C:\..\tmp\.\home", 10, @"C:\..\tmp\home" }, { @"C:\..\..\..\tmp\.\home", 10, @"C:\..\..\..\tmp\home" }, { @"C:\\tmp\\\home\..", 7, @"C:\\tmp\" }, { @"C:\tmp\home\git\.\..\.\git\runtime\..\", 18, @"C:\tmp\home\git\.\git\" }, { @"C:\.\tmp\home\.\.\", 9, @"C:\.\tmp\home\" }, }; public static TheoryData<string, int, string> RemoveRelativeSegmentsFirstRelativeSegment => new TheoryData<string, int, string> { { @"C:\\git\runtime", 2, @"C:\git\runtime"}, { @"C:\.\git\runtime", 2, @"C:\git\runtime"}, { @"C:\\.\git\.\runtime", 2, @"C:\git\runtime"}, { @"C:\..\git\runtime", 2, @"C:\git\runtime"}, { @"C:\.\git\..\runtime", 2, @"C:\runtime"}, { @"C:\.\git\runtime\..\", 2, @"C:\git\"}, { @"C:\.\git\runtime\..\..\..\", 2, @"C:\"}, { @"C:\.\git\runtime\..\..\.\", 2, @"C:\"}, { @"C:\.\git\..\.\runtime\temp\..", 2, @"C:\runtime"}, { @"C:\.\git\..\\\.\..\runtime", 2, @"C:\runtime"}, { @"C:\.\git\runtime\", 2, @"C:\git\runtime\"}, { @"C:\.\git\temp\..\runtime\", 2, @"C:\git\runtime\"}, { @"C:\\..\..", 3, @"C:\"} }; public static TheoryData<string, int, string> RemoveRelativeSegmentsSkipAboveRoot => new TheoryData<string, int, string> { { @"C:\temp\..\" , 7, @"C:\temp\" }, { @"C:\temp\..\git" , 7, @"C:\temp\git" }, { @"C:\temp\..\git" , 8, @"C:\temp\git" }, { @"C:\temp\..\.\" , 8, @"C:\temp\" }, { @"C:\temp\..\" , 9, @"C:\temp\..\" }, { @"C:\temp\..\git" , 9, @"C:\temp\..\git" }, { @"C:\git\..\temp\..\" , 15, @"C:\git\..\temp\" }, { @"C:\\\.\..\..\temp\..\" , 17, @"C:\\\.\..\..\temp\" }, }; public static TheoryData<string, int, string> RemoveRelativeSegmentsFirstRelativeSegmentRoot => new TheoryData<string, int, string> { { @"C:\\git\runtime", 3, @"C:\git\runtime"}, { @"C:\.\git\runtime", 3, @"C:\git\runtime"}, { @"C:\\.\git\.\runtime", 3, @"C:\git\runtime"}, { @"C:\..\git\runtime", 3, @"C:\git\runtime"}, { @"C:\.\git\..\runtime", 3, @"C:\runtime"}, { @"C:\.\git\runtime\..\", 3, @"C:\git\"}, { @"C:\.\git\runtime\..\..\..\", 3, @"C:\"}, { @"C:\.\git\runtime\..\..\.\", 3, @"C:\"}, { @"C:\.\git\..\.\runtime\temp\..", 3, @"C:\runtime"}, { @"C:\.\git\..\\\.\..\runtime", 3, @"C:\runtime"}, { @"C:\.\git\runtime\", 3, @"C:\git\runtime\"}, { @"C:\.\git\temp\..\runtime\", 3, @"C:\git\runtime\"}, }; [Theory, MemberData(nameof(RemoveRelativeSegmentsData)), MemberData(nameof(RemoveRelativeSegmentsFirstRelativeSegment)), MemberData(nameof(RemoveRelativeSegmentsFirstRelativeSegmentRoot)), MemberData(nameof(RemoveRelativeSegmentsSkipAboveRoot))] [PlatformSpecific(TestPlatforms.Windows)] public void RemoveRelativeSegmentsTest(string path, int skip, string expected) { Assert.Equal(expected, PathInternal.RemoveRelativeSegments(path, skip)); Assert.Equal(@"\\.\" + expected, PathInternal.RemoveRelativeSegments(@"\\.\" + path, skip + 4)); Assert.Equal(@"\\?\" + expected, PathInternal.RemoveRelativeSegments(@"\\?\" + path, skip + 4)); } public static TheoryData<string, int, string> RemoveRelativeSegmentsUncData => new TheoryData<string, int, string> { { @"Server\Share\git\runtime", 12, @"Server\Share\git\runtime"}, { @"Server\Share\\git\runtime", 12, @"Server\Share\git\runtime"}, { @"Server\Share\git\\runtime", 12, @"Server\Share\git\runtime"}, { @"Server\Share\git\.\runtime\.\\", 12, @"Server\Share\git\runtime\"}, { @"Server\Share\git\runtime", 12, @"Server\Share\git\runtime"}, { @"Server\Share\git\..\runtime", 12, @"Server\Share\runtime"}, { @"Server\Share\git\runtime\..\", 12, @"Server\Share\git\"}, { @"Server\Share\git\runtime\..\..\..\", 12, @"Server\Share\"}, { @"Server\Share\git\runtime\..\..\.\", 12, @"Server\Share\"}, { @"Server\Share\git\..\.\runtime\temp\..", 12, @"Server\Share\runtime"}, { @"Server\Share\git\..\\\.\..\runtime", 12, @"Server\Share\runtime"}, { @"Server\Share\git\runtime\", 12, @"Server\Share\git\runtime\"}, { @"Server\Share\git\temp\..\runtime\", 12, @"Server\Share\git\runtime\"}, }; [Theory, MemberData(nameof(RemoveRelativeSegmentsUncData))] [PlatformSpecific(TestPlatforms.Windows)] public void RemoveRelativeSegmentsUncTest(string path, int skip, string expected) { Assert.Equal(@"\\" + expected, PathInternal.RemoveRelativeSegments(@"\\" + path, skip + 2)); Assert.Equal(@"\\.\UNC\" + expected, PathInternal.RemoveRelativeSegments(@"\\.\UNC\" + path, skip + 8)); Assert.Equal(@"\\?\UNC\" + expected, PathInternal.RemoveRelativeSegments(@"\\?\UNC\" + path, skip + 8)); } public static TheoryData<string, int, string> RemoveRelativeSegmentsDeviceData => new TheoryData<string, int, string> { { @"\\.\git\runtime", 7, @"\\.\git\runtime"}, { @"\\.\git\runtime", 7, @"\\.\git\runtime"}, { @"\\.\git\\runtime", 7, @"\\.\git\runtime"}, { @"\\.\git\.\runtime\.\\", 7, @"\\.\git\runtime\"}, { @"\\.\git\runtime", 7, @"\\.\git\runtime"}, { @"\\.\git\..\runtime", 7, @"\\.\git\runtime"}, { @"\\.\git\runtime\..\", 7, @"\\.\git\"}, { @"\\.\git\runtime\..\..\..\", 7, @"\\.\git\"}, { @"\\.\git\runtime\..\..\.\", 7, @"\\.\git\"}, { @"\\.\git\..\.\runtime\temp\..", 7, @"\\.\git\runtime"}, { @"\\.\git\..\\\.\..\runtime", 7, @"\\.\git\runtime"}, { @"\\.\git\runtime\", 7, @"\\.\git\runtime\"}, { @"\\.\git\temp\..\runtime\", 7, @"\\.\git\runtime\"}, { @"\\.\.\runtime", 5, @"\\.\.\runtime"}, { @"\\.\.\runtime", 5, @"\\.\.\runtime"}, { @"\\.\.\\runtime", 5, @"\\.\.\runtime"}, { @"\\.\.\.\runtime\.\\", 5, @"\\.\.\runtime\"}, { @"\\.\.\runtime", 5, @"\\.\.\runtime"}, { @"\\.\.\..\runtime", 5, @"\\.\.\runtime"}, { @"\\.\.\runtime\..\", 5, @"\\.\.\"}, { @"\\.\.\runtime\..\..\..\", 5, @"\\.\.\"}, { @"\\.\.\runtime\..\..\.\", 5, @"\\.\.\"}, { @"\\.\.\..\.\runtime\temp\..", 5, @"\\.\.\runtime"}, { @"\\.\.\..\\\.\..\runtime", 5, @"\\.\.\runtime"}, { @"\\.\.\runtime\", 5, @"\\.\.\runtime\"}, { @"\\.\.\temp\..\runtime\", 5, @"\\.\.\runtime\"}, { @"\\.\..\runtime", 6, @"\\.\..\runtime"}, { @"\\.\..\runtime", 6, @"\\.\..\runtime"}, { @"\\.\..\\runtime", 6, @"\\.\..\runtime"}, { @"\\.\..\.\runtime\.\\", 6, @"\\.\..\runtime\"}, { @"\\.\..\runtime", 6, @"\\.\..\runtime"}, { @"\\.\..\..\runtime", 6, @"\\.\..\runtime"}, { @"\\.\..\runtime\..\", 6, @"\\.\..\"}, { @"\\.\..\runtime\..\..\..\", 6, @"\\.\..\"}, { @"\\.\..\runtime\..\..\.\", 6, @"\\.\..\"}, { @"\\.\..\..\.\runtime\temp\..", 6, @"\\.\..\runtime"}, { @"\\.\..\..\\\.\..\runtime", 6, @"\\.\..\runtime"}, { @"\\.\..\runtime\", 6, @"\\.\..\runtime\"}, { @"\\.\..\temp\..\runtime\", 6, @"\\.\..\runtime\"}, { @"\\.\\runtime", 4, @"\\.\runtime"}, { @"\\.\\runtime", 4, @"\\.\runtime"}, { @"\\.\\\runtime", 4, @"\\.\runtime"}, { @"\\.\\.\runtime\.\\", 4, @"\\.\runtime\"}, { @"\\.\\runtime", 4, @"\\.\runtime"}, { @"\\.\\..\runtime", 4, @"\\.\runtime"}, { @"\\.\\runtime\..\", 4, @"\\.\"}, { @"\\.\\runtime\..\..\..\", 4, @"\\.\"}, { @"\\.\\runtime\..\..\.\", 4, @"\\.\"}, { @"\\.\\..\.\runtime\temp\..", 4, @"\\.\runtime"}, { @"\\.\\..\\\.\..\runtime", 4, @"\\.\runtime"}, { @"\\.\\runtime\", 4, @"\\.\runtime\"}, { @"\\.\\temp\..\runtime\", 4, @"\\.\runtime\"}, }; public static TheoryData<string, int, string> RemoveRelativeSegmentsDeviceRootData => new TheoryData<string, int, string> { { @"\\.\git\runtime", 8, @"\\.\git\runtime"}, { @"\\.\git\runtime", 8, @"\\.\git\runtime"}, { @"\\.\git\\runtime", 8, @"\\.\git\runtime"}, { @"\\.\git\.\runtime\.\\", 8, @"\\.\git\runtime\"}, { @"\\.\git\runtime", 8, @"\\.\git\runtime"}, { @"\\.\git\..\runtime", 8, @"\\.\git\runtime"}, { @"\\.\git\runtime\..\", 8, @"\\.\git\"}, { @"\\.\git\runtime\..\..\..\", 8, @"\\.\git\"}, { @"\\.\git\runtime\..\..\.\", 8, @"\\.\git\"}, { @"\\.\git\..\.\runtime\temp\..", 8, @"\\.\git\runtime"}, { @"\\.\git\..\\\.\..\runtime", 8, @"\\.\git\runtime"}, { @"\\.\git\runtime\", 8, @"\\.\git\runtime\"}, { @"\\.\git\temp\..\runtime\", 8, @"\\.\git\runtime\"}, { @"\\.\.\runtime", 6, @"\\.\.\runtime"}, { @"\\.\.\runtime", 6, @"\\.\.\runtime"}, { @"\\.\.\\runtime", 6, @"\\.\.\runtime"}, { @"\\.\.\.\runtime\.\\", 6, @"\\.\.\runtime\"}, { @"\\.\.\runtime", 6, @"\\.\.\runtime"}, { @"\\.\.\..\runtime", 6, @"\\.\.\runtime"}, { @"\\.\.\runtime\..\", 6, @"\\.\.\"}, { @"\\.\.\runtime\..\..\..\", 6, @"\\.\.\"}, { @"\\.\.\runtime\..\..\.\", 6, @"\\.\.\"}, { @"\\.\.\..\.\runtime\temp\..", 6, @"\\.\.\runtime"}, { @"\\.\.\..\\\.\..\runtime", 6, @"\\.\.\runtime"}, { @"\\.\.\runtime\", 6, @"\\.\.\runtime\"}, { @"\\.\.\temp\..\runtime\", 6, @"\\.\.\runtime\"}, { @"\\.\..\runtime", 7, @"\\.\..\runtime"}, { @"\\.\..\runtime", 7, @"\\.\..\runtime"}, { @"\\.\..\\runtime", 7, @"\\.\..\runtime"}, { @"\\.\..\.\runtime\.\\", 7, @"\\.\..\runtime\"}, { @"\\.\..\runtime", 7, @"\\.\..\runtime"}, { @"\\.\..\..\runtime", 7, @"\\.\..\runtime"}, { @"\\.\..\runtime\..\", 7, @"\\.\..\"}, { @"\\.\..\runtime\..\..\..\", 7, @"\\.\..\"}, { @"\\.\..\runtime\..\..\.\", 7, @"\\.\..\"}, { @"\\.\..\..\.\runtime\temp\..", 7, @"\\.\..\runtime"}, { @"\\.\..\..\\\.\..\runtime", 7, @"\\.\..\runtime"}, { @"\\.\..\runtime\", 7, @"\\.\..\runtime\"}, { @"\\.\..\temp\..\runtime\", 7, @"\\.\..\runtime\"}, { @"\\.\\runtime", 5, @"\\.\\runtime"}, { @"\\.\\runtime", 5, @"\\.\\runtime"}, { @"\\.\\\runtime", 5, @"\\.\\runtime"}, { @"\\.\\.\runtime\.\\", 5, @"\\.\\runtime\"}, { @"\\.\\runtime", 5, @"\\.\\runtime"}, { @"\\.\\..\runtime", 5, @"\\.\\runtime"}, { @"\\.\\runtime\..\", 5, @"\\.\\"}, { @"\\.\\runtime\..\..\..\", 5, @"\\.\\"}, { @"\\.\\runtime\..\..\.\", 5, @"\\.\\"}, { @"\\.\\..\.\runtime\temp\..", 5, @"\\.\\runtime"}, { @"\\.\\..\\\.\..\runtime", 5, @"\\.\\runtime"}, { @"\\.\\runtime\", 5, @"\\.\\runtime\"}, { @"\\.\\temp\..\runtime\", 5, @"\\.\\runtime\"}, }; [Theory, MemberData(nameof(RemoveRelativeSegmentsDeviceData)), MemberData(nameof(RemoveRelativeSegmentsDeviceRootData))] [PlatformSpecific(TestPlatforms.Windows)] public void RemoveRelativeSegmentsDeviceTest(string path, int skip, string expected) { Assert.Equal(expected, PathInternal.RemoveRelativeSegments(path, skip)); StringBuilder sb = new StringBuilder(expected); sb.Replace('.', '?', 0, 4); expected = sb.ToString(); sb = new StringBuilder(path); sb.Replace('.', '?', 0, 4); path = sb.ToString(); Assert.Equal(expected, PathInternal.RemoveRelativeSegments(path, skip)); } public static TheoryData<string, int, string> RemoveRelativeSegmentUnixData => new TheoryData<string, int, string> { { "/tmp/home", 1, "/tmp/home" }, { "/tmp/..", 1, "/" }, { "/tmp/home/../././", 1, "/tmp/" }, { "/tmp/../../../", 1, "/" }, { "/tmp//home", 1, "/tmp/home" }, { "/./tmp//home", 1, "/tmp/home" }, { "/../tmp/home", 1, "/tmp/home" }, { "/../../../tmp/./home", 1, "/tmp/home" }, { "//tmp///home", 1, "/tmp/home" }, { "/tmp/home/git/./.././git/runtime/../", 1, "/tmp/home/git/" }, { "/./tmp/home", 1, "/tmp/home" }, { "/tmp/home", 4, "/tmp/home" }, { "/tmp/..", 4, "/tmp" }, { "/tmp/home/../././", 4, "/tmp/" }, { "/tmp/../../../", 4, "/tmp/" }, { "/tmp//home", 4, "/tmp/home" }, { "/./tmp//home", 2, "/./tmp/home" }, { "/../tmp/home", 3, "/../tmp/home" }, { "/../../../tmp/./home", 4, "/../tmp/home" }, { "//tmp///home", 5, "//tmp/home" }, { "/tmp/home/git/./.././git/runtime/../", 5, "/tmp/home/git/" }, { "/./tmp/home", 3, "/./tmp/home" }, { "/tmp/../../", 8, "/tmp/../" }, { "/tmp/home/../././", 10, "/tmp/home/" }, { "/tmp/../../../", 8, "/tmp/../" }, { "/tmp//home/.././/", 11, "/tmp//home/" }, { "/./tmp//home/git/git", 7, "/./tmp/home/git/git" }, { "/../tmp/./home", 8, "/../tmp/home" }, { "/../../../tmp/./home", 8, "/../../../tmp/home" }, { "//tmp///home/..", 5, "//tmp/" }, { "/tmp/home/git/./.././git/runtime/../", 16, "/tmp/home/git/./git/" }, { "/./tmp/home/././", 7, "/./tmp/home/" }, }; [Theory, MemberData(nameof(RemoveRelativeSegmentUnixData))] [PlatformSpecific(TestPlatforms.AnyUnix)] public void RemoveRelativeSegmentsUnix(string path, int skip, string expected) { Assert.Equal(expected, PathInternal.RemoveRelativeSegments(path, skip)); } } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.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.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Collections.Generic { #region ArraySortHelper for single arrays internal sealed partial class ArraySortHelper<T> { #region IArraySortHelper<T> Members public void Sort(Span<T> keys, IComparer<T>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { comparer ??= Comparer<T>.Default; IntrospectiveSort(keys, comparer.Compare); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } public int BinarySearch(T[] array, int index, int length, T value, IComparer<T>? comparer) { try { comparer ??= Comparer<T>.Default; return InternalBinarySearch(array, index, length, value, comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); return 0; } } #endregion internal static void Sort(Span<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null, "Check the arguments in the caller!"); // Add a try block here to detect bogus comparisons try { IntrospectiveSort(keys, comparer); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } internal static int InternalBinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer) { Debug.Assert(array != null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); int lo = index; int hi = index + length - 1; while (lo <= hi) { int i = lo + ((hi - lo) >> 1); int order = comparer.Compare(array[i], value); if (order == 0) return i; if (order < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } private static void SwapIfGreater(Span<T> keys, Comparison<T> comparer, int i, int j) { Debug.Assert(i != j); if (comparer(keys[i], keys[j]) > 0) { T key = keys[i]; keys[i] = keys[j]; keys[j] = key; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(Span<T> a, int i, int j) { Debug.Assert(i != j); T t = a[i]; a[i] = a[j]; a[j] = t; } internal static void IntrospectiveSort(Span<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null); if (keys.Length > 1) { IntroSort(keys, 2 * (BitOperations.Log2((uint)keys.Length) + 1), comparer); } } private static void IntroSort(Span<T> keys, int depthLimit, Comparison<T> comparer) { Debug.Assert(!keys.IsEmpty); Debug.Assert(depthLimit >= 0); Debug.Assert(comparer != null); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= Array.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreater(keys, comparer, 0, 1); return; } if (partitionSize == 3) { SwapIfGreater(keys, comparer, 0, 1); SwapIfGreater(keys, comparer, 0, 2); SwapIfGreater(keys, comparer, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), comparer); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), comparer); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), comparer); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys[(p+1)..partitionSize], depthLimit, comparer); partitionSize = p; } } private static int PickPivotAndPartition(Span<T> keys, Comparison<T> comparer) { Debug.Assert(keys.Length >= Array.IntrosortSizeThreshold); Debug.Assert(comparer != null); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreater(keys, comparer, 0, middle); // swap the low with the mid point SwapIfGreater(keys, comparer, 0, hi); // swap the low with the high SwapIfGreater(keys, comparer, middle, hi); // swap the middle with the high T pivot = keys[middle]; Swap(keys, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { while (comparer(keys[++left], pivot) < 0) ; while (comparer(pivot, keys[--right]) < 0) ; if (left >= right) break; Swap(keys, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, left, hi - 1); } return left; } private static void HeapSort(Span<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null); Debug.Assert(!keys.IsEmpty); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, i, n, comparer); } for (int i = n; i > 1; i--) { Swap(keys, 0, i - 1); DownHeap(keys, 1, i - 1, comparer); } } private static void DownHeap(Span<T> keys, int i, int n, Comparison<T> comparer) { Debug.Assert(comparer != null); T d = keys[i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && comparer(keys[child - 1], keys[child]) < 0) { child++; } if (!(comparer(d, keys[child - 1]) < 0)) break; keys[i - 1] = keys[child - 1]; i = child; } keys[i - 1] = d; } private static void InsertionSort(Span<T> keys, Comparison<T> comparer) { for (int i = 0; i < keys.Length - 1; i++) { T t = keys[i + 1]; int j = i; while (j >= 0 && comparer(t, keys[j]) < 0) { keys[j + 1] = keys[j]; j--; } keys[j + 1] = t; } } } internal sealed partial class GenericArraySortHelper<T> where T : IComparable<T> { // Do not add a constructor to this class because ArraySortHelper<T>.CreateSortHelper will not execute it #region IArraySortHelper<T> Members public void Sort(Span<T> keys, IComparer<T>? comparer) { try { if (comparer == null || comparer == Comparer<T>.Default) { if (keys.Length > 1) { // For floating-point, do a pre-pass to move all NaNs to the beginning // so that we can do an optimized comparison as part of the actual sort // on the remainder of the values. if (typeof(T) == typeof(double) || typeof(T) == typeof(float) || typeof(T) == typeof(Half)) { int nanLeft = SortUtils.MoveNansToFront(keys, default(Span<byte>)); if (nanLeft == keys.Length) { return; } keys = keys.Slice(nanLeft); } IntroSort(keys, 2 * (BitOperations.Log2((uint)keys.Length) + 1)); } } else { ArraySortHelper<T>.IntrospectiveSort(keys, comparer.Compare); } } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } public int BinarySearch(T[] array, int index, int length, T value, IComparer<T>? comparer) { Debug.Assert(array != null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); try { if (comparer == null || comparer == Comparer<T>.Default) { return BinarySearch(array, index, length, value); } else { return ArraySortHelper<T>.InternalBinarySearch(array, index, length, value, comparer); } } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); return 0; } } #endregion // This function is called when the user doesn't specify any comparer. // Since T is constrained here, we can call IComparable<T>.CompareTo here. // We can avoid boxing for value type and casting for reference types. private static int BinarySearch(T[] array, int index, int length, T value) { int lo = index; int hi = index + length - 1; while (lo <= hi) { int i = lo + ((hi - lo) >> 1); int order; if (array[i] == null) { order = (value == null) ? 0 : -1; } else { order = array[i].CompareTo(value); } if (order == 0) { return i; } if (order < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } /// <summary>Swaps the values in the two references if the first is greater than the second.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void SwapIfGreater(ref T i, ref T j) { if (i != null && GreaterThan(ref i, ref j)) { Swap(ref i, ref j); } } /// <summary>Swaps the values in the two references, regardless of whether the two references are the same.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(ref T i, ref T j) { Debug.Assert(!Unsafe.AreSame(ref i, ref j)); T t = i; i = j; j = t; } private static void IntroSort(Span<T> keys, int depthLimit) { Debug.Assert(!keys.IsEmpty); Debug.Assert(depthLimit >= 0); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= Array.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreater(ref keys[0], ref keys[1]); return; } if (partitionSize == 3) { ref T hiRef = ref keys[2]; ref T him1Ref = ref keys[1]; ref T loRef = ref keys[0]; SwapIfGreater(ref loRef, ref him1Ref); SwapIfGreater(ref loRef, ref hiRef); SwapIfGreater(ref him1Ref, ref hiRef); return; } InsertionSort(keys.Slice(0, partitionSize)); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize)); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize)); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys[(p+1)..partitionSize], depthLimit); partitionSize = p; } } private static int PickPivotAndPartition(Span<T> keys) { Debug.Assert(keys.Length >= Array.IntrosortSizeThreshold); // Use median-of-three to select a pivot. Grab a reference to the 0th, Length-1th, and Length/2th elements, and sort them. ref T zeroRef = ref MemoryMarshal.GetReference(keys); ref T lastRef = ref Unsafe.Add(ref zeroRef, keys.Length - 1); ref T middleRef = ref Unsafe.Add(ref zeroRef, (keys.Length - 1) >> 1); SwapIfGreater(ref zeroRef, ref middleRef); SwapIfGreater(ref zeroRef, ref lastRef); SwapIfGreater(ref middleRef, ref lastRef); // Select the middle value as the pivot, and move it to be just before the last element. ref T nextToLastRef = ref Unsafe.Add(ref zeroRef, keys.Length - 2); T pivot = middleRef; Swap(ref middleRef, ref nextToLastRef); // Walk the left and right pointers, swapping elements as necessary, until they cross. ref T leftRef = ref zeroRef, rightRef = ref nextToLastRef; while (Unsafe.IsAddressLessThan(ref leftRef, ref rightRef)) { if (pivot == null) { while (Unsafe.IsAddressLessThan(ref leftRef, ref nextToLastRef) && (leftRef = ref Unsafe.Add(ref leftRef, 1)) == null) ; while (Unsafe.IsAddressGreaterThan(ref rightRef, ref zeroRef) && (rightRef = ref Unsafe.Add(ref rightRef, -1)) != null) ; } else { while (Unsafe.IsAddressLessThan(ref leftRef, ref nextToLastRef) && GreaterThan(ref pivot, ref leftRef = ref Unsafe.Add(ref leftRef, 1))) ; while (Unsafe.IsAddressGreaterThan(ref rightRef, ref zeroRef) && LessThan(ref pivot, ref rightRef = ref Unsafe.Add(ref rightRef, -1))) ; } if (!Unsafe.IsAddressLessThan(ref leftRef, ref rightRef)) { break; } Swap(ref leftRef, ref rightRef); } // Put the pivot in the correct location. if (!Unsafe.AreSame(ref leftRef, ref nextToLastRef)) { Swap(ref leftRef, ref nextToLastRef); } return (int)((nint)Unsafe.ByteOffset(ref zeroRef, ref leftRef) / Unsafe.SizeOf<T>()); } private static void HeapSort(Span<T> keys) { Debug.Assert(!keys.IsEmpty); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, i, n); } for (int i = n; i > 1; i--) { Swap(ref keys[0], ref keys[i - 1]); DownHeap(keys, 1, i - 1); } } private static void DownHeap(Span<T> keys, int i, int n) { T d = keys[i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && (keys[child - 1] == null || LessThan(ref keys[child - 1], ref keys[child]))) { child++; } if (keys[child - 1] == null || !LessThan(ref d, ref keys[child - 1])) break; keys[i - 1] = keys[child - 1]; i = child; } keys[i - 1] = d; } private static void InsertionSort(Span<T> keys) { for (int i = 0; i < keys.Length - 1; i++) { T t = Unsafe.Add(ref MemoryMarshal.GetReference(keys), i + 1); int j = i; while (j >= 0 && (t == null || LessThan(ref t, ref Unsafe.Add(ref MemoryMarshal.GetReference(keys), j)))) { Unsafe.Add(ref MemoryMarshal.GetReference(keys), j + 1) = Unsafe.Add(ref MemoryMarshal.GetReference(keys), j); j--; } Unsafe.Add(ref MemoryMarshal.GetReference(keys), j + 1) = t!; } } // - These methods exist for use in sorting, where the additional operations present in // the CompareTo methods that would otherwise be used on these primitives add non-trivial overhead, // in particular for floating point where the CompareTo methods need to factor in NaNs. // - The floating-point comparisons here assume no NaNs, which is valid only because the sorting routines // themselves special-case NaN with a pre-pass that ensures none are present in the values being sorted // by moving them all to the front first and then sorting the rest. // - The `? true : false` is to work-around poor codegen: https://github.com/dotnet/runtime/issues/37904#issuecomment-644180265. // - These are duplicated here rather than being on a helper type due to current limitations around generic inlining. [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool LessThan(ref T left, ref T right) { if (typeof(T) == typeof(byte)) return (byte)(object)left < (byte)(object)right ? true : false; if (typeof(T) == typeof(sbyte)) return (sbyte)(object)left < (sbyte)(object)right ? true : false; if (typeof(T) == typeof(ushort)) return (ushort)(object)left < (ushort)(object)right ? true : false; if (typeof(T) == typeof(short)) return (short)(object)left < (short)(object)right ? true : false; if (typeof(T) == typeof(uint)) return (uint)(object)left < (uint)(object)right ? true : false; if (typeof(T) == typeof(int)) return (int)(object)left < (int)(object)right ? true : false; if (typeof(T) == typeof(ulong)) return (ulong)(object)left < (ulong)(object)right ? true : false; if (typeof(T) == typeof(long)) return (long)(object)left < (long)(object)right ? true : false; if (typeof(T) == typeof(nuint)) return (nuint)(object)left < (nuint)(object)right ? true : false; if (typeof(T) == typeof(nint)) return (nint)(object)left < (nint)(object)right ? true : false; if (typeof(T) == typeof(float)) return (float)(object)left < (float)(object)right ? true : false; if (typeof(T) == typeof(double)) return (double)(object)left < (double)(object)right ? true : false; if (typeof(T) == typeof(Half)) return (Half)(object)left < (Half)(object)right ? true : false; return left.CompareTo(right) < 0 ? true : false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool GreaterThan(ref T left, ref T right) { if (typeof(T) == typeof(byte)) return (byte)(object)left > (byte)(object)right ? true : false; if (typeof(T) == typeof(sbyte)) return (sbyte)(object)left > (sbyte)(object)right ? true : false; if (typeof(T) == typeof(ushort)) return (ushort)(object)left > (ushort)(object)right ? true : false; if (typeof(T) == typeof(short)) return (short)(object)left > (short)(object)right ? true : false; if (typeof(T) == typeof(uint)) return (uint)(object)left > (uint)(object)right ? true : false; if (typeof(T) == typeof(int)) return (int)(object)left > (int)(object)right ? true : false; if (typeof(T) == typeof(ulong)) return (ulong)(object)left > (ulong)(object)right ? true : false; if (typeof(T) == typeof(long)) return (long)(object)left > (long)(object)right ? true : false; if (typeof(T) == typeof(nuint)) return (nuint)(object)left > (nuint)(object)right ? true : false; if (typeof(T) == typeof(nint)) return (nint)(object)left > (nint)(object)right ? true : false; if (typeof(T) == typeof(float)) return (float)(object)left > (float)(object)right ? true : false; if (typeof(T) == typeof(double)) return (double)(object)left > (double)(object)right ? true : false; if (typeof(T) == typeof(Half)) return (Half)(object)left > (Half)(object)right ? true : false; return left.CompareTo(right) > 0 ? true : false; } } #endregion #region ArraySortHelper for paired key and value arrays internal sealed partial class ArraySortHelper<TKey, TValue> { public void Sort(Span<TKey> keys, Span<TValue> values, IComparer<TKey>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { IntrospectiveSort(keys, values, comparer ?? Comparer<TKey>.Default); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } private static void SwapIfGreaterWithValues(Span<TKey> keys, Span<TValue> values, IComparer<TKey> comparer, int i, int j) { Debug.Assert(comparer != null); Debug.Assert(0 <= i && i < keys.Length && i < values.Length); Debug.Assert(0 <= j && j < keys.Length && j < values.Length); Debug.Assert(i != j); if (comparer.Compare(keys[i], keys[j]) > 0) { TKey key = keys[i]; keys[i] = keys[j]; keys[j] = key; TValue value = values[i]; values[i] = values[j]; values[j] = value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(Span<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); TKey k = keys[i]; keys[i] = keys[j]; keys[j] = k; TValue v = values[i]; values[i] = values[j]; values[j] = v; } internal static void IntrospectiveSort(Span<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); Debug.Assert(keys.Length == values.Length); if (keys.Length > 1) { IntroSort(keys, values, 2 * (BitOperations.Log2((uint)keys.Length) + 1), comparer); } } private static void IntroSort(Span<TKey> keys, Span<TValue> values, int depthLimit, IComparer<TKey> comparer) { Debug.Assert(!keys.IsEmpty); Debug.Assert(values.Length == keys.Length); Debug.Assert(depthLimit >= 0); Debug.Assert(comparer != null); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= Array.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreaterWithValues(keys, values, comparer, 0, 1); return; } if (partitionSize == 3) { SwapIfGreaterWithValues(keys, values, comparer, 0, 1); SwapIfGreaterWithValues(keys, values, comparer, 0, 2); SwapIfGreaterWithValues(keys, values, comparer, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys[(p+1)..partitionSize], values[(p+1)..partitionSize], depthLimit, comparer); partitionSize = p; } } private static int PickPivotAndPartition(Span<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(keys.Length >= Array.IntrosortSizeThreshold); Debug.Assert(comparer != null); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreaterWithValues(keys, values, comparer, 0, middle); // swap the low with the mid point SwapIfGreaterWithValues(keys, values, comparer, 0, hi); // swap the low with the high SwapIfGreaterWithValues(keys, values, comparer, middle, hi); // swap the middle with the high TKey pivot = keys[middle]; Swap(keys, values, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { while (comparer.Compare(keys[++left], pivot) < 0) ; while (comparer.Compare(pivot, keys[--right]) < 0) ; if (left >= right) break; Swap(keys, values, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, values, left, hi - 1); } return left; } private static void HeapSort(Span<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); Debug.Assert(!keys.IsEmpty); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, values, i, n, comparer); } for (int i = n; i > 1; i--) { Swap(keys, values, 0, i - 1); DownHeap(keys, values, 1, i - 1, comparer); } } private static void DownHeap(Span<TKey> keys, Span<TValue> values, int i, int n, IComparer<TKey> comparer) { Debug.Assert(comparer != null); TKey d = keys[i - 1]; TValue dValue = values[i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && comparer.Compare(keys[child - 1], keys[child]) < 0) { child++; } if (!(comparer.Compare(d, keys[child - 1]) < 0)) break; keys[i - 1] = keys[child - 1]; values[i - 1] = values[child - 1]; i = child; } keys[i - 1] = d; values[i - 1] = dValue; } private static void InsertionSort(Span<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); for (int i = 0; i < keys.Length - 1; i++) { TKey t = keys[i + 1]; TValue tValue = values[i + 1]; int j = i; while (j >= 0 && comparer.Compare(t, keys[j]) < 0) { keys[j + 1] = keys[j]; values[j + 1] = values[j]; j--; } keys[j + 1] = t; values[j + 1] = tValue; } } } internal sealed partial class GenericArraySortHelper<TKey, TValue> where TKey : IComparable<TKey> { public void Sort(Span<TKey> keys, Span<TValue> values, IComparer<TKey>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { if (comparer == null || comparer == Comparer<TKey>.Default) { if (keys.Length > 1) { // For floating-point, do a pre-pass to move all NaNs to the beginning // so that we can do an optimized comparison as part of the actual sort // on the remainder of the values. if (typeof(TKey) == typeof(double) || typeof(TKey) == typeof(float) || typeof(TKey) == typeof(Half)) { int nanLeft = SortUtils.MoveNansToFront(keys, values); if (nanLeft == keys.Length) { return; } keys = keys.Slice(nanLeft); values = values.Slice(nanLeft); } IntroSort(keys, values, 2 * (BitOperations.Log2((uint)keys.Length) + 1)); } } else { ArraySortHelper<TKey, TValue>.IntrospectiveSort(keys, values, comparer); } } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } private static void SwapIfGreaterWithValues(Span<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); ref TKey keyRef = ref keys[i]; if (keyRef != null && GreaterThan(ref keyRef, ref keys[j])) { TKey key = keyRef; keys[i] = keys[j]; keys[j] = key; TValue value = values[i]; values[i] = values[j]; values[j] = value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(Span<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); TKey k = keys[i]; keys[i] = keys[j]; keys[j] = k; TValue v = values[i]; values[i] = values[j]; values[j] = v; } private static void IntroSort(Span<TKey> keys, Span<TValue> values, int depthLimit) { Debug.Assert(!keys.IsEmpty); Debug.Assert(values.Length == keys.Length); Debug.Assert(depthLimit >= 0); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= Array.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreaterWithValues(keys, values, 0, 1); return; } if (partitionSize == 3) { SwapIfGreaterWithValues(keys, values, 0, 1); SwapIfGreaterWithValues(keys, values, 0, 2); SwapIfGreaterWithValues(keys, values, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys[(p+1)..partitionSize], values[(p+1)..partitionSize], depthLimit); partitionSize = p; } } private static int PickPivotAndPartition(Span<TKey> keys, Span<TValue> values) { Debug.Assert(keys.Length >= Array.IntrosortSizeThreshold); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreaterWithValues(keys, values, 0, middle); // swap the low with the mid point SwapIfGreaterWithValues(keys, values, 0, hi); // swap the low with the high SwapIfGreaterWithValues(keys, values, middle, hi); // swap the middle with the high TKey pivot = keys[middle]; Swap(keys, values, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { if (pivot == null) { while (left < (hi - 1) && keys[++left] == null) ; while (right > 0 && keys[--right] != null) ; } else { while (GreaterThan(ref pivot, ref keys[++left])) ; while (LessThan(ref pivot, ref keys[--right])) ; } if (left >= right) break; Swap(keys, values, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, values, left, hi - 1); } return left; } private static void HeapSort(Span<TKey> keys, Span<TValue> values) { Debug.Assert(!keys.IsEmpty); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, values, i, n); } for (int i = n; i > 1; i--) { Swap(keys, values, 0, i - 1); DownHeap(keys, values, 1, i - 1); } } private static void DownHeap(Span<TKey> keys, Span<TValue> values, int i, int n) { TKey d = keys[i - 1]; TValue dValue = values[i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && (keys[child - 1] == null || LessThan(ref keys[child - 1], ref keys[child]))) { child++; } if (keys[child - 1] == null || !LessThan(ref d, ref keys[child - 1])) break; keys[i - 1] = keys[child - 1]; values[i - 1] = values[child - 1]; i = child; } keys[i - 1] = d; values[i - 1] = dValue; } private static void InsertionSort(Span<TKey> keys, Span<TValue> values) { for (int i = 0; i < keys.Length - 1; i++) { TKey t = keys[i + 1]; TValue tValue = values[i + 1]; int j = i; while (j >= 0 && (t == null || LessThan(ref t, ref keys[j]))) { keys[j + 1] = keys[j]; values[j + 1] = values[j]; j--; } keys[j + 1] = t!; values[j + 1] = tValue; } } // - These methods exist for use in sorting, where the additional operations present in // the CompareTo methods that would otherwise be used on these primitives add non-trivial overhead, // in particular for floating point where the CompareTo methods need to factor in NaNs. // - The floating-point comparisons here assume no NaNs, which is valid only because the sorting routines // themselves special-case NaN with a pre-pass that ensures none are present in the values being sorted // by moving them all to the front first and then sorting the rest. // - The `? true : false` is to work-around poor codegen: https://github.com/dotnet/runtime/issues/37904#issuecomment-644180265. // - These are duplicated here rather than being on a helper type due to current limitations around generic inlining. [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool LessThan(ref TKey left, ref TKey right) { if (typeof(TKey) == typeof(byte)) return (byte)(object)left < (byte)(object)right ? true : false; if (typeof(TKey) == typeof(sbyte)) return (sbyte)(object)left < (sbyte)(object)right ? true : false; if (typeof(TKey) == typeof(ushort)) return (ushort)(object)left < (ushort)(object)right ? true : false; if (typeof(TKey) == typeof(short)) return (short)(object)left < (short)(object)right ? true : false; if (typeof(TKey) == typeof(uint)) return (uint)(object)left < (uint)(object)right ? true : false; if (typeof(TKey) == typeof(int)) return (int)(object)left < (int)(object)right ? true : false; if (typeof(TKey) == typeof(ulong)) return (ulong)(object)left < (ulong)(object)right ? true : false; if (typeof(TKey) == typeof(long)) return (long)(object)left < (long)(object)right ? true : false; if (typeof(TKey) == typeof(nuint)) return (nuint)(object)left < (nuint)(object)right ? true : false; if (typeof(TKey) == typeof(nint)) return (nint)(object)left < (nint)(object)right ? true : false; if (typeof(TKey) == typeof(float)) return (float)(object)left < (float)(object)right ? true : false; if (typeof(TKey) == typeof(double)) return (double)(object)left < (double)(object)right ? true : false; if (typeof(TKey) == typeof(Half)) return (Half)(object)left < (Half)(object)right ? true : false; return left.CompareTo(right) < 0 ? true : false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool GreaterThan(ref TKey left, ref TKey right) { if (typeof(TKey) == typeof(byte)) return (byte)(object)left > (byte)(object)right ? true : false; if (typeof(TKey) == typeof(sbyte)) return (sbyte)(object)left > (sbyte)(object)right ? true : false; if (typeof(TKey) == typeof(ushort)) return (ushort)(object)left > (ushort)(object)right ? true : false; if (typeof(TKey) == typeof(short)) return (short)(object)left > (short)(object)right ? true : false; if (typeof(TKey) == typeof(uint)) return (uint)(object)left > (uint)(object)right ? true : false; if (typeof(TKey) == typeof(int)) return (int)(object)left > (int)(object)right ? true : false; if (typeof(TKey) == typeof(ulong)) return (ulong)(object)left > (ulong)(object)right ? true : false; if (typeof(TKey) == typeof(long)) return (long)(object)left > (long)(object)right ? true : false; if (typeof(TKey) == typeof(nuint)) return (nuint)(object)left > (nuint)(object)right ? true : false; if (typeof(TKey) == typeof(nint)) return (nint)(object)left > (nint)(object)right ? true : false; if (typeof(TKey) == typeof(float)) return (float)(object)left > (float)(object)right ? true : false; if (typeof(TKey) == typeof(double)) return (double)(object)left > (double)(object)right ? true : false; if (typeof(TKey) == typeof(Half)) return (Half)(object)left > (Half)(object)right ? true : false; return left.CompareTo(right) > 0 ? true : false; } } #endregion /// <summary>Helper methods for use in array/span sorting routines.</summary> internal static class SortUtils { public static int MoveNansToFront<TKey, TValue>(Span<TKey> keys, Span<TValue> values) where TKey : notnull { Debug.Assert(typeof(TKey) == typeof(double) || typeof(TKey) == typeof(float)); int left = 0; for (int i = 0; i < keys.Length; i++) { if ((typeof(TKey) == typeof(double) && double.IsNaN((double)(object)keys[i])) || (typeof(TKey) == typeof(float) && float.IsNaN((float)(object)keys[i])) || (typeof(TKey) == typeof(Half) && Half.IsNaN((Half)(object)keys[i]))) { TKey temp = keys[left]; keys[left] = keys[i]; keys[i] = temp; if ((uint)i < (uint)values.Length) // check to see if we have values { TValue tempValue = values[left]; values[left] = values[i]; values[i] = tempValue; } left++; } } return left; } } }
// 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.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Collections.Generic { #region ArraySortHelper for single arrays internal sealed partial class ArraySortHelper<T> { #region IArraySortHelper<T> Members public void Sort(Span<T> keys, IComparer<T>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { comparer ??= Comparer<T>.Default; IntrospectiveSort(keys, comparer.Compare); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } public int BinarySearch(T[] array, int index, int length, T value, IComparer<T>? comparer) { try { comparer ??= Comparer<T>.Default; return InternalBinarySearch(array, index, length, value, comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); return 0; } } #endregion internal static void Sort(Span<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null, "Check the arguments in the caller!"); // Add a try block here to detect bogus comparisons try { IntrospectiveSort(keys, comparer); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } internal static int InternalBinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer) { Debug.Assert(array != null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); int lo = index; int hi = index + length - 1; while (lo <= hi) { int i = lo + ((hi - lo) >> 1); int order = comparer.Compare(array[i], value); if (order == 0) return i; if (order < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } private static void SwapIfGreater(Span<T> keys, Comparison<T> comparer, int i, int j) { Debug.Assert(i != j); if (comparer(keys[i], keys[j]) > 0) { T key = keys[i]; keys[i] = keys[j]; keys[j] = key; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(Span<T> a, int i, int j) { Debug.Assert(i != j); T t = a[i]; a[i] = a[j]; a[j] = t; } internal static void IntrospectiveSort(Span<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null); if (keys.Length > 1) { IntroSort(keys, 2 * (BitOperations.Log2((uint)keys.Length) + 1), comparer); } } private static void IntroSort(Span<T> keys, int depthLimit, Comparison<T> comparer) { Debug.Assert(!keys.IsEmpty); Debug.Assert(depthLimit >= 0); Debug.Assert(comparer != null); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= Array.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreater(keys, comparer, 0, 1); return; } if (partitionSize == 3) { SwapIfGreater(keys, comparer, 0, 1); SwapIfGreater(keys, comparer, 0, 2); SwapIfGreater(keys, comparer, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), comparer); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), comparer); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), comparer); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys[(p+1)..partitionSize], depthLimit, comparer); partitionSize = p; } } private static int PickPivotAndPartition(Span<T> keys, Comparison<T> comparer) { Debug.Assert(keys.Length >= Array.IntrosortSizeThreshold); Debug.Assert(comparer != null); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreater(keys, comparer, 0, middle); // swap the low with the mid point SwapIfGreater(keys, comparer, 0, hi); // swap the low with the high SwapIfGreater(keys, comparer, middle, hi); // swap the middle with the high T pivot = keys[middle]; Swap(keys, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { while (comparer(keys[++left], pivot) < 0) ; while (comparer(pivot, keys[--right]) < 0) ; if (left >= right) break; Swap(keys, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, left, hi - 1); } return left; } private static void HeapSort(Span<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null); Debug.Assert(!keys.IsEmpty); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, i, n, comparer); } for (int i = n; i > 1; i--) { Swap(keys, 0, i - 1); DownHeap(keys, 1, i - 1, comparer); } } private static void DownHeap(Span<T> keys, int i, int n, Comparison<T> comparer) { Debug.Assert(comparer != null); T d = keys[i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && comparer(keys[child - 1], keys[child]) < 0) { child++; } if (!(comparer(d, keys[child - 1]) < 0)) break; keys[i - 1] = keys[child - 1]; i = child; } keys[i - 1] = d; } private static void InsertionSort(Span<T> keys, Comparison<T> comparer) { for (int i = 0; i < keys.Length - 1; i++) { T t = keys[i + 1]; int j = i; while (j >= 0 && comparer(t, keys[j]) < 0) { keys[j + 1] = keys[j]; j--; } keys[j + 1] = t; } } } internal sealed partial class GenericArraySortHelper<T> where T : IComparable<T> { // Do not add a constructor to this class because ArraySortHelper<T>.CreateSortHelper will not execute it #region IArraySortHelper<T> Members public void Sort(Span<T> keys, IComparer<T>? comparer) { try { if (comparer == null || comparer == Comparer<T>.Default) { if (keys.Length > 1) { // For floating-point, do a pre-pass to move all NaNs to the beginning // so that we can do an optimized comparison as part of the actual sort // on the remainder of the values. if (typeof(T) == typeof(double) || typeof(T) == typeof(float) || typeof(T) == typeof(Half)) { int nanLeft = SortUtils.MoveNansToFront(keys, default(Span<byte>)); if (nanLeft == keys.Length) { return; } keys = keys.Slice(nanLeft); } IntroSort(keys, 2 * (BitOperations.Log2((uint)keys.Length) + 1)); } } else { ArraySortHelper<T>.IntrospectiveSort(keys, comparer.Compare); } } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } public int BinarySearch(T[] array, int index, int length, T value, IComparer<T>? comparer) { Debug.Assert(array != null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); try { if (comparer == null || comparer == Comparer<T>.Default) { return BinarySearch(array, index, length, value); } else { return ArraySortHelper<T>.InternalBinarySearch(array, index, length, value, comparer); } } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); return 0; } } #endregion // This function is called when the user doesn't specify any comparer. // Since T is constrained here, we can call IComparable<T>.CompareTo here. // We can avoid boxing for value type and casting for reference types. private static int BinarySearch(T[] array, int index, int length, T value) { int lo = index; int hi = index + length - 1; while (lo <= hi) { int i = lo + ((hi - lo) >> 1); int order; if (array[i] == null) { order = (value == null) ? 0 : -1; } else { order = array[i].CompareTo(value); } if (order == 0) { return i; } if (order < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } /// <summary>Swaps the values in the two references if the first is greater than the second.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void SwapIfGreater(ref T i, ref T j) { if (i != null && GreaterThan(ref i, ref j)) { Swap(ref i, ref j); } } /// <summary>Swaps the values in the two references, regardless of whether the two references are the same.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(ref T i, ref T j) { Debug.Assert(!Unsafe.AreSame(ref i, ref j)); T t = i; i = j; j = t; } private static void IntroSort(Span<T> keys, int depthLimit) { Debug.Assert(!keys.IsEmpty); Debug.Assert(depthLimit >= 0); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= Array.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreater(ref keys[0], ref keys[1]); return; } if (partitionSize == 3) { ref T hiRef = ref keys[2]; ref T him1Ref = ref keys[1]; ref T loRef = ref keys[0]; SwapIfGreater(ref loRef, ref him1Ref); SwapIfGreater(ref loRef, ref hiRef); SwapIfGreater(ref him1Ref, ref hiRef); return; } InsertionSort(keys.Slice(0, partitionSize)); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize)); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize)); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys[(p+1)..partitionSize], depthLimit); partitionSize = p; } } private static int PickPivotAndPartition(Span<T> keys) { Debug.Assert(keys.Length >= Array.IntrosortSizeThreshold); // Use median-of-three to select a pivot. Grab a reference to the 0th, Length-1th, and Length/2th elements, and sort them. ref T zeroRef = ref MemoryMarshal.GetReference(keys); ref T lastRef = ref Unsafe.Add(ref zeroRef, keys.Length - 1); ref T middleRef = ref Unsafe.Add(ref zeroRef, (keys.Length - 1) >> 1); SwapIfGreater(ref zeroRef, ref middleRef); SwapIfGreater(ref zeroRef, ref lastRef); SwapIfGreater(ref middleRef, ref lastRef); // Select the middle value as the pivot, and move it to be just before the last element. ref T nextToLastRef = ref Unsafe.Add(ref zeroRef, keys.Length - 2); T pivot = middleRef; Swap(ref middleRef, ref nextToLastRef); // Walk the left and right pointers, swapping elements as necessary, until they cross. ref T leftRef = ref zeroRef, rightRef = ref nextToLastRef; while (Unsafe.IsAddressLessThan(ref leftRef, ref rightRef)) { if (pivot == null) { while (Unsafe.IsAddressLessThan(ref leftRef, ref nextToLastRef) && (leftRef = ref Unsafe.Add(ref leftRef, 1)) == null) ; while (Unsafe.IsAddressGreaterThan(ref rightRef, ref zeroRef) && (rightRef = ref Unsafe.Add(ref rightRef, -1)) != null) ; } else { while (Unsafe.IsAddressLessThan(ref leftRef, ref nextToLastRef) && GreaterThan(ref pivot, ref leftRef = ref Unsafe.Add(ref leftRef, 1))) ; while (Unsafe.IsAddressGreaterThan(ref rightRef, ref zeroRef) && LessThan(ref pivot, ref rightRef = ref Unsafe.Add(ref rightRef, -1))) ; } if (!Unsafe.IsAddressLessThan(ref leftRef, ref rightRef)) { break; } Swap(ref leftRef, ref rightRef); } // Put the pivot in the correct location. if (!Unsafe.AreSame(ref leftRef, ref nextToLastRef)) { Swap(ref leftRef, ref nextToLastRef); } return (int)((nint)Unsafe.ByteOffset(ref zeroRef, ref leftRef) / Unsafe.SizeOf<T>()); } private static void HeapSort(Span<T> keys) { Debug.Assert(!keys.IsEmpty); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, i, n); } for (int i = n; i > 1; i--) { Swap(ref keys[0], ref keys[i - 1]); DownHeap(keys, 1, i - 1); } } private static void DownHeap(Span<T> keys, int i, int n) { T d = keys[i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && (keys[child - 1] == null || LessThan(ref keys[child - 1], ref keys[child]))) { child++; } if (keys[child - 1] == null || !LessThan(ref d, ref keys[child - 1])) break; keys[i - 1] = keys[child - 1]; i = child; } keys[i - 1] = d; } private static void InsertionSort(Span<T> keys) { for (int i = 0; i < keys.Length - 1; i++) { T t = Unsafe.Add(ref MemoryMarshal.GetReference(keys), i + 1); int j = i; while (j >= 0 && (t == null || LessThan(ref t, ref Unsafe.Add(ref MemoryMarshal.GetReference(keys), j)))) { Unsafe.Add(ref MemoryMarshal.GetReference(keys), j + 1) = Unsafe.Add(ref MemoryMarshal.GetReference(keys), j); j--; } Unsafe.Add(ref MemoryMarshal.GetReference(keys), j + 1) = t!; } } // - These methods exist for use in sorting, where the additional operations present in // the CompareTo methods that would otherwise be used on these primitives add non-trivial overhead, // in particular for floating point where the CompareTo methods need to factor in NaNs. // - The floating-point comparisons here assume no NaNs, which is valid only because the sorting routines // themselves special-case NaN with a pre-pass that ensures none are present in the values being sorted // by moving them all to the front first and then sorting the rest. // - The `? true : false` is to work-around poor codegen: https://github.com/dotnet/runtime/issues/37904#issuecomment-644180265. // - These are duplicated here rather than being on a helper type due to current limitations around generic inlining. [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool LessThan(ref T left, ref T right) { if (typeof(T) == typeof(byte)) return (byte)(object)left < (byte)(object)right ? true : false; if (typeof(T) == typeof(sbyte)) return (sbyte)(object)left < (sbyte)(object)right ? true : false; if (typeof(T) == typeof(ushort)) return (ushort)(object)left < (ushort)(object)right ? true : false; if (typeof(T) == typeof(short)) return (short)(object)left < (short)(object)right ? true : false; if (typeof(T) == typeof(uint)) return (uint)(object)left < (uint)(object)right ? true : false; if (typeof(T) == typeof(int)) return (int)(object)left < (int)(object)right ? true : false; if (typeof(T) == typeof(ulong)) return (ulong)(object)left < (ulong)(object)right ? true : false; if (typeof(T) == typeof(long)) return (long)(object)left < (long)(object)right ? true : false; if (typeof(T) == typeof(nuint)) return (nuint)(object)left < (nuint)(object)right ? true : false; if (typeof(T) == typeof(nint)) return (nint)(object)left < (nint)(object)right ? true : false; if (typeof(T) == typeof(float)) return (float)(object)left < (float)(object)right ? true : false; if (typeof(T) == typeof(double)) return (double)(object)left < (double)(object)right ? true : false; if (typeof(T) == typeof(Half)) return (Half)(object)left < (Half)(object)right ? true : false; return left.CompareTo(right) < 0 ? true : false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool GreaterThan(ref T left, ref T right) { if (typeof(T) == typeof(byte)) return (byte)(object)left > (byte)(object)right ? true : false; if (typeof(T) == typeof(sbyte)) return (sbyte)(object)left > (sbyte)(object)right ? true : false; if (typeof(T) == typeof(ushort)) return (ushort)(object)left > (ushort)(object)right ? true : false; if (typeof(T) == typeof(short)) return (short)(object)left > (short)(object)right ? true : false; if (typeof(T) == typeof(uint)) return (uint)(object)left > (uint)(object)right ? true : false; if (typeof(T) == typeof(int)) return (int)(object)left > (int)(object)right ? true : false; if (typeof(T) == typeof(ulong)) return (ulong)(object)left > (ulong)(object)right ? true : false; if (typeof(T) == typeof(long)) return (long)(object)left > (long)(object)right ? true : false; if (typeof(T) == typeof(nuint)) return (nuint)(object)left > (nuint)(object)right ? true : false; if (typeof(T) == typeof(nint)) return (nint)(object)left > (nint)(object)right ? true : false; if (typeof(T) == typeof(float)) return (float)(object)left > (float)(object)right ? true : false; if (typeof(T) == typeof(double)) return (double)(object)left > (double)(object)right ? true : false; if (typeof(T) == typeof(Half)) return (Half)(object)left > (Half)(object)right ? true : false; return left.CompareTo(right) > 0 ? true : false; } } #endregion #region ArraySortHelper for paired key and value arrays internal sealed partial class ArraySortHelper<TKey, TValue> { public void Sort(Span<TKey> keys, Span<TValue> values, IComparer<TKey>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { IntrospectiveSort(keys, values, comparer ?? Comparer<TKey>.Default); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } private static void SwapIfGreaterWithValues(Span<TKey> keys, Span<TValue> values, IComparer<TKey> comparer, int i, int j) { Debug.Assert(comparer != null); Debug.Assert(0 <= i && i < keys.Length && i < values.Length); Debug.Assert(0 <= j && j < keys.Length && j < values.Length); Debug.Assert(i != j); if (comparer.Compare(keys[i], keys[j]) > 0) { TKey key = keys[i]; keys[i] = keys[j]; keys[j] = key; TValue value = values[i]; values[i] = values[j]; values[j] = value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(Span<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); TKey k = keys[i]; keys[i] = keys[j]; keys[j] = k; TValue v = values[i]; values[i] = values[j]; values[j] = v; } internal static void IntrospectiveSort(Span<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); Debug.Assert(keys.Length == values.Length); if (keys.Length > 1) { IntroSort(keys, values, 2 * (BitOperations.Log2((uint)keys.Length) + 1), comparer); } } private static void IntroSort(Span<TKey> keys, Span<TValue> values, int depthLimit, IComparer<TKey> comparer) { Debug.Assert(!keys.IsEmpty); Debug.Assert(values.Length == keys.Length); Debug.Assert(depthLimit >= 0); Debug.Assert(comparer != null); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= Array.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreaterWithValues(keys, values, comparer, 0, 1); return; } if (partitionSize == 3) { SwapIfGreaterWithValues(keys, values, comparer, 0, 1); SwapIfGreaterWithValues(keys, values, comparer, 0, 2); SwapIfGreaterWithValues(keys, values, comparer, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys[(p+1)..partitionSize], values[(p+1)..partitionSize], depthLimit, comparer); partitionSize = p; } } private static int PickPivotAndPartition(Span<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(keys.Length >= Array.IntrosortSizeThreshold); Debug.Assert(comparer != null); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreaterWithValues(keys, values, comparer, 0, middle); // swap the low with the mid point SwapIfGreaterWithValues(keys, values, comparer, 0, hi); // swap the low with the high SwapIfGreaterWithValues(keys, values, comparer, middle, hi); // swap the middle with the high TKey pivot = keys[middle]; Swap(keys, values, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { while (comparer.Compare(keys[++left], pivot) < 0) ; while (comparer.Compare(pivot, keys[--right]) < 0) ; if (left >= right) break; Swap(keys, values, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, values, left, hi - 1); } return left; } private static void HeapSort(Span<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); Debug.Assert(!keys.IsEmpty); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, values, i, n, comparer); } for (int i = n; i > 1; i--) { Swap(keys, values, 0, i - 1); DownHeap(keys, values, 1, i - 1, comparer); } } private static void DownHeap(Span<TKey> keys, Span<TValue> values, int i, int n, IComparer<TKey> comparer) { Debug.Assert(comparer != null); TKey d = keys[i - 1]; TValue dValue = values[i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && comparer.Compare(keys[child - 1], keys[child]) < 0) { child++; } if (!(comparer.Compare(d, keys[child - 1]) < 0)) break; keys[i - 1] = keys[child - 1]; values[i - 1] = values[child - 1]; i = child; } keys[i - 1] = d; values[i - 1] = dValue; } private static void InsertionSort(Span<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); for (int i = 0; i < keys.Length - 1; i++) { TKey t = keys[i + 1]; TValue tValue = values[i + 1]; int j = i; while (j >= 0 && comparer.Compare(t, keys[j]) < 0) { keys[j + 1] = keys[j]; values[j + 1] = values[j]; j--; } keys[j + 1] = t; values[j + 1] = tValue; } } } internal sealed partial class GenericArraySortHelper<TKey, TValue> where TKey : IComparable<TKey> { public void Sort(Span<TKey> keys, Span<TValue> values, IComparer<TKey>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { if (comparer == null || comparer == Comparer<TKey>.Default) { if (keys.Length > 1) { // For floating-point, do a pre-pass to move all NaNs to the beginning // so that we can do an optimized comparison as part of the actual sort // on the remainder of the values. if (typeof(TKey) == typeof(double) || typeof(TKey) == typeof(float) || typeof(TKey) == typeof(Half)) { int nanLeft = SortUtils.MoveNansToFront(keys, values); if (nanLeft == keys.Length) { return; } keys = keys.Slice(nanLeft); values = values.Slice(nanLeft); } IntroSort(keys, values, 2 * (BitOperations.Log2((uint)keys.Length) + 1)); } } else { ArraySortHelper<TKey, TValue>.IntrospectiveSort(keys, values, comparer); } } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } private static void SwapIfGreaterWithValues(Span<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); ref TKey keyRef = ref keys[i]; if (keyRef != null && GreaterThan(ref keyRef, ref keys[j])) { TKey key = keyRef; keys[i] = keys[j]; keys[j] = key; TValue value = values[i]; values[i] = values[j]; values[j] = value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(Span<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); TKey k = keys[i]; keys[i] = keys[j]; keys[j] = k; TValue v = values[i]; values[i] = values[j]; values[j] = v; } private static void IntroSort(Span<TKey> keys, Span<TValue> values, int depthLimit) { Debug.Assert(!keys.IsEmpty); Debug.Assert(values.Length == keys.Length); Debug.Assert(depthLimit >= 0); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= Array.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreaterWithValues(keys, values, 0, 1); return; } if (partitionSize == 3) { SwapIfGreaterWithValues(keys, values, 0, 1); SwapIfGreaterWithValues(keys, values, 0, 2); SwapIfGreaterWithValues(keys, values, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys[(p+1)..partitionSize], values[(p+1)..partitionSize], depthLimit); partitionSize = p; } } private static int PickPivotAndPartition(Span<TKey> keys, Span<TValue> values) { Debug.Assert(keys.Length >= Array.IntrosortSizeThreshold); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreaterWithValues(keys, values, 0, middle); // swap the low with the mid point SwapIfGreaterWithValues(keys, values, 0, hi); // swap the low with the high SwapIfGreaterWithValues(keys, values, middle, hi); // swap the middle with the high TKey pivot = keys[middle]; Swap(keys, values, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { if (pivot == null) { while (left < (hi - 1) && keys[++left] == null) ; while (right > 0 && keys[--right] != null) ; } else { while (GreaterThan(ref pivot, ref keys[++left])) ; while (LessThan(ref pivot, ref keys[--right])) ; } if (left >= right) break; Swap(keys, values, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, values, left, hi - 1); } return left; } private static void HeapSort(Span<TKey> keys, Span<TValue> values) { Debug.Assert(!keys.IsEmpty); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, values, i, n); } for (int i = n; i > 1; i--) { Swap(keys, values, 0, i - 1); DownHeap(keys, values, 1, i - 1); } } private static void DownHeap(Span<TKey> keys, Span<TValue> values, int i, int n) { TKey d = keys[i - 1]; TValue dValue = values[i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && (keys[child - 1] == null || LessThan(ref keys[child - 1], ref keys[child]))) { child++; } if (keys[child - 1] == null || !LessThan(ref d, ref keys[child - 1])) break; keys[i - 1] = keys[child - 1]; values[i - 1] = values[child - 1]; i = child; } keys[i - 1] = d; values[i - 1] = dValue; } private static void InsertionSort(Span<TKey> keys, Span<TValue> values) { for (int i = 0; i < keys.Length - 1; i++) { TKey t = keys[i + 1]; TValue tValue = values[i + 1]; int j = i; while (j >= 0 && (t == null || LessThan(ref t, ref keys[j]))) { keys[j + 1] = keys[j]; values[j + 1] = values[j]; j--; } keys[j + 1] = t!; values[j + 1] = tValue; } } // - These methods exist for use in sorting, where the additional operations present in // the CompareTo methods that would otherwise be used on these primitives add non-trivial overhead, // in particular for floating point where the CompareTo methods need to factor in NaNs. // - The floating-point comparisons here assume no NaNs, which is valid only because the sorting routines // themselves special-case NaN with a pre-pass that ensures none are present in the values being sorted // by moving them all to the front first and then sorting the rest. // - The `? true : false` is to work-around poor codegen: https://github.com/dotnet/runtime/issues/37904#issuecomment-644180265. // - These are duplicated here rather than being on a helper type due to current limitations around generic inlining. [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool LessThan(ref TKey left, ref TKey right) { if (typeof(TKey) == typeof(byte)) return (byte)(object)left < (byte)(object)right ? true : false; if (typeof(TKey) == typeof(sbyte)) return (sbyte)(object)left < (sbyte)(object)right ? true : false; if (typeof(TKey) == typeof(ushort)) return (ushort)(object)left < (ushort)(object)right ? true : false; if (typeof(TKey) == typeof(short)) return (short)(object)left < (short)(object)right ? true : false; if (typeof(TKey) == typeof(uint)) return (uint)(object)left < (uint)(object)right ? true : false; if (typeof(TKey) == typeof(int)) return (int)(object)left < (int)(object)right ? true : false; if (typeof(TKey) == typeof(ulong)) return (ulong)(object)left < (ulong)(object)right ? true : false; if (typeof(TKey) == typeof(long)) return (long)(object)left < (long)(object)right ? true : false; if (typeof(TKey) == typeof(nuint)) return (nuint)(object)left < (nuint)(object)right ? true : false; if (typeof(TKey) == typeof(nint)) return (nint)(object)left < (nint)(object)right ? true : false; if (typeof(TKey) == typeof(float)) return (float)(object)left < (float)(object)right ? true : false; if (typeof(TKey) == typeof(double)) return (double)(object)left < (double)(object)right ? true : false; if (typeof(TKey) == typeof(Half)) return (Half)(object)left < (Half)(object)right ? true : false; return left.CompareTo(right) < 0 ? true : false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool GreaterThan(ref TKey left, ref TKey right) { if (typeof(TKey) == typeof(byte)) return (byte)(object)left > (byte)(object)right ? true : false; if (typeof(TKey) == typeof(sbyte)) return (sbyte)(object)left > (sbyte)(object)right ? true : false; if (typeof(TKey) == typeof(ushort)) return (ushort)(object)left > (ushort)(object)right ? true : false; if (typeof(TKey) == typeof(short)) return (short)(object)left > (short)(object)right ? true : false; if (typeof(TKey) == typeof(uint)) return (uint)(object)left > (uint)(object)right ? true : false; if (typeof(TKey) == typeof(int)) return (int)(object)left > (int)(object)right ? true : false; if (typeof(TKey) == typeof(ulong)) return (ulong)(object)left > (ulong)(object)right ? true : false; if (typeof(TKey) == typeof(long)) return (long)(object)left > (long)(object)right ? true : false; if (typeof(TKey) == typeof(nuint)) return (nuint)(object)left > (nuint)(object)right ? true : false; if (typeof(TKey) == typeof(nint)) return (nint)(object)left > (nint)(object)right ? true : false; if (typeof(TKey) == typeof(float)) return (float)(object)left > (float)(object)right ? true : false; if (typeof(TKey) == typeof(double)) return (double)(object)left > (double)(object)right ? true : false; if (typeof(TKey) == typeof(Half)) return (Half)(object)left > (Half)(object)right ? true : false; return left.CompareTo(right) > 0 ? true : false; } } #endregion /// <summary>Helper methods for use in array/span sorting routines.</summary> internal static class SortUtils { public static int MoveNansToFront<TKey, TValue>(Span<TKey> keys, Span<TValue> values) where TKey : notnull { Debug.Assert(typeof(TKey) == typeof(double) || typeof(TKey) == typeof(float)); int left = 0; for (int i = 0; i < keys.Length; i++) { if ((typeof(TKey) == typeof(double) && double.IsNaN((double)(object)keys[i])) || (typeof(TKey) == typeof(float) && float.IsNaN((float)(object)keys[i])) || (typeof(TKey) == typeof(Half) && Half.IsNaN((Half)(object)keys[i]))) { TKey temp = keys[left]; keys[left] = keys[i]; keys[i] = temp; if ((uint)i < (uint)values.Length) // check to see if we have values { TValue tempValue = values[left]; values[left] = values[i]; values[i] = tempValue; } left++; } } return left; } } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/mono/mono/tests/verifier/valid_merge_interface_type_4.cs
using System; using System.Reflection; using System.Reflection.Emit; public interface Parent { void Test (); } public interface ParentB { void TestB (); } public class Foo : Parent, ParentB { public void Test () { Console.WriteLine ("Foo::Test"); } public void TestB () { Console.WriteLine ("Foo::TestB"); } } public class Bar : Parent, ParentB { public void Test () { Console.WriteLine ("Bar::Test"); } public void TestB () { Console.WriteLine ("Bar::TestB"); } } class Driver { public static int Main (string[] args) { ParentB p; Foo f = new Foo(); ParentB b = new Bar(); p = args == null ? (ParentB) f : (ParentB) b; p.TestB(); return 1; } }
using System; using System.Reflection; using System.Reflection.Emit; public interface Parent { void Test (); } public interface ParentB { void TestB (); } public class Foo : Parent, ParentB { public void Test () { Console.WriteLine ("Foo::Test"); } public void TestB () { Console.WriteLine ("Foo::TestB"); } } public class Bar : Parent, ParentB { public void Test () { Console.WriteLine ("Bar::Test"); } public void TestB () { Console.WriteLine ("Bar::TestB"); } } class Driver { public static int Main (string[] args) { ParentB p; Foo f = new Foo(); ParentB b = new Bar(); p = args == null ? (ParentB) f : (ParentB) b; p.TestB(); return 1; } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Drawing.Common/src/System/Drawing/ClientUtils.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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Security; namespace System.Drawing { internal static class ClientUtils { // ExecutionEngineException is obsolete and shouldn't be used (to catch, throw or reference) anymore. // Pragma added to prevent converting the "type is obsolete" warning into build error. #pragma warning disable 618 public static bool IsCriticalException(Exception ex) { return ex is NullReferenceException || ex is StackOverflowException || ex is OutOfMemoryException || ex is System.Threading.ThreadAbortException || ex is ExecutionEngineException || ex is IndexOutOfRangeException || ex is AccessViolationException; } #pragma warning restore 618 public static bool IsSecurityOrCriticalException(Exception ex) { return (ex is SecurityException) || IsCriticalException(ex); } /// <summary> /// WeakRefCollection - a collection that holds onto weak references. /// /// Essentially you pass in the object as it is, and under the covers /// we only hold a weak reference to the object. /// /// ----------------------------------------------------------------- /// !!!IMPORTANT USAGE NOTE!!! /// Users of this class should set the RefCheckThreshold property /// explicitly or call ScavengeReferences every once in a while to /// remove dead references. /// Also avoid calling Remove(item). Instead call RemoveByHashCode(item) /// to make sure dead refs are removed. /// </summary> internal sealed class WeakRefCollection : IList { internal WeakRefCollection() : this(4) { } internal WeakRefCollection(int size) => InnerList = new ArrayList(size); internal ArrayList InnerList { get; } /// <summary> /// Indicates the value where the collection should check its items to remove dead weakref left over. /// Note: When GC collects weak refs from this collection the WeakRefObject identity changes since its /// Target becomes null. This makes the item unrecognizable by the collection and cannot be /// removed - Remove(item) and Contains(item) will not find it anymore. /// A value of int.MaxValue means disabled by default. /// </summary> public int RefCheckThreshold { get; set; } = int.MaxValue; public object? this[int index] { get { if (InnerList[index] is WeakRefObject weakRef && weakRef.IsAlive) { return weakRef.Target; } return null; } set => InnerList[index] = CreateWeakRefObject(value); } public void ScavengeReferences() { int currentIndex = 0; int currentCount = Count; for (int i = 0; i < currentCount; i++) { object? item = this[currentIndex]; if (item == null) { InnerList.RemoveAt(currentIndex); } else { // Only incriment if we have not removed the item. currentIndex++; } } } public override bool Equals(object? obj) { if (!(obj is WeakRefCollection other)) { return false; } if (other == null || Count != other.Count) { return false; } for (int i = 0; i < Count; i++) { object? thisObj = InnerList[i]; object? otherObj = other.InnerList[i]; if (thisObj != otherObj) { if (thisObj is null || !thisObj.Equals(otherObj)) { return false; } } } return true; } public override int GetHashCode() => base.GetHashCode(); [return: NotNullIfNotNull("value")] private WeakRefObject? CreateWeakRefObject(object? value) { if (value == null) { return null; } return new WeakRefObject(value); } private static void Copy(WeakRefCollection sourceList, int sourceIndex, WeakRefCollection destinationList, int destinationIndex, int length) { if (sourceIndex < destinationIndex) { // We need to copy from the back forward to prevent overwrite if source and // destination lists are the same, so we need to flip the source/dest indices // to point at the end of the spans to be copied. sourceIndex = sourceIndex + length; destinationIndex = destinationIndex + length; for (; length > 0; length--) { destinationList.InnerList[--destinationIndex] = sourceList.InnerList[--sourceIndex]; } } else { for (; length > 0; length--) { destinationList.InnerList[destinationIndex++] = sourceList.InnerList[sourceIndex++]; } } } /// <summary> /// Removes the value using its hash code as its identity. /// This is needed because the underlying item in the collection may have already been collected changing /// the identity of the WeakRefObject making it impossible for the collection to identify it. /// See WeakRefObject for more info. /// </summary> public void RemoveByHashCode(object value) { if (value == null) { return; } int hash = value.GetHashCode(); for (int idx = 0; idx < InnerList.Count; idx++) { if (InnerList[idx] != null && InnerList[idx]!.GetHashCode() == hash) { RemoveAt(idx); return; } } } public void Clear() => InnerList.Clear(); public bool IsFixedSize => InnerList.IsFixedSize; public bool Contains(object? value) => InnerList.Contains(CreateWeakRefObject(value)); public void RemoveAt(int index) => InnerList.RemoveAt(index); public void Remove(object? value) => InnerList.Remove(CreateWeakRefObject(value)); public int IndexOf(object? value) => InnerList.IndexOf(CreateWeakRefObject(value)); public void Insert(int index, object? value) => InnerList.Insert(index, CreateWeakRefObject(value)); public int Add(object? value) { if (Count > RefCheckThreshold) { ScavengeReferences(); } return InnerList.Add(CreateWeakRefObject(value)); } public int Count => InnerList.Count; object ICollection.SyncRoot => InnerList.SyncRoot; public bool IsReadOnly => InnerList.IsReadOnly; public void CopyTo(Array array, int index) => InnerList.CopyTo(array, index); bool ICollection.IsSynchronized => InnerList.IsSynchronized; public IEnumerator GetEnumerator() => InnerList.GetEnumerator(); /// <summary> /// Wraps a weak ref object. /// WARNING: Use this class carefully! /// When the weak ref is collected, this object looses its identity. This is bad when the object has been /// added to a collection since Contains(WeakRef(item)) and Remove(WeakRef(item)) would not be able to /// identify the item. /// </summary> internal sealed class WeakRefObject { private readonly int _hash; private readonly WeakReference _weakHolder; internal WeakRefObject(object obj) { Debug.Assert(obj != null, "Unexpected null object!"); _weakHolder = new WeakReference(obj); _hash = obj.GetHashCode(); } internal bool IsAlive => _weakHolder.IsAlive; internal object? Target => _weakHolder.Target; public override int GetHashCode() => _hash; public override bool Equals(object? obj) { WeakRefObject? other = obj as WeakRefObject; if (other == this) { return true; } if (other == null) { return false; } if (other.Target != Target) { if (Target == null || !Target.Equals(other.Target)) { return false; } } return true; } } } } }
// 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Security; namespace System.Drawing { internal static class ClientUtils { // ExecutionEngineException is obsolete and shouldn't be used (to catch, throw or reference) anymore. // Pragma added to prevent converting the "type is obsolete" warning into build error. #pragma warning disable 618 public static bool IsCriticalException(Exception ex) { return ex is NullReferenceException || ex is StackOverflowException || ex is OutOfMemoryException || ex is System.Threading.ThreadAbortException || ex is ExecutionEngineException || ex is IndexOutOfRangeException || ex is AccessViolationException; } #pragma warning restore 618 public static bool IsSecurityOrCriticalException(Exception ex) { return (ex is SecurityException) || IsCriticalException(ex); } /// <summary> /// WeakRefCollection - a collection that holds onto weak references. /// /// Essentially you pass in the object as it is, and under the covers /// we only hold a weak reference to the object. /// /// ----------------------------------------------------------------- /// !!!IMPORTANT USAGE NOTE!!! /// Users of this class should set the RefCheckThreshold property /// explicitly or call ScavengeReferences every once in a while to /// remove dead references. /// Also avoid calling Remove(item). Instead call RemoveByHashCode(item) /// to make sure dead refs are removed. /// </summary> internal sealed class WeakRefCollection : IList { internal WeakRefCollection() : this(4) { } internal WeakRefCollection(int size) => InnerList = new ArrayList(size); internal ArrayList InnerList { get; } /// <summary> /// Indicates the value where the collection should check its items to remove dead weakref left over. /// Note: When GC collects weak refs from this collection the WeakRefObject identity changes since its /// Target becomes null. This makes the item unrecognizable by the collection and cannot be /// removed - Remove(item) and Contains(item) will not find it anymore. /// A value of int.MaxValue means disabled by default. /// </summary> public int RefCheckThreshold { get; set; } = int.MaxValue; public object? this[int index] { get { if (InnerList[index] is WeakRefObject weakRef && weakRef.IsAlive) { return weakRef.Target; } return null; } set => InnerList[index] = CreateWeakRefObject(value); } public void ScavengeReferences() { int currentIndex = 0; int currentCount = Count; for (int i = 0; i < currentCount; i++) { object? item = this[currentIndex]; if (item == null) { InnerList.RemoveAt(currentIndex); } else { // Only incriment if we have not removed the item. currentIndex++; } } } public override bool Equals(object? obj) { if (!(obj is WeakRefCollection other)) { return false; } if (other == null || Count != other.Count) { return false; } for (int i = 0; i < Count; i++) { object? thisObj = InnerList[i]; object? otherObj = other.InnerList[i]; if (thisObj != otherObj) { if (thisObj is null || !thisObj.Equals(otherObj)) { return false; } } } return true; } public override int GetHashCode() => base.GetHashCode(); [return: NotNullIfNotNull("value")] private WeakRefObject? CreateWeakRefObject(object? value) { if (value == null) { return null; } return new WeakRefObject(value); } private static void Copy(WeakRefCollection sourceList, int sourceIndex, WeakRefCollection destinationList, int destinationIndex, int length) { if (sourceIndex < destinationIndex) { // We need to copy from the back forward to prevent overwrite if source and // destination lists are the same, so we need to flip the source/dest indices // to point at the end of the spans to be copied. sourceIndex = sourceIndex + length; destinationIndex = destinationIndex + length; for (; length > 0; length--) { destinationList.InnerList[--destinationIndex] = sourceList.InnerList[--sourceIndex]; } } else { for (; length > 0; length--) { destinationList.InnerList[destinationIndex++] = sourceList.InnerList[sourceIndex++]; } } } /// <summary> /// Removes the value using its hash code as its identity. /// This is needed because the underlying item in the collection may have already been collected changing /// the identity of the WeakRefObject making it impossible for the collection to identify it. /// See WeakRefObject for more info. /// </summary> public void RemoveByHashCode(object value) { if (value == null) { return; } int hash = value.GetHashCode(); for (int idx = 0; idx < InnerList.Count; idx++) { if (InnerList[idx] != null && InnerList[idx]!.GetHashCode() == hash) { RemoveAt(idx); return; } } } public void Clear() => InnerList.Clear(); public bool IsFixedSize => InnerList.IsFixedSize; public bool Contains(object? value) => InnerList.Contains(CreateWeakRefObject(value)); public void RemoveAt(int index) => InnerList.RemoveAt(index); public void Remove(object? value) => InnerList.Remove(CreateWeakRefObject(value)); public int IndexOf(object? value) => InnerList.IndexOf(CreateWeakRefObject(value)); public void Insert(int index, object? value) => InnerList.Insert(index, CreateWeakRefObject(value)); public int Add(object? value) { if (Count > RefCheckThreshold) { ScavengeReferences(); } return InnerList.Add(CreateWeakRefObject(value)); } public int Count => InnerList.Count; object ICollection.SyncRoot => InnerList.SyncRoot; public bool IsReadOnly => InnerList.IsReadOnly; public void CopyTo(Array array, int index) => InnerList.CopyTo(array, index); bool ICollection.IsSynchronized => InnerList.IsSynchronized; public IEnumerator GetEnumerator() => InnerList.GetEnumerator(); /// <summary> /// Wraps a weak ref object. /// WARNING: Use this class carefully! /// When the weak ref is collected, this object looses its identity. This is bad when the object has been /// added to a collection since Contains(WeakRef(item)) and Remove(WeakRef(item)) would not be able to /// identify the item. /// </summary> internal sealed class WeakRefObject { private readonly int _hash; private readonly WeakReference _weakHolder; internal WeakRefObject(object obj) { Debug.Assert(obj != null, "Unexpected null object!"); _weakHolder = new WeakReference(obj); _hash = obj.GetHashCode(); } internal bool IsAlive => _weakHolder.IsAlive; internal object? Target => _weakHolder.Target; public override int GetHashCode() => _hash; public override bool Equals(object? obj) { WeakRefObject? other = obj as WeakRefObject; if (other == this) { return true; } if (other == null) { return false; } if (other.Target != Target) { if (Target == null || !Target.Equals(other.Target)) { return false; } } return true; } } } } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/tests/JIT/HardwareIntrinsics/X86/General/VectorHelpers.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.Numerics; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; using System.Runtime.CompilerServices; internal partial class IntelHardwareIntrinsicTest { public static Vector128<T> Vector128Add<T>(Vector128<T> left, Vector128<T> right) where T : struct { if (typeof(T) == typeof(byte)) { return Sse2.Add(left.AsByte(), right.AsByte()).As<byte, T>(); } else if (typeof(T) == typeof(sbyte)) { return Sse2.Add(left.AsSByte(), right.AsSByte()).As<sbyte, T>(); } else if (typeof(T) == typeof(short)) { return Sse2.Add(left.AsInt16(), right.AsInt16()).As<short, T>(); } else if (typeof(T) == typeof(ushort)) { return Sse2.Add(left.AsUInt16(), right.AsUInt16()).As<ushort, T>(); } else if (typeof(T) == typeof(int)) { return Sse2.Add(left.AsInt32(), right.AsInt32()).As<int, T>(); } else if (typeof(T) == typeof(uint)) { return Sse2.Add(left.AsUInt32(), right.AsUInt32()).As<uint, T>(); } else if (typeof(T) == typeof(long)) { return Sse2.Add(left.AsInt64(), right.AsInt64()).As<long, T>(); } else if (typeof(T) == typeof(ulong)) { return Sse2.Add(left.AsUInt64(), right.AsUInt64()).As<ulong, T>(); } else if (typeof(T) == typeof(float)) { return Sse.Add(left.AsSingle(), right.AsSingle()).As<float, T>(); } else if (typeof(T) == typeof(double)) { return Sse2.Add(left.AsDouble(), right.AsDouble()).As<double, T>(); } else { throw new NotSupportedException(); } } public static Vector256<T> Vector256Add<T>(Vector256<T> left, Vector256<T> right) where T : struct { if (typeof(T) == typeof(byte)) { return Avx2.Add(left.AsByte(), right.AsByte()).As<byte, T>(); } else if (typeof(T) == typeof(sbyte)) { return Avx2.Add(left.AsSByte(), right.AsSByte()).As<sbyte, T>(); } else if (typeof(T) == typeof(short)) { return Avx2.Add(left.AsInt16(), right.AsInt16()).As<short, T>(); } else if (typeof(T) == typeof(ushort)) { return Avx2.Add(left.AsUInt16(), right.AsUInt16()).As<ushort, T>(); } else if (typeof(T) == typeof(int)) { return Avx2.Add(left.AsInt32(), right.AsInt32()).As<int, T>(); } else if (typeof(T) == typeof(uint)) { return Avx2.Add(left.AsUInt32(), right.AsUInt32()).As<uint, T>(); } else if (typeof(T) == typeof(long)) { return Avx2.Add(left.AsInt64(), right.AsInt64()).As<long, T>(); } else if (typeof(T) == typeof(ulong)) { return Avx2.Add(left.AsUInt64(), right.AsUInt64()).As<ulong, T>(); } else if (typeof(T) == typeof(float)) { return Avx.Add(left.AsSingle(), right.AsSingle()).As<float, T>(); } else if (typeof(T) == typeof(double)) { return Avx.Add(left.AsDouble(), right.AsDouble()).As<double, T>(); } else { throw new NotSupportedException(); } } public static Vector128<T> CreateVector128<T>(T value) where T : struct { if (typeof(T) == typeof(byte)) { return Vector128.Create(Convert.ToByte(value)).As<byte, T>(); } else if (typeof(T) == typeof(sbyte)) { return Vector128.Create(Convert.ToSByte(value)).As<sbyte, T>(); } else if (typeof(T) == typeof(short)) { return Vector128.Create(Convert.ToInt16(value)).As<short, T>(); } else if (typeof(T) == typeof(ushort)) { return Vector128.Create(Convert.ToUInt16(value)).As<ushort, T>(); } else if (typeof(T) == typeof(int)) { return Vector128.Create(Convert.ToInt32(value)).As<int, T>(); } else if (typeof(T) == typeof(uint)) { return Vector128.Create(Convert.ToUInt32(value)).As<uint, T>(); } else if (typeof(T) == typeof(long)) { return Vector128.Create(Convert.ToInt64(value)).As<long, T>(); } else if (typeof(T) == typeof(ulong)) { return Vector128.Create(Convert.ToUInt64(value)).As<ulong, T>(); } else if (typeof(T) == typeof(float)) { return Vector128.Create(Convert.ToSingle(value)).As<float, T>(); } else if (typeof(T) == typeof(double)) { return Vector128.Create(Convert.ToDouble(value)).As<double, T>(); } else { throw new NotSupportedException(); } } public static Vector256<T> CreateVector256<T>(T value) where T : struct { if (typeof(T) == typeof(byte)) { return Vector256.Create(Convert.ToByte(value)).As<byte, T>(); } else if (typeof(T) == typeof(sbyte)) { return Vector256.Create(Convert.ToSByte(value)).As<sbyte, T>(); } else if (typeof(T) == typeof(short)) { return Vector256.Create(Convert.ToInt16(value)).As<short, T>(); } else if (typeof(T) == typeof(ushort)) { return Vector256.Create(Convert.ToUInt16(value)).As<ushort, T>(); } else if (typeof(T) == typeof(int)) { return Vector256.Create(Convert.ToInt32(value)).As<int, T>(); } else if (typeof(T) == typeof(uint)) { return Vector256.Create(Convert.ToUInt32(value)).As<uint, T>(); } else if (typeof(T) == typeof(long)) { return Vector256.Create(Convert.ToInt64(value)).As<long, T>(); } else if (typeof(T) == typeof(ulong)) { return Vector256.Create(Convert.ToUInt64(value)).As<ulong, T>(); } else if (typeof(T) == typeof(float)) { return Vector256.Create(Convert.ToSingle(value)).As<float, T>(); } else if (typeof(T) == typeof(double)) { return Vector256.Create(Convert.ToDouble(value)).As<double, T>(); } else { throw new NotSupportedException(); } } public static bool CheckValue<T>(T value, T expectedValue) where T : struct { bool returnVal; if (typeof(T) == typeof(float)) { returnVal = Math.Abs(((float)(object)value) - ((float)(object)expectedValue)) <= Single.Epsilon; } if (typeof(T) == typeof(double)) { returnVal = Math.Abs(((double)(object)value) - ((double)(object)expectedValue)) <= Double.Epsilon; } else { returnVal = value.Equals(expectedValue); } if (returnVal == false) { if ((typeof(T) == typeof(double)) || (typeof(T) == typeof(float))) { Console.WriteLine("CheckValue failed for type " + typeof(T).ToString() + ". Expected: {0} , Got: {1}", expectedValue, value); } else { Console.WriteLine("CheckValue failed for type " + typeof(T).ToString() + ". Expected: {0} (0x{0:X}), Got: {1} (0x{1:X})", expectedValue, value); } } return returnVal; } public static T GetValueFromInt<T>(int value) where T : struct { if (typeof(T) == typeof(float)) { float floatValue = (float)value; return (T)(object)floatValue; } if (typeof(T) == typeof(double)) { double doubleValue = (double)value; return (T)(object)doubleValue; } if (typeof(T) == typeof(int)) { return (T)(object)value; } if (typeof(T) == typeof(uint)) { uint uintValue = (uint)value; return (T)(object)uintValue; } if (typeof(T) == typeof(long)) { long longValue = (long)value; return (T)(object)longValue; } if (typeof(T) == typeof(ulong)) { ulong longValue = (ulong)value; return (T)(object)longValue; } if (typeof(T) == typeof(ushort)) { return (T)(object)(ushort)value; } if (typeof(T) == typeof(byte)) { return (T)(object)(byte)value; } if (typeof(T) == typeof(short)) { return (T)(object)(short)value; } if (typeof(T) == typeof(sbyte)) { return (T)(object)(sbyte)value; } else { throw new ArgumentException(); } } }
// 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.Numerics; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; using System.Runtime.CompilerServices; internal partial class IntelHardwareIntrinsicTest { public static Vector128<T> Vector128Add<T>(Vector128<T> left, Vector128<T> right) where T : struct { if (typeof(T) == typeof(byte)) { return Sse2.Add(left.AsByte(), right.AsByte()).As<byte, T>(); } else if (typeof(T) == typeof(sbyte)) { return Sse2.Add(left.AsSByte(), right.AsSByte()).As<sbyte, T>(); } else if (typeof(T) == typeof(short)) { return Sse2.Add(left.AsInt16(), right.AsInt16()).As<short, T>(); } else if (typeof(T) == typeof(ushort)) { return Sse2.Add(left.AsUInt16(), right.AsUInt16()).As<ushort, T>(); } else if (typeof(T) == typeof(int)) { return Sse2.Add(left.AsInt32(), right.AsInt32()).As<int, T>(); } else if (typeof(T) == typeof(uint)) { return Sse2.Add(left.AsUInt32(), right.AsUInt32()).As<uint, T>(); } else if (typeof(T) == typeof(long)) { return Sse2.Add(left.AsInt64(), right.AsInt64()).As<long, T>(); } else if (typeof(T) == typeof(ulong)) { return Sse2.Add(left.AsUInt64(), right.AsUInt64()).As<ulong, T>(); } else if (typeof(T) == typeof(float)) { return Sse.Add(left.AsSingle(), right.AsSingle()).As<float, T>(); } else if (typeof(T) == typeof(double)) { return Sse2.Add(left.AsDouble(), right.AsDouble()).As<double, T>(); } else { throw new NotSupportedException(); } } public static Vector256<T> Vector256Add<T>(Vector256<T> left, Vector256<T> right) where T : struct { if (typeof(T) == typeof(byte)) { return Avx2.Add(left.AsByte(), right.AsByte()).As<byte, T>(); } else if (typeof(T) == typeof(sbyte)) { return Avx2.Add(left.AsSByte(), right.AsSByte()).As<sbyte, T>(); } else if (typeof(T) == typeof(short)) { return Avx2.Add(left.AsInt16(), right.AsInt16()).As<short, T>(); } else if (typeof(T) == typeof(ushort)) { return Avx2.Add(left.AsUInt16(), right.AsUInt16()).As<ushort, T>(); } else if (typeof(T) == typeof(int)) { return Avx2.Add(left.AsInt32(), right.AsInt32()).As<int, T>(); } else if (typeof(T) == typeof(uint)) { return Avx2.Add(left.AsUInt32(), right.AsUInt32()).As<uint, T>(); } else if (typeof(T) == typeof(long)) { return Avx2.Add(left.AsInt64(), right.AsInt64()).As<long, T>(); } else if (typeof(T) == typeof(ulong)) { return Avx2.Add(left.AsUInt64(), right.AsUInt64()).As<ulong, T>(); } else if (typeof(T) == typeof(float)) { return Avx.Add(left.AsSingle(), right.AsSingle()).As<float, T>(); } else if (typeof(T) == typeof(double)) { return Avx.Add(left.AsDouble(), right.AsDouble()).As<double, T>(); } else { throw new NotSupportedException(); } } public static Vector128<T> CreateVector128<T>(T value) where T : struct { if (typeof(T) == typeof(byte)) { return Vector128.Create(Convert.ToByte(value)).As<byte, T>(); } else if (typeof(T) == typeof(sbyte)) { return Vector128.Create(Convert.ToSByte(value)).As<sbyte, T>(); } else if (typeof(T) == typeof(short)) { return Vector128.Create(Convert.ToInt16(value)).As<short, T>(); } else if (typeof(T) == typeof(ushort)) { return Vector128.Create(Convert.ToUInt16(value)).As<ushort, T>(); } else if (typeof(T) == typeof(int)) { return Vector128.Create(Convert.ToInt32(value)).As<int, T>(); } else if (typeof(T) == typeof(uint)) { return Vector128.Create(Convert.ToUInt32(value)).As<uint, T>(); } else if (typeof(T) == typeof(long)) { return Vector128.Create(Convert.ToInt64(value)).As<long, T>(); } else if (typeof(T) == typeof(ulong)) { return Vector128.Create(Convert.ToUInt64(value)).As<ulong, T>(); } else if (typeof(T) == typeof(float)) { return Vector128.Create(Convert.ToSingle(value)).As<float, T>(); } else if (typeof(T) == typeof(double)) { return Vector128.Create(Convert.ToDouble(value)).As<double, T>(); } else { throw new NotSupportedException(); } } public static Vector256<T> CreateVector256<T>(T value) where T : struct { if (typeof(T) == typeof(byte)) { return Vector256.Create(Convert.ToByte(value)).As<byte, T>(); } else if (typeof(T) == typeof(sbyte)) { return Vector256.Create(Convert.ToSByte(value)).As<sbyte, T>(); } else if (typeof(T) == typeof(short)) { return Vector256.Create(Convert.ToInt16(value)).As<short, T>(); } else if (typeof(T) == typeof(ushort)) { return Vector256.Create(Convert.ToUInt16(value)).As<ushort, T>(); } else if (typeof(T) == typeof(int)) { return Vector256.Create(Convert.ToInt32(value)).As<int, T>(); } else if (typeof(T) == typeof(uint)) { return Vector256.Create(Convert.ToUInt32(value)).As<uint, T>(); } else if (typeof(T) == typeof(long)) { return Vector256.Create(Convert.ToInt64(value)).As<long, T>(); } else if (typeof(T) == typeof(ulong)) { return Vector256.Create(Convert.ToUInt64(value)).As<ulong, T>(); } else if (typeof(T) == typeof(float)) { return Vector256.Create(Convert.ToSingle(value)).As<float, T>(); } else if (typeof(T) == typeof(double)) { return Vector256.Create(Convert.ToDouble(value)).As<double, T>(); } else { throw new NotSupportedException(); } } public static bool CheckValue<T>(T value, T expectedValue) where T : struct { bool returnVal; if (typeof(T) == typeof(float)) { returnVal = Math.Abs(((float)(object)value) - ((float)(object)expectedValue)) <= Single.Epsilon; } if (typeof(T) == typeof(double)) { returnVal = Math.Abs(((double)(object)value) - ((double)(object)expectedValue)) <= Double.Epsilon; } else { returnVal = value.Equals(expectedValue); } if (returnVal == false) { if ((typeof(T) == typeof(double)) || (typeof(T) == typeof(float))) { Console.WriteLine("CheckValue failed for type " + typeof(T).ToString() + ". Expected: {0} , Got: {1}", expectedValue, value); } else { Console.WriteLine("CheckValue failed for type " + typeof(T).ToString() + ". Expected: {0} (0x{0:X}), Got: {1} (0x{1:X})", expectedValue, value); } } return returnVal; } public static T GetValueFromInt<T>(int value) where T : struct { if (typeof(T) == typeof(float)) { float floatValue = (float)value; return (T)(object)floatValue; } if (typeof(T) == typeof(double)) { double doubleValue = (double)value; return (T)(object)doubleValue; } if (typeof(T) == typeof(int)) { return (T)(object)value; } if (typeof(T) == typeof(uint)) { uint uintValue = (uint)value; return (T)(object)uintValue; } if (typeof(T) == typeof(long)) { long longValue = (long)value; return (T)(object)longValue; } if (typeof(T) == typeof(ulong)) { ulong longValue = (ulong)value; return (T)(object)longValue; } if (typeof(T) == typeof(ushort)) { return (T)(object)(ushort)value; } if (typeof(T) == typeof(byte)) { return (T)(object)(byte)value; } if (typeof(T) == typeof(short)) { return (T)(object)(short)value; } if (typeof(T) == typeof(sbyte)) { return (T)(object)(sbyte)value; } else { throw new ArgumentException(); } } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/tests/JIT/HardwareIntrinsics/General/Vector64_1/op_BitwiseAnd.Int64.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 op_BitwiseAndInt64() { var test = new VectorBinaryOpTest__op_BitwiseAndInt64(); // 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__op_BitwiseAndInt64 { 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(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); 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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, 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 Vector64<Int64> _fld1; public Vector64<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__op_BitwiseAndInt64 testClass) { var result = _fld1 & _fld2; Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector64<Int64> _clsVar1; private static Vector64<Int64> _clsVar2; private Vector64<Int64> _fld1; private Vector64<Int64> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__op_BitwiseAndInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); } public VectorBinaryOpTest__op_BitwiseAndInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr) & Unsafe.Read<Vector64<Int64>>(_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(Vector64<Int64>).GetMethod("op_BitwiseAnd", new Type[] { typeof(Vector64<Int64>), typeof(Vector64<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = _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<Vector64<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr); var result = op1 & op2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__op_BitwiseAndInt64(); var result = 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 = _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 = 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(Vector64<Int64> op1, Vector64<Int64> op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (long)(left[0] & right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (long)(left[i] & right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.op_BitwiseAnd<Int64>(Vector64<Int64>, Vector64<Int64>): {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 op_BitwiseAndInt64() { var test = new VectorBinaryOpTest__op_BitwiseAndInt64(); // 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__op_BitwiseAndInt64 { 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(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); 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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, 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 Vector64<Int64> _fld1; public Vector64<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__op_BitwiseAndInt64 testClass) { var result = _fld1 & _fld2; Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector64<Int64> _clsVar1; private static Vector64<Int64> _clsVar2; private Vector64<Int64> _fld1; private Vector64<Int64> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__op_BitwiseAndInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); } public VectorBinaryOpTest__op_BitwiseAndInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr) & Unsafe.Read<Vector64<Int64>>(_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(Vector64<Int64>).GetMethod("op_BitwiseAnd", new Type[] { typeof(Vector64<Int64>), typeof(Vector64<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = _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<Vector64<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr); var result = op1 & op2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__op_BitwiseAndInt64(); var result = 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 = _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 = 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(Vector64<Int64> op1, Vector64<Int64> op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (long)(left[0] & right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (long)(left[i] & right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.op_BitwiseAnd<Int64>(Vector64<Int64>, Vector64<Int64>): {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,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/mono/System.Private.CoreLib/src/System/Runtime/InteropServices/ObjectiveCMarshal.Mono.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.Runtime.Versioning; using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices.ObjectiveC { public static partial class ObjectiveCMarshal { #pragma warning disable IDE0060 // Remove when implemented /// <summary> /// Sets a pending exception to be thrown the next time the runtime is entered from an Objective-C msgSend P/Invoke. /// </summary> /// <param name="exception">The exception.</param> /// <remarks> /// If <c>null</c> is supplied any pending exception is discarded. /// </remarks> public static void SetMessageSendPendingException(Exception? exception) => throw new NotImplementedException(); private static bool TrySetGlobalMessageSendCallback( MessageSendFunction msgSendFunction, IntPtr func) => throw new NotImplementedException(); private static unsafe bool TryInitializeReferenceTracker( delegate* unmanaged<void> beginEndCallback, delegate* unmanaged<IntPtr, int> isReferencedCallback, delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization) => throw new NotImplementedException(); private static IntPtr CreateReferenceTrackingHandleInternal( ObjectHandleOnStack obj, out int memInSizeT, out IntPtr mem) => throw new NotImplementedException(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Runtime.Versioning; using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices.ObjectiveC { public static partial class ObjectiveCMarshal { #pragma warning disable IDE0060 // Remove when implemented /// <summary> /// Sets a pending exception to be thrown the next time the runtime is entered from an Objective-C msgSend P/Invoke. /// </summary> /// <param name="exception">The exception.</param> /// <remarks> /// If <c>null</c> is supplied any pending exception is discarded. /// </remarks> public static void SetMessageSendPendingException(Exception? exception) => throw new NotImplementedException(); private static bool TrySetGlobalMessageSendCallback( MessageSendFunction msgSendFunction, IntPtr func) => throw new NotImplementedException(); private static unsafe bool TryInitializeReferenceTracker( delegate* unmanaged<void> beginEndCallback, delegate* unmanaged<IntPtr, int> isReferencedCallback, delegate* unmanaged<IntPtr, void> trackedObjectEnteredFinalization) => throw new NotImplementedException(); private static IntPtr CreateReferenceTrackingHandleInternal( ObjectHandleOnStack obj, out int memInSizeT, out IntPtr mem) => throw new NotImplementedException(); } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/tests/JIT/HardwareIntrinsics/General/Vector128_1/Zero.SByte.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 ZeroSByte() { var test = new VectorZero__ZeroSByte(); // Validates basic functionality works test.RunBasicScenario(); // 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 VectorZero__ZeroSByte { private static readonly int LargestVectorSize = 16; private static readonly int ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Vector128<SByte> result = Vector128<SByte>.Zero; ValidateResult(result); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); object result = typeof(Vector128<SByte>) .GetProperty(nameof(Vector128<SByte>.Zero), new Type[] { }) .GetGetMethod() .Invoke(null, new object[] { }); ValidateResult((Vector128<SByte>)(result)); } private void ValidateResult(Vector128<SByte> result, [CallerMemberName] string method = "") { SByte[] resultElements = new SByte[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref resultElements[0]), result); ValidateResult(resultElements, method); } private void ValidateResult(SByte[] resultElements, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != 0) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128.Zero(SByte): {method} failed:"); 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 ZeroSByte() { var test = new VectorZero__ZeroSByte(); // Validates basic functionality works test.RunBasicScenario(); // 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 VectorZero__ZeroSByte { private static readonly int LargestVectorSize = 16; private static readonly int ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Vector128<SByte> result = Vector128<SByte>.Zero; ValidateResult(result); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); object result = typeof(Vector128<SByte>) .GetProperty(nameof(Vector128<SByte>.Zero), new Type[] { }) .GetGetMethod() .Invoke(null, new object[] { }); ValidateResult((Vector128<SByte>)(result)); } private void ValidateResult(Vector128<SByte> result, [CallerMemberName] string method = "") { SByte[] resultElements = new SByte[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref resultElements[0]), result); ValidateResult(resultElements, method); } private void ValidateResult(SByte[] resultElements, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != 0) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128.Zero(SByte): {method} failed:"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/OptimizedInboxTextEncoder.AdvSimd64.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.Numerics; using System.Runtime.CompilerServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace System.Text.Encodings.Web { internal sealed partial class OptimizedInboxTextEncoder { private unsafe nuint GetIndexOfFirstByteToEncodeAdvSimd64(byte* pData, nuint lengthInBytes) { Debug.Assert(AdvSimd.Arm64.IsSupported); Debug.Assert(BitConverter.IsLittleEndian); Vector128<byte> vec0xF = Vector128.Create((byte)0xF); Vector128<byte> vecPowersOfTwo = Vector128.Create(1, 2, 4, 8, 16, 32, 64, 128, 0, 0, 0, 0, 0, 0, 0, 0); Vector128<byte> vecPairwiseAddNibbleBitmask = Vector128.Create((ushort)0xF00F).AsByte(); // little endian only Vector128<byte> allowedCodePoints = _allowedAsciiCodePoints.AsVector; ulong resultScalar; nuint i = 0; if (lengthInBytes >= 16) { nuint lastLegalIterationFor16CharRead = lengthInBytes & unchecked((nuint)(nint)~0xF); do { // Read 16 bytes at a time into a single 128-bit vector. Vector128<byte> packed = AdvSimd.LoadVector128(pData + i); // unaligned read // Each element of the packed vector corresponds to a byte of untrusted source data. It will // have the format [ ..., 0xYZ, ... ]. We use the low nibble of each byte to index into // the 'allowedCodePoints' vector, and we use the high nibble of each byte to select a bit // from the corresponding element in the 'allowedCodePoints' vector. // // Example: let packed := [ ..., 0x6D ('m'), ... ] // The final 'result' vector will contain a non-zero value in the corresponding space iff the // 0xD element in the 'allowedCodePoints' vector has its 1 << 0x6 bit set. // // We rely on the fact that when we perform an arithmetic shift of vector values to get the // high nibble into the low 4 bits, we'll smear the high (non-ASCII) bit, causing the vector // element value to be in the range [ 128..255 ]. This causes the tbl lookup to return 0x00 // for that particular element in the 'vecPowersOfTwoShuffled' vector, meaning that escaping is required. var allowedCodePointsShuffled = AdvSimd.Arm64.VectorTableLookup(allowedCodePoints, AdvSimd.And(packed, vec0xF)); var vecPowersOfTwoShuffled = AdvSimd.Arm64.VectorTableLookup(vecPowersOfTwo, AdvSimd.ShiftRightArithmetic(packed.AsSByte(), 4).AsByte()); var result = AdvSimd.CompareTest(allowedCodePointsShuffled, vecPowersOfTwoShuffled); // Now, each element of 'result' contains 0xFF if the corresponding element in 'packed' is allowed; // and it contains a zero value if the corresponding element in 'packed' is disallowed. We'll convert // this into a vector where if 0xFF occurs in an even-numbered index, it gets converted to 0x0F; and // if 0xFF occurs in an odd-numbered index, it gets converted to 0xF0. This allows us to collapse // the Vector128<byte> to a 64-bit unsigned integer, where each of the 16 nibbles in the 64-bit integer // corresponds to whether an element in the 'result' vector was originally 0xFF or 0x00. var maskedResult = AdvSimd.And(result, vecPairwiseAddNibbleBitmask); resultScalar = AdvSimd.Arm64.AddPairwise(maskedResult, maskedResult).AsUInt64().ToScalar(); if (resultScalar != ulong.MaxValue) { goto PairwiseAddMaskContainsDataWhichRequiresEscaping; } } while ((i += 16) < lastLegalIterationFor16CharRead); } if ((lengthInBytes & 8) != 0) { // Read 8 bytes at a time into a single 64-bit vector, extended to 128 bits. // Same logic as the 16-byte case, but we don't need to worry about the pairwise add step. // We'll treat the low 64 bits of the 'result' vector as its own scalar element. Vector128<byte> packed = AdvSimd.LoadVector64(pData + i).ToVector128Unsafe(); // unaligned read var allowedCodePointsShuffled = AdvSimd.Arm64.VectorTableLookup(allowedCodePoints, AdvSimd.And(packed, vec0xF)); var vecPowersOfTwoShuffled = AdvSimd.Arm64.VectorTableLookup(vecPowersOfTwo, AdvSimd.ShiftRightArithmetic(packed.AsSByte(), 4).AsByte()); var result = AdvSimd.CompareTest(allowedCodePointsShuffled, vecPowersOfTwoShuffled); resultScalar = result.AsUInt64().ToScalar(); if (resultScalar != ulong.MaxValue) { goto MaskContainsDataWhichRequiresEscaping; } i += 8; } if ((lengthInBytes & 4) != 0) { // Read 4 bytes at a time into a single element, extended to a 128-bit vector. // Same logic as the 16-byte case, but we don't need to worry about the pairwise add step. // We'll treat the low 32 bits of the 'result' vector as its own scalar element. Vector128<byte> packed = Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned<uint>(pData + i)).AsByte(); var allowedCodePointsShuffled = AdvSimd.Arm64.VectorTableLookup(allowedCodePoints, AdvSimd.And(packed, vec0xF)); var vecPowersOfTwoShuffled = AdvSimd.Arm64.VectorTableLookup(vecPowersOfTwo, AdvSimd.ShiftRightArithmetic(packed.AsSByte(), 4).AsByte()); var result = AdvSimd.CompareTest(allowedCodePointsShuffled, vecPowersOfTwoShuffled); resultScalar = result.AsUInt32().ToScalar(); // n.b. implicit conversion uint -> ulong; high 32 bits will be zeroed if (resultScalar != uint.MaxValue) { goto MaskContainsDataWhichRequiresEscaping; } i += 4; } // Beyond this point, vectorization isn't worthwhile. Just do a normal loop. if ((lengthInBytes & 3) != 0) { Debug.Assert(lengthInBytes - i <= 3); do { if (!_allowedAsciiCodePoints.IsAllowedAsciiCodePoint(pData[i])) { break; } } while (++i != lengthInBytes); } Return: return i; PairwiseAddMaskContainsDataWhichRequiresEscaping: Debug.Assert(resultScalar != ulong.MaxValue); // Each nibble is 4 (1 << 2) bits, so we shr by 2 to account for per-nibble stride. i += (uint)BitOperations.TrailingZeroCount(~resultScalar) >> 2; // location of lowest set bit is where we must begin escaping goto Return; MaskContainsDataWhichRequiresEscaping: Debug.Assert(resultScalar != ulong.MaxValue); // Each byte is 8 (1 << 3) bits, so we shr by 3 to account for per-byte stride. i += (uint)BitOperations.TrailingZeroCount(~resultScalar) >> 3; // location of lowest set bit is where we must begin escaping goto Return; } private unsafe nuint GetIndexOfFirstCharToEncodeAdvSimd64(char* pData, nuint lengthInChars) { // See GetIndexOfFirstByteToEncodeAdvSimd64 for the central logic behind this method. // The main difference here is that we need to pack WORDs to BYTEs before performing // the main vectorized logic. It doesn't matter if we use signed or unsigned saturation // while packing, as saturation will convert out-of-range (non-ASCII char) WORDs to // 0x00 or 0x7F..0xFF, all of which are forbidden by the encoder. Debug.Assert(AdvSimd.Arm64.IsSupported); Debug.Assert(BitConverter.IsLittleEndian); Vector128<byte> vec0xF = Vector128.Create((byte)0xF); Vector128<byte> vecPowersOfTwo = Vector128.Create(1, 2, 4, 8, 16, 32, 64, 128, 0, 0, 0, 0, 0, 0, 0, 0); Vector128<byte> vecPairwiseAddNibbleBitmask = Vector128.Create((ushort)0xF00F).AsByte(); // little endian only Vector128<byte> allowedCodePoints = _allowedAsciiCodePoints.AsVector; ulong resultScalar; nuint i = 0; if (lengthInChars >= 16) { nuint lastLegalIterationFor16CharRead = lengthInChars & unchecked((nuint)(nint)~0xF); do { // Read 16 chars at a time into 2x 128-bit vectors, then pack into a single 128-bit vector. // We turn 16 chars (256 bits) into 16 nibbles (64 bits) during this process. Vector128<byte> packed = AdvSimd.ExtractNarrowingSaturateUnsignedUpper( AdvSimd.ExtractNarrowingSaturateUnsignedLower(AdvSimd.LoadVector128((/* unaligned */ short*)(pData + i))), AdvSimd.LoadVector128((/* unaligned */ short*)(pData + 8 + i))); var allowedCodePointsShuffled = AdvSimd.Arm64.VectorTableLookup(allowedCodePoints, AdvSimd.And(packed, vec0xF)); var vecPowersOfTwoShuffled = AdvSimd.Arm64.VectorTableLookup(vecPowersOfTwo, AdvSimd.ShiftRightArithmetic(packed.AsSByte(), 4).AsByte()); var result = AdvSimd.CompareTest(allowedCodePointsShuffled, vecPowersOfTwoShuffled); var maskedResult = AdvSimd.And(result, vecPairwiseAddNibbleBitmask); resultScalar = AdvSimd.Arm64.AddPairwise(maskedResult, maskedResult).AsUInt64().ToScalar(); if (resultScalar != ulong.MaxValue) { goto PairwiseAddMaskContainsDataWhichRequiresEscaping; } } while ((i += 16) < lastLegalIterationFor16CharRead); } if ((lengthInChars & 8) != 0) { // Read 8 chars at a time into a single 128-bit vector, then pack into a 64-bit // vector, then extend to 128 bits. We turn 8 chars (128 bits) into 8 bytes (64 bits) // during this process. Only the low 64 bits of the 'result' vector have meaningful // data. Vector128<byte> packed = AdvSimd.ExtractNarrowingSaturateUnsignedLower(AdvSimd.LoadVector128((/* unaligned */ short*)(pData + i))).AsByte().ToVector128Unsafe(); var allowedCodePointsShuffled = AdvSimd.Arm64.VectorTableLookup(allowedCodePoints, AdvSimd.And(packed, vec0xF)); var vecPowersOfTwoShuffled = AdvSimd.Arm64.VectorTableLookup(vecPowersOfTwo, AdvSimd.ShiftRightArithmetic(packed.AsSByte(), 4).AsByte()); var result = AdvSimd.CompareTest(allowedCodePointsShuffled, vecPowersOfTwoShuffled); resultScalar = result.AsUInt64().ToScalar(); if (resultScalar != ulong.MaxValue) { goto MaskContainsDataWhichRequiresEscaping; } i += 8; } if ((lengthInChars & 4) != 0) { // Read 4 chars at a time into a single 64-bit vector, then pack into the low 32 bits // of a 128-bit vector. We turn 4 chars (64 bits) into 4 bytes (32 bits) during this // process. Only the low 32 bits of the 'result' vector have meaningful data. Vector128<byte> packed = AdvSimd.ExtractNarrowingSaturateUnsignedLower(AdvSimd.LoadVector64((/* unaligned */ short*)(pData + i)).ToVector128Unsafe()).ToVector128Unsafe(); var allowedCodePointsShuffled = AdvSimd.Arm64.VectorTableLookup(allowedCodePoints, AdvSimd.And(packed, vec0xF)); var vecPowersOfTwoShuffled = AdvSimd.Arm64.VectorTableLookup(vecPowersOfTwo, AdvSimd.ShiftRightArithmetic(packed.AsSByte(), 4).AsByte()); var result = AdvSimd.CompareTest(allowedCodePointsShuffled, vecPowersOfTwoShuffled); resultScalar = result.AsUInt32().ToScalar(); // n.b. implicit conversion uint -> ulong; high 32 bits will be zeroed if (resultScalar != uint.MaxValue) { goto MaskContainsDataWhichRequiresEscaping; } i += 4; } // Beyond this point, vectorization isn't worthwhile. Just do a normal loop. if ((lengthInChars & 3) != 0) { Debug.Assert(lengthInChars - i <= 3); do { if (!_allowedAsciiCodePoints.IsAllowedAsciiCodePoint(pData[i])) { break; } } while (++i != lengthInChars); } Return: return i; PairwiseAddMaskContainsDataWhichRequiresEscaping: Debug.Assert(resultScalar != ulong.MaxValue); // Each nibble is 4 (1 << 2) bits, so we shr by 2 to account for per-nibble stride. i += (uint)BitOperations.TrailingZeroCount(~resultScalar) >> 2; // location of lowest set bit is where we must begin escaping goto Return; MaskContainsDataWhichRequiresEscaping: Debug.Assert(resultScalar != ulong.MaxValue); // Each byte is 8 (1 << 3) bits, so we shr by 3 to account for per-byte stride. i += (uint)BitOperations.TrailingZeroCount(~resultScalar) >> 3; // location of lowest set bit is where we must begin escaping goto Return; } } }
// 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.Numerics; using System.Runtime.CompilerServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace System.Text.Encodings.Web { internal sealed partial class OptimizedInboxTextEncoder { private unsafe nuint GetIndexOfFirstByteToEncodeAdvSimd64(byte* pData, nuint lengthInBytes) { Debug.Assert(AdvSimd.Arm64.IsSupported); Debug.Assert(BitConverter.IsLittleEndian); Vector128<byte> vec0xF = Vector128.Create((byte)0xF); Vector128<byte> vecPowersOfTwo = Vector128.Create(1, 2, 4, 8, 16, 32, 64, 128, 0, 0, 0, 0, 0, 0, 0, 0); Vector128<byte> vecPairwiseAddNibbleBitmask = Vector128.Create((ushort)0xF00F).AsByte(); // little endian only Vector128<byte> allowedCodePoints = _allowedAsciiCodePoints.AsVector; ulong resultScalar; nuint i = 0; if (lengthInBytes >= 16) { nuint lastLegalIterationFor16CharRead = lengthInBytes & unchecked((nuint)(nint)~0xF); do { // Read 16 bytes at a time into a single 128-bit vector. Vector128<byte> packed = AdvSimd.LoadVector128(pData + i); // unaligned read // Each element of the packed vector corresponds to a byte of untrusted source data. It will // have the format [ ..., 0xYZ, ... ]. We use the low nibble of each byte to index into // the 'allowedCodePoints' vector, and we use the high nibble of each byte to select a bit // from the corresponding element in the 'allowedCodePoints' vector. // // Example: let packed := [ ..., 0x6D ('m'), ... ] // The final 'result' vector will contain a non-zero value in the corresponding space iff the // 0xD element in the 'allowedCodePoints' vector has its 1 << 0x6 bit set. // // We rely on the fact that when we perform an arithmetic shift of vector values to get the // high nibble into the low 4 bits, we'll smear the high (non-ASCII) bit, causing the vector // element value to be in the range [ 128..255 ]. This causes the tbl lookup to return 0x00 // for that particular element in the 'vecPowersOfTwoShuffled' vector, meaning that escaping is required. var allowedCodePointsShuffled = AdvSimd.Arm64.VectorTableLookup(allowedCodePoints, AdvSimd.And(packed, vec0xF)); var vecPowersOfTwoShuffled = AdvSimd.Arm64.VectorTableLookup(vecPowersOfTwo, AdvSimd.ShiftRightArithmetic(packed.AsSByte(), 4).AsByte()); var result = AdvSimd.CompareTest(allowedCodePointsShuffled, vecPowersOfTwoShuffled); // Now, each element of 'result' contains 0xFF if the corresponding element in 'packed' is allowed; // and it contains a zero value if the corresponding element in 'packed' is disallowed. We'll convert // this into a vector where if 0xFF occurs in an even-numbered index, it gets converted to 0x0F; and // if 0xFF occurs in an odd-numbered index, it gets converted to 0xF0. This allows us to collapse // the Vector128<byte> to a 64-bit unsigned integer, where each of the 16 nibbles in the 64-bit integer // corresponds to whether an element in the 'result' vector was originally 0xFF or 0x00. var maskedResult = AdvSimd.And(result, vecPairwiseAddNibbleBitmask); resultScalar = AdvSimd.Arm64.AddPairwise(maskedResult, maskedResult).AsUInt64().ToScalar(); if (resultScalar != ulong.MaxValue) { goto PairwiseAddMaskContainsDataWhichRequiresEscaping; } } while ((i += 16) < lastLegalIterationFor16CharRead); } if ((lengthInBytes & 8) != 0) { // Read 8 bytes at a time into a single 64-bit vector, extended to 128 bits. // Same logic as the 16-byte case, but we don't need to worry about the pairwise add step. // We'll treat the low 64 bits of the 'result' vector as its own scalar element. Vector128<byte> packed = AdvSimd.LoadVector64(pData + i).ToVector128Unsafe(); // unaligned read var allowedCodePointsShuffled = AdvSimd.Arm64.VectorTableLookup(allowedCodePoints, AdvSimd.And(packed, vec0xF)); var vecPowersOfTwoShuffled = AdvSimd.Arm64.VectorTableLookup(vecPowersOfTwo, AdvSimd.ShiftRightArithmetic(packed.AsSByte(), 4).AsByte()); var result = AdvSimd.CompareTest(allowedCodePointsShuffled, vecPowersOfTwoShuffled); resultScalar = result.AsUInt64().ToScalar(); if (resultScalar != ulong.MaxValue) { goto MaskContainsDataWhichRequiresEscaping; } i += 8; } if ((lengthInBytes & 4) != 0) { // Read 4 bytes at a time into a single element, extended to a 128-bit vector. // Same logic as the 16-byte case, but we don't need to worry about the pairwise add step. // We'll treat the low 32 bits of the 'result' vector as its own scalar element. Vector128<byte> packed = Vector128.CreateScalarUnsafe(Unsafe.ReadUnaligned<uint>(pData + i)).AsByte(); var allowedCodePointsShuffled = AdvSimd.Arm64.VectorTableLookup(allowedCodePoints, AdvSimd.And(packed, vec0xF)); var vecPowersOfTwoShuffled = AdvSimd.Arm64.VectorTableLookup(vecPowersOfTwo, AdvSimd.ShiftRightArithmetic(packed.AsSByte(), 4).AsByte()); var result = AdvSimd.CompareTest(allowedCodePointsShuffled, vecPowersOfTwoShuffled); resultScalar = result.AsUInt32().ToScalar(); // n.b. implicit conversion uint -> ulong; high 32 bits will be zeroed if (resultScalar != uint.MaxValue) { goto MaskContainsDataWhichRequiresEscaping; } i += 4; } // Beyond this point, vectorization isn't worthwhile. Just do a normal loop. if ((lengthInBytes & 3) != 0) { Debug.Assert(lengthInBytes - i <= 3); do { if (!_allowedAsciiCodePoints.IsAllowedAsciiCodePoint(pData[i])) { break; } } while (++i != lengthInBytes); } Return: return i; PairwiseAddMaskContainsDataWhichRequiresEscaping: Debug.Assert(resultScalar != ulong.MaxValue); // Each nibble is 4 (1 << 2) bits, so we shr by 2 to account for per-nibble stride. i += (uint)BitOperations.TrailingZeroCount(~resultScalar) >> 2; // location of lowest set bit is where we must begin escaping goto Return; MaskContainsDataWhichRequiresEscaping: Debug.Assert(resultScalar != ulong.MaxValue); // Each byte is 8 (1 << 3) bits, so we shr by 3 to account for per-byte stride. i += (uint)BitOperations.TrailingZeroCount(~resultScalar) >> 3; // location of lowest set bit is where we must begin escaping goto Return; } private unsafe nuint GetIndexOfFirstCharToEncodeAdvSimd64(char* pData, nuint lengthInChars) { // See GetIndexOfFirstByteToEncodeAdvSimd64 for the central logic behind this method. // The main difference here is that we need to pack WORDs to BYTEs before performing // the main vectorized logic. It doesn't matter if we use signed or unsigned saturation // while packing, as saturation will convert out-of-range (non-ASCII char) WORDs to // 0x00 or 0x7F..0xFF, all of which are forbidden by the encoder. Debug.Assert(AdvSimd.Arm64.IsSupported); Debug.Assert(BitConverter.IsLittleEndian); Vector128<byte> vec0xF = Vector128.Create((byte)0xF); Vector128<byte> vecPowersOfTwo = Vector128.Create(1, 2, 4, 8, 16, 32, 64, 128, 0, 0, 0, 0, 0, 0, 0, 0); Vector128<byte> vecPairwiseAddNibbleBitmask = Vector128.Create((ushort)0xF00F).AsByte(); // little endian only Vector128<byte> allowedCodePoints = _allowedAsciiCodePoints.AsVector; ulong resultScalar; nuint i = 0; if (lengthInChars >= 16) { nuint lastLegalIterationFor16CharRead = lengthInChars & unchecked((nuint)(nint)~0xF); do { // Read 16 chars at a time into 2x 128-bit vectors, then pack into a single 128-bit vector. // We turn 16 chars (256 bits) into 16 nibbles (64 bits) during this process. Vector128<byte> packed = AdvSimd.ExtractNarrowingSaturateUnsignedUpper( AdvSimd.ExtractNarrowingSaturateUnsignedLower(AdvSimd.LoadVector128((/* unaligned */ short*)(pData + i))), AdvSimd.LoadVector128((/* unaligned */ short*)(pData + 8 + i))); var allowedCodePointsShuffled = AdvSimd.Arm64.VectorTableLookup(allowedCodePoints, AdvSimd.And(packed, vec0xF)); var vecPowersOfTwoShuffled = AdvSimd.Arm64.VectorTableLookup(vecPowersOfTwo, AdvSimd.ShiftRightArithmetic(packed.AsSByte(), 4).AsByte()); var result = AdvSimd.CompareTest(allowedCodePointsShuffled, vecPowersOfTwoShuffled); var maskedResult = AdvSimd.And(result, vecPairwiseAddNibbleBitmask); resultScalar = AdvSimd.Arm64.AddPairwise(maskedResult, maskedResult).AsUInt64().ToScalar(); if (resultScalar != ulong.MaxValue) { goto PairwiseAddMaskContainsDataWhichRequiresEscaping; } } while ((i += 16) < lastLegalIterationFor16CharRead); } if ((lengthInChars & 8) != 0) { // Read 8 chars at a time into a single 128-bit vector, then pack into a 64-bit // vector, then extend to 128 bits. We turn 8 chars (128 bits) into 8 bytes (64 bits) // during this process. Only the low 64 bits of the 'result' vector have meaningful // data. Vector128<byte> packed = AdvSimd.ExtractNarrowingSaturateUnsignedLower(AdvSimd.LoadVector128((/* unaligned */ short*)(pData + i))).AsByte().ToVector128Unsafe(); var allowedCodePointsShuffled = AdvSimd.Arm64.VectorTableLookup(allowedCodePoints, AdvSimd.And(packed, vec0xF)); var vecPowersOfTwoShuffled = AdvSimd.Arm64.VectorTableLookup(vecPowersOfTwo, AdvSimd.ShiftRightArithmetic(packed.AsSByte(), 4).AsByte()); var result = AdvSimd.CompareTest(allowedCodePointsShuffled, vecPowersOfTwoShuffled); resultScalar = result.AsUInt64().ToScalar(); if (resultScalar != ulong.MaxValue) { goto MaskContainsDataWhichRequiresEscaping; } i += 8; } if ((lengthInChars & 4) != 0) { // Read 4 chars at a time into a single 64-bit vector, then pack into the low 32 bits // of a 128-bit vector. We turn 4 chars (64 bits) into 4 bytes (32 bits) during this // process. Only the low 32 bits of the 'result' vector have meaningful data. Vector128<byte> packed = AdvSimd.ExtractNarrowingSaturateUnsignedLower(AdvSimd.LoadVector64((/* unaligned */ short*)(pData + i)).ToVector128Unsafe()).ToVector128Unsafe(); var allowedCodePointsShuffled = AdvSimd.Arm64.VectorTableLookup(allowedCodePoints, AdvSimd.And(packed, vec0xF)); var vecPowersOfTwoShuffled = AdvSimd.Arm64.VectorTableLookup(vecPowersOfTwo, AdvSimd.ShiftRightArithmetic(packed.AsSByte(), 4).AsByte()); var result = AdvSimd.CompareTest(allowedCodePointsShuffled, vecPowersOfTwoShuffled); resultScalar = result.AsUInt32().ToScalar(); // n.b. implicit conversion uint -> ulong; high 32 bits will be zeroed if (resultScalar != uint.MaxValue) { goto MaskContainsDataWhichRequiresEscaping; } i += 4; } // Beyond this point, vectorization isn't worthwhile. Just do a normal loop. if ((lengthInChars & 3) != 0) { Debug.Assert(lengthInChars - i <= 3); do { if (!_allowedAsciiCodePoints.IsAllowedAsciiCodePoint(pData[i])) { break; } } while (++i != lengthInChars); } Return: return i; PairwiseAddMaskContainsDataWhichRequiresEscaping: Debug.Assert(resultScalar != ulong.MaxValue); // Each nibble is 4 (1 << 2) bits, so we shr by 2 to account for per-nibble stride. i += (uint)BitOperations.TrailingZeroCount(~resultScalar) >> 2; // location of lowest set bit is where we must begin escaping goto Return; MaskContainsDataWhichRequiresEscaping: Debug.Assert(resultScalar != ulong.MaxValue); // Each byte is 8 (1 << 3) bits, so we shr by 3 to account for per-byte stride. i += (uint)BitOperations.TrailingZeroCount(~resultScalar) >> 3; // location of lowest set bit is where we must begin escaping goto Return; } } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.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; using System.Threading; using System.Collections; using System.Globalization; using System.Runtime.CompilerServices; namespace System.Diagnostics { /// <summary> /// A Performance counter category object. /// </summary> public sealed class PerformanceCounterCategory { private string _categoryName; private string _categoryHelp; private string _machineName; internal const int MaxCategoryNameLength = 80; internal const int MaxCounterNameLength = 32767; internal const int MaxHelpLength = 32767; private const string PerfMutexName = "netfxperf.1.0"; public PerformanceCounterCategory() { _machineName = "."; } /// <summary> /// Creates a PerformanceCounterCategory object for given category. /// Uses the local machine. /// </summary> public PerformanceCounterCategory(string categoryName) : this(categoryName, ".") { } /// <summary> /// Creates a PerformanceCounterCategory object for given category. /// Uses the given machine name. /// </summary> public PerformanceCounterCategory(string categoryName!!, string machineName) { if (categoryName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName)); if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName)); _categoryName = categoryName; _machineName = machineName; } /// <summary> /// Gets/sets the Category name /// </summary> public string CategoryName { get { return _categoryName; } set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidProperty, nameof(CategoryName), value), nameof(value)); // the lock prevents a race between setting CategoryName and MachineName, since this permission // checks depend on both pieces of info. lock (this) { _categoryName = value; } } } /// <summary> /// Gets/sets the Category help /// </summary> public string CategoryHelp { get { if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); if (_categoryHelp == null) _categoryHelp = PerformanceCounterLib.GetCategoryHelp(_machineName, _categoryName); return _categoryHelp; } } public PerformanceCounterCategoryType CategoryType { get { using (CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName)) { // If we get MultiInstance, we can be confident it is correct. If it is single instance, though // we need to check if is a custom category and if the IsMultiInstance value is set in the registry. // If not we return Unknown if (categorySample._isMultiInstance) return PerformanceCounterCategoryType.MultiInstance; else { if (PerformanceCounterLib.IsCustomCategory(".", _categoryName)) return PerformanceCounterLib.GetCategoryType(".", _categoryName); else return PerformanceCounterCategoryType.SingleInstance; } } } } /// <summary> /// Gets/sets the Machine name /// </summary> public string MachineName { get { return _machineName; } set { if (!SyntaxCheck.CheckMachineName(value)) throw new ArgumentException(SR.Format(SR.InvalidProperty, nameof(MachineName), value), nameof(value)); // the lock prevents a race between setting CategoryName and MachineName, since this permission // checks depend on both pieces of info. lock (this) { _machineName = value; } } } /// <summary> /// Returns true if the counter is registered for this category /// </summary> public bool CounterExists(string counterName!!) { if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); return PerformanceCounterLib.CounterExists(_machineName, _categoryName, counterName); } /// <summary> /// Returns true if the counter is registered for this category on the current machine. /// </summary> public static bool CounterExists(string counterName, string categoryName) { return CounterExists(counterName, categoryName, "."); } /// <summary> /// Returns true if the counter is registered for this category on a particular machine. /// </summary> public static bool CounterExists(string counterName!!, string categoryName!!, string machineName) { if (categoryName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName)); if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName)); return PerformanceCounterLib.CounterExists(machineName, categoryName, counterName); } /// <summary> /// Registers one extensible performance category with counter type NumberOfItems32 with the system /// </summary> [Obsolete("This overload of PerformanceCounterCategory.Create has been deprecated. Use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) instead.")] public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, string counterName, string counterHelp) { CounterCreationData customData = new CounterCreationData(counterName, counterHelp, PerformanceCounterType.NumberOfItems32); return Create(categoryName, categoryHelp, PerformanceCounterCategoryType.Unknown, new CounterCreationDataCollection(new CounterCreationData[] { customData })); } /// <summary> /// Registers one extensible performance category of the specified category type with counter type NumberOfItems32 with the system /// </summary> public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) { CounterCreationData customData = new CounterCreationData(counterName, counterHelp, PerformanceCounterType.NumberOfItems32); return Create(categoryName, categoryHelp, categoryType, new CounterCreationDataCollection(new CounterCreationData[] { customData })); } /// <summary> /// Registers the extensible performance category with the system on the local machine /// </summary> [Obsolete("This overload of PerformanceCounterCategory.Create has been deprecated. Use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) instead.")] public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, CounterCreationDataCollection counterData) { return Create(categoryName, categoryHelp, PerformanceCounterCategoryType.Unknown, counterData); } public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) { if (categoryType < PerformanceCounterCategoryType.Unknown || categoryType > PerformanceCounterCategoryType.MultiInstance) throw new ArgumentOutOfRangeException(nameof(categoryType)); if (counterData == null) throw new ArgumentNullException(nameof(counterData)); CheckValidCategory(categoryName); if (categoryHelp != null) { // null categoryHelp is a valid option - it gets set to "Help Not Available" later on. CheckValidHelp(categoryHelp); } string machineName = "."; Mutex mutex = null; try { NetFrameworkUtils.EnterMutex(PerfMutexName, ref mutex); if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName) || PerformanceCounterLib.CategoryExists(machineName, categoryName)) throw new InvalidOperationException(SR.Format(SR.PerformanceCategoryExists, categoryName)); CheckValidCounterLayout(counterData); PerformanceCounterLib.RegisterCategory(categoryName, categoryType, categoryHelp, counterData); return new PerformanceCounterCategory(categoryName, machineName); } finally { if (mutex != null) { mutex.ReleaseMutex(); mutex.Close(); } } } // there is an idential copy of CheckValidCategory in PerformnaceCounterInstaller internal static void CheckValidCategory(string categoryName!!) { if (!CheckValidId(categoryName, MaxCategoryNameLength)) throw new ArgumentException(SR.Format(SR.PerfInvalidCategoryName, 1, MaxCategoryNameLength)); // 1026 chars is the size of the buffer used in perfcounter.dll to get this name. // If the categoryname plus prefix is too long, we won't be able to read the category properly. if (categoryName.Length > (1024 - SharedPerformanceCounter.DefaultFileMappingName.Length)) throw new ArgumentException(SR.CategoryNameTooLong); } internal static void CheckValidCounter(string counterName!!) { if (!CheckValidId(counterName, MaxCounterNameLength)) throw new ArgumentException(SR.Format(SR.PerfInvalidCounterName, 1, MaxCounterNameLength)); } // there is an idential copy of CheckValidId in PerformnaceCounterInstaller internal static bool CheckValidId(string id, int maxLength) { if (id.Length == 0 || id.Length > maxLength) return false; for (int index = 0; index < id.Length; ++index) { char current = id[index]; if ((index == 0 || index == (id.Length - 1)) && current == ' ') return false; if (current == '\"') return false; if (char.IsControl(current)) return false; } return true; } internal static void CheckValidHelp(string help!!) { if (help.Length > MaxHelpLength) throw new ArgumentException(SR.Format(SR.PerfInvalidHelp, 0, MaxHelpLength)); } internal static void CheckValidCounterLayout(CounterCreationDataCollection counterData) { // Ensure that there are no duplicate counter names being created Hashtable h = new Hashtable(); for (int i = 0; i < counterData.Count; i++) { if (counterData[i].CounterName == null || counterData[i].CounterName.Length == 0) { throw new ArgumentException(SR.InvalidCounterName); } int currentSampleType = (int)counterData[i].CounterType; if ((currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BULK) || (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER) || (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER_INV) || (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER) || (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER_INV) || (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_FRACTION) || (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_FRACTION) || (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_TIMER)) { if (counterData.Count <= (i + 1)) throw new InvalidOperationException(SR.CounterLayout); else { currentSampleType = (int)counterData[i + 1].CounterType; if (!PerformanceCounterLib.IsBaseCounter(currentSampleType)) throw new InvalidOperationException(SR.CounterLayout); } } else if (PerformanceCounterLib.IsBaseCounter(currentSampleType)) { if (i == 0) throw new InvalidOperationException(SR.CounterLayout); else { currentSampleType = (int)counterData[i - 1].CounterType; if ( (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BULK) && (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER) && (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER_INV) && (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER) && (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER_INV) && (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_FRACTION) && (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_FRACTION) && (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_TIMER)) throw new InvalidOperationException(SR.CounterLayout); } } if (h.ContainsKey(counterData[i].CounterName)) { throw new ArgumentException(SR.Format(SR.DuplicateCounterName, counterData[i].CounterName)); } else { h.Add(counterData[i].CounterName, string.Empty); // Ensure that all counter help strings aren't null or empty if (counterData[i].CounterHelp == null || counterData[i].CounterHelp.Length == 0) { counterData[i].CounterHelp = counterData[i].CounterName; } } } } /// <summary> /// Removes the counter (category) from the system /// </summary> public static void Delete(string categoryName) { CheckValidCategory(categoryName); string machineName = "."; categoryName = categoryName.ToLowerInvariant(); Mutex mutex = null; try { NetFrameworkUtils.EnterMutex(PerfMutexName, ref mutex); if (!PerformanceCounterLib.IsCustomCategory(machineName, categoryName)) throw new InvalidOperationException(SR.CantDeleteCategory); SharedPerformanceCounter.RemoveAllInstances(categoryName); PerformanceCounterLib.UnregisterCategory(categoryName); PerformanceCounterLib.CloseAllLibraries(); } finally { if (mutex != null) { mutex.ReleaseMutex(); mutex.Close(); } } } /// <summary> /// Returns true if the category is registered on the current machine. /// </summary> public static bool Exists(string categoryName) { return Exists(categoryName, "."); } /// <summary> /// Returns true if the category is registered in the machine. /// </summary> public static bool Exists(string categoryName!!, string machineName) { if (categoryName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName)); if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName)); if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName)) return true; return PerformanceCounterLib.CategoryExists(machineName, categoryName); } /// <summary> /// Returns the instance names for a given category /// </summary> /// <internalonly/> internal static string[] GetCounterInstances(string categoryName, string machineName) { using (CategorySample categorySample = PerformanceCounterLib.GetCategorySample(machineName, categoryName)) { if (categorySample._instanceNameTable.Count == 0) return Array.Empty<string>(); string[] instanceNames = new string[categorySample._instanceNameTable.Count]; categorySample._instanceNameTable.Keys.CopyTo(instanceNames, 0); if (instanceNames.Length == 1 && instanceNames[0] == PerformanceCounterLib.SingleInstanceName) return Array.Empty<string>(); return instanceNames; } } /// <summary> /// Returns an array of counters in this category. The counter must have only one instance. /// </summary> public PerformanceCounter[] GetCounters() { if (GetInstanceNames().Length != 0) throw new ArgumentException(SR.InstanceNameRequired); return GetCounters(""); } /// <summary> /// Returns an array of counters in this category for the given instance. /// </summary> public PerformanceCounter[] GetCounters(string instanceName!!) { if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); if (instanceName.Length != 0 && !InstanceExists(instanceName)) throw new InvalidOperationException(SR.Format(SR.MissingInstance, instanceName, _categoryName)); string[] counterNames = PerformanceCounterLib.GetCounters(_machineName, _categoryName); PerformanceCounter[] counters = new PerformanceCounter[counterNames.Length]; for (int index = 0; index < counters.Length; index++) counters[index] = new PerformanceCounter(_categoryName, counterNames[index], instanceName, _machineName, true); return counters; } /// <summary> /// Returns an array of performance counter categories for the current machine. /// </summary> public static PerformanceCounterCategory[] GetCategories() { return GetCategories("."); } /// <summary> /// Returns an array of performance counter categories for a particular machine. /// </summary> public static PerformanceCounterCategory[] GetCategories(string machineName) { if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName)); string[] categoryNames = PerformanceCounterLib.GetCategories(machineName); PerformanceCounterCategory[] categories = new PerformanceCounterCategory[categoryNames.Length]; for (int index = 0; index < categories.Length; index++) categories[index] = new PerformanceCounterCategory(categoryNames[index], machineName); return categories; } /// <summary> /// Returns an array of instances for this category /// </summary> public string[] GetInstanceNames() { if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); return GetCounterInstances(_categoryName, _machineName); } /// <summary> /// Returns true if the instance already exists for this category. /// </summary> public bool InstanceExists(string instanceName!!) { if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); using (CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName)) { return categorySample._instanceNameTable.ContainsKey(instanceName); } } /// <summary> /// Returns true if the instance already exists for the category specified. /// </summary> public static bool InstanceExists(string instanceName, string categoryName) { return InstanceExists(instanceName, categoryName, "."); } /// <summary> /// Returns true if the instance already exists for this category and machine specified. /// </summary> public static bool InstanceExists(string instanceName!!, string categoryName!!, string machineName) { if (categoryName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName)); if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName)); PerformanceCounterCategory category = new PerformanceCounterCategory(categoryName, machineName); return category.InstanceExists(instanceName); } /// <summary> /// Reads all the counter and instance data of this performance category. Note that reading the entire category /// at once can be as efficient as reading a single counter because of the way the system provides the data. /// </summary> public InstanceDataCollectionCollection ReadCategory() { if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); using (CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName)) { return categorySample.ReadCategory(); } } } [Flags] internal enum PerformanceCounterCategoryOptions { EnableReuse = 0x1, UseUniqueSharedMemory = 0x2, } }
// 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; using System.Threading; using System.Collections; using System.Globalization; using System.Runtime.CompilerServices; namespace System.Diagnostics { /// <summary> /// A Performance counter category object. /// </summary> public sealed class PerformanceCounterCategory { private string _categoryName; private string _categoryHelp; private string _machineName; internal const int MaxCategoryNameLength = 80; internal const int MaxCounterNameLength = 32767; internal const int MaxHelpLength = 32767; private const string PerfMutexName = "netfxperf.1.0"; public PerformanceCounterCategory() { _machineName = "."; } /// <summary> /// Creates a PerformanceCounterCategory object for given category. /// Uses the local machine. /// </summary> public PerformanceCounterCategory(string categoryName) : this(categoryName, ".") { } /// <summary> /// Creates a PerformanceCounterCategory object for given category. /// Uses the given machine name. /// </summary> public PerformanceCounterCategory(string categoryName!!, string machineName) { if (categoryName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName)); if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName)); _categoryName = categoryName; _machineName = machineName; } /// <summary> /// Gets/sets the Category name /// </summary> public string CategoryName { get { return _categoryName; } set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidProperty, nameof(CategoryName), value), nameof(value)); // the lock prevents a race between setting CategoryName and MachineName, since this permission // checks depend on both pieces of info. lock (this) { _categoryName = value; } } } /// <summary> /// Gets/sets the Category help /// </summary> public string CategoryHelp { get { if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); if (_categoryHelp == null) _categoryHelp = PerformanceCounterLib.GetCategoryHelp(_machineName, _categoryName); return _categoryHelp; } } public PerformanceCounterCategoryType CategoryType { get { using (CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName)) { // If we get MultiInstance, we can be confident it is correct. If it is single instance, though // we need to check if is a custom category and if the IsMultiInstance value is set in the registry. // If not we return Unknown if (categorySample._isMultiInstance) return PerformanceCounterCategoryType.MultiInstance; else { if (PerformanceCounterLib.IsCustomCategory(".", _categoryName)) return PerformanceCounterLib.GetCategoryType(".", _categoryName); else return PerformanceCounterCategoryType.SingleInstance; } } } } /// <summary> /// Gets/sets the Machine name /// </summary> public string MachineName { get { return _machineName; } set { if (!SyntaxCheck.CheckMachineName(value)) throw new ArgumentException(SR.Format(SR.InvalidProperty, nameof(MachineName), value), nameof(value)); // the lock prevents a race between setting CategoryName and MachineName, since this permission // checks depend on both pieces of info. lock (this) { _machineName = value; } } } /// <summary> /// Returns true if the counter is registered for this category /// </summary> public bool CounterExists(string counterName!!) { if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); return PerformanceCounterLib.CounterExists(_machineName, _categoryName, counterName); } /// <summary> /// Returns true if the counter is registered for this category on the current machine. /// </summary> public static bool CounterExists(string counterName, string categoryName) { return CounterExists(counterName, categoryName, "."); } /// <summary> /// Returns true if the counter is registered for this category on a particular machine. /// </summary> public static bool CounterExists(string counterName!!, string categoryName!!, string machineName) { if (categoryName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName)); if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName)); return PerformanceCounterLib.CounterExists(machineName, categoryName, counterName); } /// <summary> /// Registers one extensible performance category with counter type NumberOfItems32 with the system /// </summary> [Obsolete("This overload of PerformanceCounterCategory.Create has been deprecated. Use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) instead.")] public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, string counterName, string counterHelp) { CounterCreationData customData = new CounterCreationData(counterName, counterHelp, PerformanceCounterType.NumberOfItems32); return Create(categoryName, categoryHelp, PerformanceCounterCategoryType.Unknown, new CounterCreationDataCollection(new CounterCreationData[] { customData })); } /// <summary> /// Registers one extensible performance category of the specified category type with counter type NumberOfItems32 with the system /// </summary> public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, string counterName, string counterHelp) { CounterCreationData customData = new CounterCreationData(counterName, counterHelp, PerformanceCounterType.NumberOfItems32); return Create(categoryName, categoryHelp, categoryType, new CounterCreationDataCollection(new CounterCreationData[] { customData })); } /// <summary> /// Registers the extensible performance category with the system on the local machine /// </summary> [Obsolete("This overload of PerformanceCounterCategory.Create has been deprecated. Use System.Diagnostics.PerformanceCounterCategory.Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) instead.")] public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, CounterCreationDataCollection counterData) { return Create(categoryName, categoryHelp, PerformanceCounterCategoryType.Unknown, counterData); } public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData) { if (categoryType < PerformanceCounterCategoryType.Unknown || categoryType > PerformanceCounterCategoryType.MultiInstance) throw new ArgumentOutOfRangeException(nameof(categoryType)); if (counterData == null) throw new ArgumentNullException(nameof(counterData)); CheckValidCategory(categoryName); if (categoryHelp != null) { // null categoryHelp is a valid option - it gets set to "Help Not Available" later on. CheckValidHelp(categoryHelp); } string machineName = "."; Mutex mutex = null; try { NetFrameworkUtils.EnterMutex(PerfMutexName, ref mutex); if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName) || PerformanceCounterLib.CategoryExists(machineName, categoryName)) throw new InvalidOperationException(SR.Format(SR.PerformanceCategoryExists, categoryName)); CheckValidCounterLayout(counterData); PerformanceCounterLib.RegisterCategory(categoryName, categoryType, categoryHelp, counterData); return new PerformanceCounterCategory(categoryName, machineName); } finally { if (mutex != null) { mutex.ReleaseMutex(); mutex.Close(); } } } // there is an idential copy of CheckValidCategory in PerformnaceCounterInstaller internal static void CheckValidCategory(string categoryName!!) { if (!CheckValidId(categoryName, MaxCategoryNameLength)) throw new ArgumentException(SR.Format(SR.PerfInvalidCategoryName, 1, MaxCategoryNameLength)); // 1026 chars is the size of the buffer used in perfcounter.dll to get this name. // If the categoryname plus prefix is too long, we won't be able to read the category properly. if (categoryName.Length > (1024 - SharedPerformanceCounter.DefaultFileMappingName.Length)) throw new ArgumentException(SR.CategoryNameTooLong); } internal static void CheckValidCounter(string counterName!!) { if (!CheckValidId(counterName, MaxCounterNameLength)) throw new ArgumentException(SR.Format(SR.PerfInvalidCounterName, 1, MaxCounterNameLength)); } // there is an idential copy of CheckValidId in PerformnaceCounterInstaller internal static bool CheckValidId(string id, int maxLength) { if (id.Length == 0 || id.Length > maxLength) return false; for (int index = 0; index < id.Length; ++index) { char current = id[index]; if ((index == 0 || index == (id.Length - 1)) && current == ' ') return false; if (current == '\"') return false; if (char.IsControl(current)) return false; } return true; } internal static void CheckValidHelp(string help!!) { if (help.Length > MaxHelpLength) throw new ArgumentException(SR.Format(SR.PerfInvalidHelp, 0, MaxHelpLength)); } internal static void CheckValidCounterLayout(CounterCreationDataCollection counterData) { // Ensure that there are no duplicate counter names being created Hashtable h = new Hashtable(); for (int i = 0; i < counterData.Count; i++) { if (counterData[i].CounterName == null || counterData[i].CounterName.Length == 0) { throw new ArgumentException(SR.InvalidCounterName); } int currentSampleType = (int)counterData[i].CounterType; if ((currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BULK) || (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER) || (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER_INV) || (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER) || (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER_INV) || (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_FRACTION) || (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_FRACTION) || (currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_TIMER)) { if (counterData.Count <= (i + 1)) throw new InvalidOperationException(SR.CounterLayout); else { currentSampleType = (int)counterData[i + 1].CounterType; if (!PerformanceCounterLib.IsBaseCounter(currentSampleType)) throw new InvalidOperationException(SR.CounterLayout); } } else if (PerformanceCounterLib.IsBaseCounter(currentSampleType)) { if (i == 0) throw new InvalidOperationException(SR.CounterLayout); else { currentSampleType = (int)counterData[i - 1].CounterType; if ( (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BULK) && (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER) && (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_100NSEC_MULTI_TIMER_INV) && (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER) && (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_TIMER_INV) && (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_FRACTION) && (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_FRACTION) && (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_TIMER)) throw new InvalidOperationException(SR.CounterLayout); } } if (h.ContainsKey(counterData[i].CounterName)) { throw new ArgumentException(SR.Format(SR.DuplicateCounterName, counterData[i].CounterName)); } else { h.Add(counterData[i].CounterName, string.Empty); // Ensure that all counter help strings aren't null or empty if (counterData[i].CounterHelp == null || counterData[i].CounterHelp.Length == 0) { counterData[i].CounterHelp = counterData[i].CounterName; } } } } /// <summary> /// Removes the counter (category) from the system /// </summary> public static void Delete(string categoryName) { CheckValidCategory(categoryName); string machineName = "."; categoryName = categoryName.ToLowerInvariant(); Mutex mutex = null; try { NetFrameworkUtils.EnterMutex(PerfMutexName, ref mutex); if (!PerformanceCounterLib.IsCustomCategory(machineName, categoryName)) throw new InvalidOperationException(SR.CantDeleteCategory); SharedPerformanceCounter.RemoveAllInstances(categoryName); PerformanceCounterLib.UnregisterCategory(categoryName); PerformanceCounterLib.CloseAllLibraries(); } finally { if (mutex != null) { mutex.ReleaseMutex(); mutex.Close(); } } } /// <summary> /// Returns true if the category is registered on the current machine. /// </summary> public static bool Exists(string categoryName) { return Exists(categoryName, "."); } /// <summary> /// Returns true if the category is registered in the machine. /// </summary> public static bool Exists(string categoryName!!, string machineName) { if (categoryName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName)); if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName)); if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName)) return true; return PerformanceCounterLib.CategoryExists(machineName, categoryName); } /// <summary> /// Returns the instance names for a given category /// </summary> /// <internalonly/> internal static string[] GetCounterInstances(string categoryName, string machineName) { using (CategorySample categorySample = PerformanceCounterLib.GetCategorySample(machineName, categoryName)) { if (categorySample._instanceNameTable.Count == 0) return Array.Empty<string>(); string[] instanceNames = new string[categorySample._instanceNameTable.Count]; categorySample._instanceNameTable.Keys.CopyTo(instanceNames, 0); if (instanceNames.Length == 1 && instanceNames[0] == PerformanceCounterLib.SingleInstanceName) return Array.Empty<string>(); return instanceNames; } } /// <summary> /// Returns an array of counters in this category. The counter must have only one instance. /// </summary> public PerformanceCounter[] GetCounters() { if (GetInstanceNames().Length != 0) throw new ArgumentException(SR.InstanceNameRequired); return GetCounters(""); } /// <summary> /// Returns an array of counters in this category for the given instance. /// </summary> public PerformanceCounter[] GetCounters(string instanceName!!) { if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); if (instanceName.Length != 0 && !InstanceExists(instanceName)) throw new InvalidOperationException(SR.Format(SR.MissingInstance, instanceName, _categoryName)); string[] counterNames = PerformanceCounterLib.GetCounters(_machineName, _categoryName); PerformanceCounter[] counters = new PerformanceCounter[counterNames.Length]; for (int index = 0; index < counters.Length; index++) counters[index] = new PerformanceCounter(_categoryName, counterNames[index], instanceName, _machineName, true); return counters; } /// <summary> /// Returns an array of performance counter categories for the current machine. /// </summary> public static PerformanceCounterCategory[] GetCategories() { return GetCategories("."); } /// <summary> /// Returns an array of performance counter categories for a particular machine. /// </summary> public static PerformanceCounterCategory[] GetCategories(string machineName) { if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName)); string[] categoryNames = PerformanceCounterLib.GetCategories(machineName); PerformanceCounterCategory[] categories = new PerformanceCounterCategory[categoryNames.Length]; for (int index = 0; index < categories.Length; index++) categories[index] = new PerformanceCounterCategory(categoryNames[index], machineName); return categories; } /// <summary> /// Returns an array of instances for this category /// </summary> public string[] GetInstanceNames() { if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); return GetCounterInstances(_categoryName, _machineName); } /// <summary> /// Returns true if the instance already exists for this category. /// </summary> public bool InstanceExists(string instanceName!!) { if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); using (CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName)) { return categorySample._instanceNameTable.ContainsKey(instanceName); } } /// <summary> /// Returns true if the instance already exists for the category specified. /// </summary> public static bool InstanceExists(string instanceName, string categoryName) { return InstanceExists(instanceName, categoryName, "."); } /// <summary> /// Returns true if the instance already exists for this category and machine specified. /// </summary> public static bool InstanceExists(string instanceName!!, string categoryName!!, string machineName) { if (categoryName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName)); if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName)); PerformanceCounterCategory category = new PerformanceCounterCategory(categoryName, machineName); return category.InstanceExists(instanceName); } /// <summary> /// Reads all the counter and instance data of this performance category. Note that reading the entire category /// at once can be as efficient as reading a single counter because of the way the system provides the data. /// </summary> public InstanceDataCollectionCollection ReadCategory() { if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); using (CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName)) { return categorySample.ReadCategory(); } } } [Flags] internal enum PerformanceCounterCategoryOptions { EnableReuse = 0x1, UseUniqueSharedMemory = 0x2, } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ObjectSecurityT.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================ ** ** Class: ObjectSecurity ** ** Purpose: Generic Managed ACL wrapper ** ** Date: February 7, 2007 ** ===========================================================*/ using System; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Principal; using Microsoft.Win32.SafeHandles; namespace System.Security.AccessControl { public class AccessRule<T> : AccessRule where T : struct { #region Constructors // // Constructors for creating access rules for file objects // public AccessRule( IdentityReference identity, T rights, AccessControlType type) : this( identity, (int)(object)rights, false, InheritanceFlags.None, PropagationFlags.None, type) { } public AccessRule( string identity, T rights, AccessControlType type) : this( new NTAccount(identity), (int)(object)rights, false, InheritanceFlags.None, PropagationFlags.None, type) { } // // Constructor for creating access rules for folder objects // public AccessRule( IdentityReference identity, T rights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : this( identity, (int)(object)rights, false, inheritanceFlags, propagationFlags, type) { } public AccessRule( string identity, T rights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : this( new NTAccount(identity), (int)(object)rights, false, inheritanceFlags, propagationFlags, type) { } // // Internal constructor to be called by public constructors // and the access rule factory methods of ObjectSecurity // internal AccessRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type) { } #endregion #region Public properties public T Rights { get { return (T)(object)base.AccessMask; } } #endregion } public class AuditRule<T> : AuditRule where T : struct { #region Constructors public AuditRule( IdentityReference identity, T rights, AuditFlags flags) : this( identity, rights, InheritanceFlags.None, PropagationFlags.None, flags) { } public AuditRule( IdentityReference identity, T rights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : this( identity, (int)(object)rights, false, inheritanceFlags, propagationFlags, flags) { } public AuditRule( string identity, T rights, AuditFlags flags) : this( new NTAccount(identity), rights, InheritanceFlags.None, PropagationFlags.None, flags) { } public AuditRule( string identity, T rights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : this( new NTAccount(identity), (int)(object)rights, false, inheritanceFlags, propagationFlags, flags) { } internal AuditRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags) { } #endregion #region Public properties public T Rights { get { return (T)(object)base.AccessMask; } } #endregion } public abstract class ObjectSecurity<T> : NativeObjectSecurity where T : struct { #region Constructors protected ObjectSecurity(bool isContainer, ResourceType resourceType) : base(isContainer, resourceType, null, null) { } protected ObjectSecurity(bool isContainer, ResourceType resourceType, string? name, AccessControlSections includeSections) : base(isContainer, resourceType, name, includeSections, null, null) { } protected ObjectSecurity(bool isContainer, ResourceType resourceType, string? name, AccessControlSections includeSections, ExceptionFromErrorCode? exceptionFromErrorCode, object? exceptionContext) : base(isContainer, resourceType, name, includeSections, exceptionFromErrorCode, exceptionContext) { } protected ObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle? safeHandle, AccessControlSections includeSections) : base(isContainer, resourceType, safeHandle, includeSections, null, null) { } protected ObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle? safeHandle, AccessControlSections includeSections, ExceptionFromErrorCode? exceptionFromErrorCode, object? exceptionContext) : base(isContainer, resourceType, safeHandle, includeSections, exceptionFromErrorCode, exceptionContext) { } #endregion #region Factories public override AccessRule AccessRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) { return new AccessRule<T>( identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type); } public override AuditRule AuditRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) { return new AuditRule<T>( identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags); } #endregion #region Private Methods private AccessControlSections GetAccessControlSectionsFromChanges() { AccessControlSections persistRules = AccessControlSections.None; if (AccessRulesModified) { persistRules = AccessControlSections.Access; } if (AuditRulesModified) { persistRules |= AccessControlSections.Audit; } if (OwnerModified) { persistRules |= AccessControlSections.Owner; } if (GroupModified) { persistRules |= AccessControlSections.Group; } return persistRules; } #endregion #region Protected Methods // Use this in your own Persist after you have demanded any appropriate CAS permissions. // Note that you will want your version to be internal and use a specialized Safe Handle. protected internal void Persist(SafeHandle handle) { WriteLock(); try { AccessControlSections persistRules = GetAccessControlSectionsFromChanges(); base.Persist(handle, persistRules); OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; } finally { WriteUnlock(); } } // Use this in your own Persist after you have demanded any appropriate CAS permissions. // Note that you will want your version to be internal. protected internal void Persist(string name) { WriteLock(); try { AccessControlSections persistRules = GetAccessControlSectionsFromChanges(); base.Persist(name, persistRules); OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; } finally { WriteUnlock(); } } #endregion #region Public Methods // Override these if you need to do some custom bit remapping to hide any // complexity from the user. public virtual void AddAccessRule(AccessRule<T> rule) { base.AddAccessRule(rule); } public virtual void SetAccessRule(AccessRule<T> rule) { base.SetAccessRule(rule); } public virtual void ResetAccessRule(AccessRule<T> rule) { base.ResetAccessRule(rule); } public virtual bool RemoveAccessRule(AccessRule<T> rule) { return base.RemoveAccessRule(rule); } public virtual void RemoveAccessRuleAll(AccessRule<T> rule) { base.RemoveAccessRuleAll(rule); } public virtual void RemoveAccessRuleSpecific(AccessRule<T> rule) { base.RemoveAccessRuleSpecific(rule); } public virtual void AddAuditRule(AuditRule<T> rule) { base.AddAuditRule(rule); } public virtual void SetAuditRule(AuditRule<T> rule) { base.SetAuditRule(rule); } public virtual bool RemoveAuditRule(AuditRule<T> rule) { return base.RemoveAuditRule(rule); } public virtual void RemoveAuditRuleAll(AuditRule<T> rule) { base.RemoveAuditRuleAll(rule); } public virtual void RemoveAuditRuleSpecific(AuditRule<T> rule) { base.RemoveAuditRuleSpecific(rule); } #endregion #region some overrides public override Type AccessRightType { get { return typeof(T); } } public override Type AccessRuleType { get { return typeof(AccessRule<T>); } } public override Type AuditRuleType { get { return typeof(AuditRule<T>); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================ ** ** Class: ObjectSecurity ** ** Purpose: Generic Managed ACL wrapper ** ** Date: February 7, 2007 ** ===========================================================*/ using System; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Principal; using Microsoft.Win32.SafeHandles; namespace System.Security.AccessControl { public class AccessRule<T> : AccessRule where T : struct { #region Constructors // // Constructors for creating access rules for file objects // public AccessRule( IdentityReference identity, T rights, AccessControlType type) : this( identity, (int)(object)rights, false, InheritanceFlags.None, PropagationFlags.None, type) { } public AccessRule( string identity, T rights, AccessControlType type) : this( new NTAccount(identity), (int)(object)rights, false, InheritanceFlags.None, PropagationFlags.None, type) { } // // Constructor for creating access rules for folder objects // public AccessRule( IdentityReference identity, T rights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : this( identity, (int)(object)rights, false, inheritanceFlags, propagationFlags, type) { } public AccessRule( string identity, T rights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : this( new NTAccount(identity), (int)(object)rights, false, inheritanceFlags, propagationFlags, type) { } // // Internal constructor to be called by public constructors // and the access rule factory methods of ObjectSecurity // internal AccessRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type) { } #endregion #region Public properties public T Rights { get { return (T)(object)base.AccessMask; } } #endregion } public class AuditRule<T> : AuditRule where T : struct { #region Constructors public AuditRule( IdentityReference identity, T rights, AuditFlags flags) : this( identity, rights, InheritanceFlags.None, PropagationFlags.None, flags) { } public AuditRule( IdentityReference identity, T rights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : this( identity, (int)(object)rights, false, inheritanceFlags, propagationFlags, flags) { } public AuditRule( string identity, T rights, AuditFlags flags) : this( new NTAccount(identity), rights, InheritanceFlags.None, PropagationFlags.None, flags) { } public AuditRule( string identity, T rights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : this( new NTAccount(identity), (int)(object)rights, false, inheritanceFlags, propagationFlags, flags) { } internal AuditRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags) { } #endregion #region Public properties public T Rights { get { return (T)(object)base.AccessMask; } } #endregion } public abstract class ObjectSecurity<T> : NativeObjectSecurity where T : struct { #region Constructors protected ObjectSecurity(bool isContainer, ResourceType resourceType) : base(isContainer, resourceType, null, null) { } protected ObjectSecurity(bool isContainer, ResourceType resourceType, string? name, AccessControlSections includeSections) : base(isContainer, resourceType, name, includeSections, null, null) { } protected ObjectSecurity(bool isContainer, ResourceType resourceType, string? name, AccessControlSections includeSections, ExceptionFromErrorCode? exceptionFromErrorCode, object? exceptionContext) : base(isContainer, resourceType, name, includeSections, exceptionFromErrorCode, exceptionContext) { } protected ObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle? safeHandle, AccessControlSections includeSections) : base(isContainer, resourceType, safeHandle, includeSections, null, null) { } protected ObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle? safeHandle, AccessControlSections includeSections, ExceptionFromErrorCode? exceptionFromErrorCode, object? exceptionContext) : base(isContainer, resourceType, safeHandle, includeSections, exceptionFromErrorCode, exceptionContext) { } #endregion #region Factories public override AccessRule AccessRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) { return new AccessRule<T>( identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type); } public override AuditRule AuditRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) { return new AuditRule<T>( identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags); } #endregion #region Private Methods private AccessControlSections GetAccessControlSectionsFromChanges() { AccessControlSections persistRules = AccessControlSections.None; if (AccessRulesModified) { persistRules = AccessControlSections.Access; } if (AuditRulesModified) { persistRules |= AccessControlSections.Audit; } if (OwnerModified) { persistRules |= AccessControlSections.Owner; } if (GroupModified) { persistRules |= AccessControlSections.Group; } return persistRules; } #endregion #region Protected Methods // Use this in your own Persist after you have demanded any appropriate CAS permissions. // Note that you will want your version to be internal and use a specialized Safe Handle. protected internal void Persist(SafeHandle handle) { WriteLock(); try { AccessControlSections persistRules = GetAccessControlSectionsFromChanges(); base.Persist(handle, persistRules); OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; } finally { WriteUnlock(); } } // Use this in your own Persist after you have demanded any appropriate CAS permissions. // Note that you will want your version to be internal. protected internal void Persist(string name) { WriteLock(); try { AccessControlSections persistRules = GetAccessControlSectionsFromChanges(); base.Persist(name, persistRules); OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; } finally { WriteUnlock(); } } #endregion #region Public Methods // Override these if you need to do some custom bit remapping to hide any // complexity from the user. public virtual void AddAccessRule(AccessRule<T> rule) { base.AddAccessRule(rule); } public virtual void SetAccessRule(AccessRule<T> rule) { base.SetAccessRule(rule); } public virtual void ResetAccessRule(AccessRule<T> rule) { base.ResetAccessRule(rule); } public virtual bool RemoveAccessRule(AccessRule<T> rule) { return base.RemoveAccessRule(rule); } public virtual void RemoveAccessRuleAll(AccessRule<T> rule) { base.RemoveAccessRuleAll(rule); } public virtual void RemoveAccessRuleSpecific(AccessRule<T> rule) { base.RemoveAccessRuleSpecific(rule); } public virtual void AddAuditRule(AuditRule<T> rule) { base.AddAuditRule(rule); } public virtual void SetAuditRule(AuditRule<T> rule) { base.SetAuditRule(rule); } public virtual bool RemoveAuditRule(AuditRule<T> rule) { return base.RemoveAuditRule(rule); } public virtual void RemoveAuditRuleAll(AuditRule<T> rule) { base.RemoveAuditRuleAll(rule); } public virtual void RemoveAuditRuleSpecific(AuditRule<T> rule) { base.RemoveAuditRuleSpecific(rule); } #endregion #region some overrides public override Type AccessRightType { get { return typeof(T); } } public override Type AccessRuleType { get { return typeof(AccessRule<T>); } } public override Type AuditRuleType { get { return typeof(AuditRule<T>); } } #endregion } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/BsdIPGlobalProperties.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.Versioning; namespace System.Net.NetworkInformation { internal sealed class BsdIPGlobalProperties : UnixIPGlobalProperties { private unsafe TcpConnectionInformation[] GetTcpConnections(bool listeners) { int realCount = Interop.Sys.GetEstimatedTcpConnectionCount(); int infoCount = realCount * 2; Interop.Sys.NativeTcpConnectionInformation[] infos = new Interop.Sys.NativeTcpConnectionInformation[infoCount]; fixed (Interop.Sys.NativeTcpConnectionInformation* infosPtr = infos) { if (Interop.Sys.GetActiveTcpConnectionInfos(infosPtr, &infoCount) == -1) { throw new NetworkInformationException(SR.net_PInvokeError); } } TcpConnectionInformation[] connectionInformations = new TcpConnectionInformation[infoCount]; int nextResultIndex = 0; for (int i = 0; i < infoCount; i++) { Interop.Sys.NativeTcpConnectionInformation nativeInfo = infos[i]; TcpState state = nativeInfo.State; if (listeners != (state == TcpState.Listen)) { continue; } byte[] localBytes = new byte[nativeInfo.LocalEndPoint.NumAddressBytes]; fixed (byte* localBytesPtr = localBytes) { Buffer.MemoryCopy(nativeInfo.LocalEndPoint.AddressBytes, localBytesPtr, localBytes.Length, localBytes.Length); } IPAddress localIPAddress = new IPAddress(localBytes); IPEndPoint local = new IPEndPoint(localIPAddress, (int)nativeInfo.LocalEndPoint.Port); IPAddress remoteIPAddress; if (nativeInfo.RemoteEndPoint.NumAddressBytes == 0) { remoteIPAddress = IPAddress.Any; } else { byte[] remoteBytes = new byte[nativeInfo.RemoteEndPoint.NumAddressBytes]; fixed (byte* remoteBytesPtr = &remoteBytes[0]) { Buffer.MemoryCopy(nativeInfo.RemoteEndPoint.AddressBytes, remoteBytesPtr, remoteBytes.Length, remoteBytes.Length); } remoteIPAddress = new IPAddress(remoteBytes); } IPEndPoint remote = new IPEndPoint(remoteIPAddress, (int)nativeInfo.RemoteEndPoint.Port); connectionInformations[nextResultIndex++] = new SimpleTcpConnectionInformation(local, remote, state); } if (nextResultIndex != connectionInformations.Length) { Array.Resize(ref connectionInformations, nextResultIndex); } return connectionInformations; } public override TcpConnectionInformation[] GetActiveTcpConnections() { return GetTcpConnections(listeners:false); } public override IPEndPoint[] GetActiveTcpListeners() { TcpConnectionInformation[] allConnections = GetTcpConnections(listeners:true); var endPoints = new IPEndPoint[allConnections.Length]; for (int i = 0; i < allConnections.Length; i++) { endPoints[i] = allConnections[i].LocalEndPoint; } return endPoints; } public unsafe override IPEndPoint[] GetActiveUdpListeners() { int realCount = Interop.Sys.GetEstimatedUdpListenerCount(); int infoCount = realCount * 2; Interop.Sys.IPEndPointInfo[] infos = new Interop.Sys.IPEndPointInfo[infoCount]; fixed (Interop.Sys.IPEndPointInfo* infosPtr = infos) { if (Interop.Sys.GetActiveUdpListeners(infosPtr, &infoCount) == -1) { throw new NetworkInformationException(SR.net_PInvokeError); } } IPEndPoint[] endPoints = new IPEndPoint[infoCount]; for (int i = 0; i < infoCount; i++) { Interop.Sys.IPEndPointInfo endPointInfo = infos[i]; int port = (int)endPointInfo.Port; IPAddress ipAddress; if (endPointInfo.NumAddressBytes == 0) { ipAddress = IPAddress.Any; } else { byte[] bytes = new byte[endPointInfo.NumAddressBytes]; fixed (byte* bytesPtr = &bytes[0]) { Buffer.MemoryCopy(endPointInfo.AddressBytes, bytesPtr, bytes.Length, bytes.Length); } ipAddress = new IPAddress(bytes); } endPoints[i] = new IPEndPoint(ipAddress, port); } return endPoints; } public override IcmpV4Statistics GetIcmpV4Statistics() { return new BsdIcmpV4Statistics(); } public override IcmpV6Statistics GetIcmpV6Statistics() { return new BsdIcmpV6Statistics(); } public override IPGlobalStatistics GetIPv4GlobalStatistics() { return new BsdIPv4GlobalStatistics(); } [UnsupportedOSPlatform("osx")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [UnsupportedOSPlatform("freebsd")] public override IPGlobalStatistics GetIPv6GlobalStatistics() { // Although there is a 'net.inet6.ip6.stats' sysctl variable, there // is no header for the ip6stat structure and therefore isn't available. throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); } public override TcpStatistics GetTcpIPv4Statistics() { // OSX does not provide separated TCP-IPv4 and TCP-IPv6 stats. return new BsdTcpStatistics(); } public override TcpStatistics GetTcpIPv6Statistics() { // OSX does not provide separated TCP-IPv4 and TCP-IPv6 stats. return new BsdTcpStatistics(); } public override UdpStatistics GetUdpIPv4Statistics() { // OSX does not provide separated UDP-IPv4 and UDP-IPv6 stats. return new BsdUdpStatistics(); } public override UdpStatistics GetUdpIPv6Statistics() { // OSX does not provide separated UDP-IPv4 and UDP-IPv6 stats. return new BsdUdpStatistics(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.Versioning; namespace System.Net.NetworkInformation { internal sealed class BsdIPGlobalProperties : UnixIPGlobalProperties { private unsafe TcpConnectionInformation[] GetTcpConnections(bool listeners) { int realCount = Interop.Sys.GetEstimatedTcpConnectionCount(); int infoCount = realCount * 2; Interop.Sys.NativeTcpConnectionInformation[] infos = new Interop.Sys.NativeTcpConnectionInformation[infoCount]; fixed (Interop.Sys.NativeTcpConnectionInformation* infosPtr = infos) { if (Interop.Sys.GetActiveTcpConnectionInfos(infosPtr, &infoCount) == -1) { throw new NetworkInformationException(SR.net_PInvokeError); } } TcpConnectionInformation[] connectionInformations = new TcpConnectionInformation[infoCount]; int nextResultIndex = 0; for (int i = 0; i < infoCount; i++) { Interop.Sys.NativeTcpConnectionInformation nativeInfo = infos[i]; TcpState state = nativeInfo.State; if (listeners != (state == TcpState.Listen)) { continue; } byte[] localBytes = new byte[nativeInfo.LocalEndPoint.NumAddressBytes]; fixed (byte* localBytesPtr = localBytes) { Buffer.MemoryCopy(nativeInfo.LocalEndPoint.AddressBytes, localBytesPtr, localBytes.Length, localBytes.Length); } IPAddress localIPAddress = new IPAddress(localBytes); IPEndPoint local = new IPEndPoint(localIPAddress, (int)nativeInfo.LocalEndPoint.Port); IPAddress remoteIPAddress; if (nativeInfo.RemoteEndPoint.NumAddressBytes == 0) { remoteIPAddress = IPAddress.Any; } else { byte[] remoteBytes = new byte[nativeInfo.RemoteEndPoint.NumAddressBytes]; fixed (byte* remoteBytesPtr = &remoteBytes[0]) { Buffer.MemoryCopy(nativeInfo.RemoteEndPoint.AddressBytes, remoteBytesPtr, remoteBytes.Length, remoteBytes.Length); } remoteIPAddress = new IPAddress(remoteBytes); } IPEndPoint remote = new IPEndPoint(remoteIPAddress, (int)nativeInfo.RemoteEndPoint.Port); connectionInformations[nextResultIndex++] = new SimpleTcpConnectionInformation(local, remote, state); } if (nextResultIndex != connectionInformations.Length) { Array.Resize(ref connectionInformations, nextResultIndex); } return connectionInformations; } public override TcpConnectionInformation[] GetActiveTcpConnections() { return GetTcpConnections(listeners:false); } public override IPEndPoint[] GetActiveTcpListeners() { TcpConnectionInformation[] allConnections = GetTcpConnections(listeners:true); var endPoints = new IPEndPoint[allConnections.Length]; for (int i = 0; i < allConnections.Length; i++) { endPoints[i] = allConnections[i].LocalEndPoint; } return endPoints; } public unsafe override IPEndPoint[] GetActiveUdpListeners() { int realCount = Interop.Sys.GetEstimatedUdpListenerCount(); int infoCount = realCount * 2; Interop.Sys.IPEndPointInfo[] infos = new Interop.Sys.IPEndPointInfo[infoCount]; fixed (Interop.Sys.IPEndPointInfo* infosPtr = infos) { if (Interop.Sys.GetActiveUdpListeners(infosPtr, &infoCount) == -1) { throw new NetworkInformationException(SR.net_PInvokeError); } } IPEndPoint[] endPoints = new IPEndPoint[infoCount]; for (int i = 0; i < infoCount; i++) { Interop.Sys.IPEndPointInfo endPointInfo = infos[i]; int port = (int)endPointInfo.Port; IPAddress ipAddress; if (endPointInfo.NumAddressBytes == 0) { ipAddress = IPAddress.Any; } else { byte[] bytes = new byte[endPointInfo.NumAddressBytes]; fixed (byte* bytesPtr = &bytes[0]) { Buffer.MemoryCopy(endPointInfo.AddressBytes, bytesPtr, bytes.Length, bytes.Length); } ipAddress = new IPAddress(bytes); } endPoints[i] = new IPEndPoint(ipAddress, port); } return endPoints; } public override IcmpV4Statistics GetIcmpV4Statistics() { return new BsdIcmpV4Statistics(); } public override IcmpV6Statistics GetIcmpV6Statistics() { return new BsdIcmpV6Statistics(); } public override IPGlobalStatistics GetIPv4GlobalStatistics() { return new BsdIPv4GlobalStatistics(); } [UnsupportedOSPlatform("osx")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [UnsupportedOSPlatform("freebsd")] public override IPGlobalStatistics GetIPv6GlobalStatistics() { // Although there is a 'net.inet6.ip6.stats' sysctl variable, there // is no header for the ip6stat structure and therefore isn't available. throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); } public override TcpStatistics GetTcpIPv4Statistics() { // OSX does not provide separated TCP-IPv4 and TCP-IPv6 stats. return new BsdTcpStatistics(); } public override TcpStatistics GetTcpIPv6Statistics() { // OSX does not provide separated TCP-IPv4 and TCP-IPv6 stats. return new BsdTcpStatistics(); } public override UdpStatistics GetUdpIPv4Statistics() { // OSX does not provide separated UDP-IPv4 and UDP-IPv6 stats. return new BsdUdpStatistics(); } public override UdpStatistics GetUdpIPv6Statistics() { // OSX does not provide separated UDP-IPv4 and UDP-IPv6 stats. return new BsdUdpStatistics(); } } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.ComponentModel.EventBasedAsync/ref/System.ComponentModel.EventBasedAsync.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.ComponentModel { public partial class AsyncCompletedEventArgs : System.EventArgs { public AsyncCompletedEventArgs(System.Exception? error, bool cancelled, object? userState) { } public bool Cancelled { get { throw null; } } public System.Exception? Error { get { throw null; } } public object? UserState { get { throw null; } } protected void RaiseExceptionIfNecessary() { } } public delegate void AsyncCompletedEventHandler(object? sender, System.ComponentModel.AsyncCompletedEventArgs e); public sealed partial class AsyncOperation { internal AsyncOperation() { } public System.Threading.SynchronizationContext SynchronizationContext { get { throw null; } } public object? UserSuppliedState { get { throw null; } } ~AsyncOperation() { } public void OperationCompleted() { } public void Post(System.Threading.SendOrPostCallback d, object? arg) { } public void PostOperationCompleted(System.Threading.SendOrPostCallback d, object? arg) { } } public static partial class AsyncOperationManager { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static System.Threading.SynchronizationContext SynchronizationContext { get { throw null; } set { } } public static System.ComponentModel.AsyncOperation CreateOperation(object? userSuppliedState) { throw null; } } public partial class BackgroundWorker : System.ComponentModel.Component { public BackgroundWorker() { } public bool CancellationPending { get { throw null; } } public bool IsBusy { get { throw null; } } public bool WorkerReportsProgress { get { throw null; } set { } } public bool WorkerSupportsCancellation { get { throw null; } set { } } public event System.ComponentModel.DoWorkEventHandler? DoWork { add { } remove { } } public event System.ComponentModel.ProgressChangedEventHandler? ProgressChanged { add { } remove { } } public event System.ComponentModel.RunWorkerCompletedEventHandler? RunWorkerCompleted { add { } remove { } } public void CancelAsync() { } protected override void Dispose(bool disposing) { } protected virtual void OnDoWork(System.ComponentModel.DoWorkEventArgs e) { } protected virtual void OnProgressChanged(System.ComponentModel.ProgressChangedEventArgs e) { } protected virtual void OnRunWorkerCompleted(System.ComponentModel.RunWorkerCompletedEventArgs e) { } public void ReportProgress(int percentProgress) { } public void ReportProgress(int percentProgress, object? userState) { } public void RunWorkerAsync() { } public void RunWorkerAsync(object? argument) { } } public partial class DoWorkEventArgs : System.ComponentModel.CancelEventArgs { public DoWorkEventArgs(object? argument) { } public object? Argument { get { throw null; } } public object? Result { get { throw null; } set { } } } public delegate void DoWorkEventHandler(object? sender, System.ComponentModel.DoWorkEventArgs e); public partial class ProgressChangedEventArgs : System.EventArgs { public ProgressChangedEventArgs(int progressPercentage, object? userState) { } public int ProgressPercentage { get { throw null; } } public object? UserState { get { throw null; } } } public delegate void ProgressChangedEventHandler(object? sender, System.ComponentModel.ProgressChangedEventArgs e); public partial class RunWorkerCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { public RunWorkerCompletedEventArgs(object? result, System.Exception? error, bool cancelled) : base (default(System.Exception), default(bool), default(object)) { } public object? Result { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public new object? UserState { get { throw null; } } } public delegate void RunWorkerCompletedEventHandler(object? sender, System.ComponentModel.RunWorkerCompletedEventArgs e); }
// 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.ComponentModel { public partial class AsyncCompletedEventArgs : System.EventArgs { public AsyncCompletedEventArgs(System.Exception? error, bool cancelled, object? userState) { } public bool Cancelled { get { throw null; } } public System.Exception? Error { get { throw null; } } public object? UserState { get { throw null; } } protected void RaiseExceptionIfNecessary() { } } public delegate void AsyncCompletedEventHandler(object? sender, System.ComponentModel.AsyncCompletedEventArgs e); public sealed partial class AsyncOperation { internal AsyncOperation() { } public System.Threading.SynchronizationContext SynchronizationContext { get { throw null; } } public object? UserSuppliedState { get { throw null; } } ~AsyncOperation() { } public void OperationCompleted() { } public void Post(System.Threading.SendOrPostCallback d, object? arg) { } public void PostOperationCompleted(System.Threading.SendOrPostCallback d, object? arg) { } } public static partial class AsyncOperationManager { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static System.Threading.SynchronizationContext SynchronizationContext { get { throw null; } set { } } public static System.ComponentModel.AsyncOperation CreateOperation(object? userSuppliedState) { throw null; } } public partial class BackgroundWorker : System.ComponentModel.Component { public BackgroundWorker() { } public bool CancellationPending { get { throw null; } } public bool IsBusy { get { throw null; } } public bool WorkerReportsProgress { get { throw null; } set { } } public bool WorkerSupportsCancellation { get { throw null; } set { } } public event System.ComponentModel.DoWorkEventHandler? DoWork { add { } remove { } } public event System.ComponentModel.ProgressChangedEventHandler? ProgressChanged { add { } remove { } } public event System.ComponentModel.RunWorkerCompletedEventHandler? RunWorkerCompleted { add { } remove { } } public void CancelAsync() { } protected override void Dispose(bool disposing) { } protected virtual void OnDoWork(System.ComponentModel.DoWorkEventArgs e) { } protected virtual void OnProgressChanged(System.ComponentModel.ProgressChangedEventArgs e) { } protected virtual void OnRunWorkerCompleted(System.ComponentModel.RunWorkerCompletedEventArgs e) { } public void ReportProgress(int percentProgress) { } public void ReportProgress(int percentProgress, object? userState) { } public void RunWorkerAsync() { } public void RunWorkerAsync(object? argument) { } } public partial class DoWorkEventArgs : System.ComponentModel.CancelEventArgs { public DoWorkEventArgs(object? argument) { } public object? Argument { get { throw null; } } public object? Result { get { throw null; } set { } } } public delegate void DoWorkEventHandler(object? sender, System.ComponentModel.DoWorkEventArgs e); public partial class ProgressChangedEventArgs : System.EventArgs { public ProgressChangedEventArgs(int progressPercentage, object? userState) { } public int ProgressPercentage { get { throw null; } } public object? UserState { get { throw null; } } } public delegate void ProgressChangedEventHandler(object? sender, System.ComponentModel.ProgressChangedEventArgs e); public partial class RunWorkerCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { public RunWorkerCompletedEventArgs(object? result, System.Exception? error, bool cancelled) : base (default(System.Exception), default(bool), default(object)) { } public object? Result { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public new object? UserState { get { throw null; } } } public delegate void RunWorkerCompletedEventHandler(object? sender, System.ComponentModel.RunWorkerCompletedEventArgs e); }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/tasks/Crossgen2Tasks/CommonFilePulledFromSdkRepo/TaskBase.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 Microsoft.Build.Utilities; using Microsoft.Build.Framework; using System.Collections.Generic; using System.Globalization; namespace Microsoft.NET.Build.Tasks { public abstract class TaskBase : Task { private Logger _logger; internal TaskBase(Logger logger = null) { _logger = logger; } internal new Logger Log { get { if (_logger == null) { _logger = new LogAdapter(base.Log); } return _logger; } } public override bool Execute() { try { ExecuteCore(); } catch (BuildErrorException e) { Log.LogError(e.Message); } catch (Exception e) { LogErrorTelemetry("taskBaseCatchException", e); throw; } return !Log.HasLoggedErrors; } private void LogErrorTelemetry(string eventName, Exception e) { (BuildEngine as IBuildEngine5)?.LogTelemetry(eventName, new Dictionary<string, string> { {"exceptionType", e.GetType().ToString() }, {"detail", ExceptionToStringWithoutMessage(e) }}); } private static string ExceptionToStringWithoutMessage(Exception e) { const string AggregateException_ToString = "{0}{1}---> (Inner Exception #{2}) {3}{4}{5}"; if (e is AggregateException aggregate) { string text = NonAggregateExceptionToStringWithoutMessage(aggregate); for (int i = 0; i < aggregate.InnerExceptions.Count; i++) { text = string.Format(CultureInfo.InvariantCulture, AggregateException_ToString, text, Environment.NewLine, i, ExceptionToStringWithoutMessage(aggregate.InnerExceptions[i]), "<---", Environment.NewLine); } return text; } else { return NonAggregateExceptionToStringWithoutMessage(e); } } private static string NonAggregateExceptionToStringWithoutMessage(Exception e) { string s; const string Exception_EndOfInnerExceptionStack = "--- End of inner exception stack trace ---"; s = e.GetType().ToString(); if (e.InnerException != null) { s = s + " ---> " + ExceptionToStringWithoutMessage(e.InnerException) + Environment.NewLine + " " + Exception_EndOfInnerExceptionStack; } var stackTrace = e.StackTrace; if (stackTrace != null) { s += Environment.NewLine + stackTrace; } return s; } protected abstract void ExecuteCore(); } }
// 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 Microsoft.Build.Utilities; using Microsoft.Build.Framework; using System.Collections.Generic; using System.Globalization; namespace Microsoft.NET.Build.Tasks { public abstract class TaskBase : Task { private Logger _logger; internal TaskBase(Logger logger = null) { _logger = logger; } internal new Logger Log { get { if (_logger == null) { _logger = new LogAdapter(base.Log); } return _logger; } } public override bool Execute() { try { ExecuteCore(); } catch (BuildErrorException e) { Log.LogError(e.Message); } catch (Exception e) { LogErrorTelemetry("taskBaseCatchException", e); throw; } return !Log.HasLoggedErrors; } private void LogErrorTelemetry(string eventName, Exception e) { (BuildEngine as IBuildEngine5)?.LogTelemetry(eventName, new Dictionary<string, string> { {"exceptionType", e.GetType().ToString() }, {"detail", ExceptionToStringWithoutMessage(e) }}); } private static string ExceptionToStringWithoutMessage(Exception e) { const string AggregateException_ToString = "{0}{1}---> (Inner Exception #{2}) {3}{4}{5}"; if (e is AggregateException aggregate) { string text = NonAggregateExceptionToStringWithoutMessage(aggregate); for (int i = 0; i < aggregate.InnerExceptions.Count; i++) { text = string.Format(CultureInfo.InvariantCulture, AggregateException_ToString, text, Environment.NewLine, i, ExceptionToStringWithoutMessage(aggregate.InnerExceptions[i]), "<---", Environment.NewLine); } return text; } else { return NonAggregateExceptionToStringWithoutMessage(e); } } private static string NonAggregateExceptionToStringWithoutMessage(Exception e) { string s; const string Exception_EndOfInnerExceptionStack = "--- End of inner exception stack trace ---"; s = e.GetType().ToString(); if (e.InnerException != null) { s = s + " ---> " + ExceptionToStringWithoutMessage(e.InnerException) + Environment.NewLine + " " + Exception_EndOfInnerExceptionStack; } var stackTrace = e.StackTrace; if (stackTrace != null) { s += Environment.NewLine + stackTrace; } return s; } protected abstract void ExecuteCore(); } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/tests/readytorun/r2rdump/BasicTests/files/HelloWorld.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 HelloWorld { class HelloWorld { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
// 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 HelloWorld { class HelloWorld { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/tests/JIT/HardwareIntrinsics/X86/Sse41/Min.UInt32.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 MinUInt32() { var test = new SimpleBinaryOpTest__MinUInt32(); 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__MinUInt32 { 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(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); 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<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, 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<UInt32> _fld1; public Vector128<UInt32> _fld2; 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 < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MinUInt32 testClass) { var result = Sse41.Min(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MinUInt32 testClass) { fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) { var result = Sse41.Min( Sse2.LoadVector128((UInt32*)(pFld1)), Sse2.LoadVector128((UInt32*)(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<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private Vector128<UInt32> _fld1; private Vector128<UInt32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MinUInt32() { 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 < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public SimpleBinaryOpTest__MinUInt32() { 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 < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.Min( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_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 = Sse41.Min( Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_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 = Sse41.Min( Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_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(Sse41).GetMethod(nameof(Sse41.Min), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Min), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Min), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.Min( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt32>* pClsVar2 = &_clsVar2) { var result = Sse41.Min( Sse2.LoadVector128((UInt32*)(pClsVar1)), Sse2.LoadVector128((UInt32*)(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<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr); var result = Sse41.Min(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((UInt32*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Sse41.Min(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((UInt32*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Sse41.Min(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MinUInt32(); var result = Sse41.Min(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__MinUInt32(); fixed (Vector128<UInt32>* pFld1 = &test._fld1) fixed (Vector128<UInt32>* pFld2 = &test._fld2) { var result = Sse41.Min( Sse2.LoadVector128((UInt32*)(pFld1)), Sse2.LoadVector128((UInt32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.Min(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) { var result = Sse41.Min( Sse2.LoadVector128((UInt32*)(pFld1)), Sse2.LoadVector128((UInt32*)(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 = Sse41.Min(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 = Sse41.Min( Sse2.LoadVector128((UInt32*)(&test._fld1)), Sse2.LoadVector128((UInt32*)(&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<UInt32> op1, Vector128<UInt32> op2, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; 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 inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != Math.Min(left[0], right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != Math.Min(left[i], right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Min)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {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 MinUInt32() { var test = new SimpleBinaryOpTest__MinUInt32(); 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__MinUInt32 { 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(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); 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<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, 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<UInt32> _fld1; public Vector128<UInt32> _fld2; 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 < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MinUInt32 testClass) { var result = Sse41.Min(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MinUInt32 testClass) { fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) { var result = Sse41.Min( Sse2.LoadVector128((UInt32*)(pFld1)), Sse2.LoadVector128((UInt32*)(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<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private Vector128<UInt32> _fld1; private Vector128<UInt32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MinUInt32() { 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 < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public SimpleBinaryOpTest__MinUInt32() { 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 < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.Min( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_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 = Sse41.Min( Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_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 = Sse41.Min( Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_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(Sse41).GetMethod(nameof(Sse41.Min), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Min), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Min), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.Min( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt32>* pClsVar2 = &_clsVar2) { var result = Sse41.Min( Sse2.LoadVector128((UInt32*)(pClsVar1)), Sse2.LoadVector128((UInt32*)(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<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr); var result = Sse41.Min(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((UInt32*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Sse41.Min(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((UInt32*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Sse41.Min(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MinUInt32(); var result = Sse41.Min(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__MinUInt32(); fixed (Vector128<UInt32>* pFld1 = &test._fld1) fixed (Vector128<UInt32>* pFld2 = &test._fld2) { var result = Sse41.Min( Sse2.LoadVector128((UInt32*)(pFld1)), Sse2.LoadVector128((UInt32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.Min(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) { var result = Sse41.Min( Sse2.LoadVector128((UInt32*)(pFld1)), Sse2.LoadVector128((UInt32*)(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 = Sse41.Min(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 = Sse41.Min( Sse2.LoadVector128((UInt32*)(&test._fld1)), Sse2.LoadVector128((UInt32*)(&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<UInt32> op1, Vector128<UInt32> op2, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; 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 inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != Math.Min(left[0], right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != Math.Min(left[i], right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Min)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {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,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Private.Xml/tests/XmlSchema/TestFiles/TestData/AllowXmlAttributes/v8-1.xsd
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="base"> <xs:attribute name="att1" use="required"/> <xs:attribute name="att2" use="optional"/> </xs:complexType> <xs:element name="doc"> <xs:complexType> <xs:complexContent> <xs:restriction base="base"> <xs:attribute name="att1" use="required"/> <xs:attribute name="att2" use="prohibited"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> </xs:schema>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="base"> <xs:attribute name="att1" use="required"/> <xs:attribute name="att2" use="optional"/> </xs:complexType> <xs:element name="doc"> <xs:complexType> <xs:complexContent> <xs:restriction base="base"> <xs:attribute name="att1" use="required"/> <xs:attribute name="att2" use="prohibited"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> </xs:schema>
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Buffers/src/System.Buffers.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <IsPartialFacadeAssembly>true</IsPartialFacadeAssembly> <ExcludeResourcesImport>true</ExcludeResourcesImport> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <ProjectReference Include="$(CoreLibProject)" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <IsPartialFacadeAssembly>true</IsPartialFacadeAssembly> <ExcludeResourcesImport>true</ExcludeResourcesImport> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <ProjectReference Include="$(CoreLibProject)" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstanceType.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.Diagnostics.PerformanceData { /// <summary> /// Enum of friendly names to CounterSet instance type (maps directory to the native types defined in perflib.h) /// </summary> public enum CounterSetInstanceType { /// <summary> /// Single means that at any time CounterSet should only have at most 1 active instance. /// </summary> Single = 0, // PERF_COUNTERSET_SINGLE_INSTANCE /// <summary> /// Multiple means that CounterSet could have multiple active instances. /// </summary> Multiple = 0x00000002, // PERF_COUNTERSET_MULTI_INSTANCES /// <summary> /// GlobalAggregate means that CounterSet could have multiple active instances, but counter consumption /// applications (for example, perfmon) would aggregate raw counter data from different instances. /// </summary> GlobalAggregate = 0x00000004, // PERF_COUNTERSET_SINGLE_AGGREGATE /// <summary> /// GlobalAggregateWithHistory is similar to GlobalAggregate, but counter consumption applications /// (for example, permfon) would aggregate raw counter data not only from active instances, but also /// from instances since consumption applications start. /// </summary> GlobalAggregateWithHistory = 0x0000000B, // PERF_COUNTERSET_SINGLE_AGGREGATE_HISTORY /// <summary> /// MultipleInstancesWithAggregate acts similar to Multiple, but it also generate aggregated instace /// "_Total" that hosts aggregated raw counter data from all other instances. /// </summary> MultipleAggregate = 0x00000006, // PERF_COUNTERSET_MULTI_AGGREGATE /// <summary> /// InstanceAggregate only exists in Longhonr Server. Counter consumption applications aggregate raw /// counter data for active instances with the same instance name. /// </summary> InstanceAggregate = 0x00000016 // PERF_COUNTERSET_INSTANCE_AGGREGATE } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Diagnostics.PerformanceData { /// <summary> /// Enum of friendly names to CounterSet instance type (maps directory to the native types defined in perflib.h) /// </summary> public enum CounterSetInstanceType { /// <summary> /// Single means that at any time CounterSet should only have at most 1 active instance. /// </summary> Single = 0, // PERF_COUNTERSET_SINGLE_INSTANCE /// <summary> /// Multiple means that CounterSet could have multiple active instances. /// </summary> Multiple = 0x00000002, // PERF_COUNTERSET_MULTI_INSTANCES /// <summary> /// GlobalAggregate means that CounterSet could have multiple active instances, but counter consumption /// applications (for example, perfmon) would aggregate raw counter data from different instances. /// </summary> GlobalAggregate = 0x00000004, // PERF_COUNTERSET_SINGLE_AGGREGATE /// <summary> /// GlobalAggregateWithHistory is similar to GlobalAggregate, but counter consumption applications /// (for example, permfon) would aggregate raw counter data not only from active instances, but also /// from instances since consumption applications start. /// </summary> GlobalAggregateWithHistory = 0x0000000B, // PERF_COUNTERSET_SINGLE_AGGREGATE_HISTORY /// <summary> /// MultipleInstancesWithAggregate acts similar to Multiple, but it also generate aggregated instace /// "_Total" that hosts aggregated raw counter data from all other instances. /// </summary> MultipleAggregate = 0x00000006, // PERF_COUNTERSET_MULTI_AGGREGATE /// <summary> /// InstanceAggregate only exists in Longhonr Server. Counter consumption applications aggregate raw /// counter data for active instances with the same instance name. /// </summary> InstanceAggregate = 0x00000016 // PERF_COUNTERSET_INSTANCE_AGGREGATE } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest107/Generated107.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="Generated107.il" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\TestFramework\TestFramework.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="Generated107.il" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\TestFramework\TestFramework.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./eng/common/templates/steps/run-on-windows.yml
parameters: agentOs: '' steps: [] steps: - ${{ if eq(parameters.agentOs, 'Windows_NT') }}: - ${{ parameters.steps }}
parameters: agentOs: '' steps: [] steps: - ${{ if eq(parameters.agentOs, 'Windows_NT') }}: - ${{ parameters.steps }}
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Threading.Tasks.Extensions/tests/AsyncValueTaskMethodBuilderTests.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.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks.Sources.Tests; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Threading.Tasks.Tests { public class AsyncValueTaskMethodBuilderTests { [Fact] public void Create_ReturnsDefaultInstance() // implementation detail being verified { Assert.Equal(default, AsyncValueTaskMethodBuilder.Create()); Assert.Equal(default, AsyncValueTaskMethodBuilder<int>.Create()); } [Fact] public void NonGeneric_SetResult_BeforeAccessTask_ValueTaskIsDefault() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); b.SetResult(); Assert.Equal(default, b.Task); } [Fact] public void Generic_SetResult_BeforeAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); b.SetResult(42); ValueTask<int> vt = b.Task; Assert.Equal(vt, b.Task); Assert.Equal(new ValueTask<int>(42), vt); } [Fact] public void NonGeneric_SetResult_AfterAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); ValueTask vt = b.Task; Assert.NotEqual(default, vt); Assert.Equal(vt, b.Task); b.SetResult(); Assert.Equal(vt, b.Task); Assert.True(vt.IsCompletedSuccessfully); } [Fact] public void Generic_SetResult_AfterAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); ValueTask<int> vt = b.Task; Assert.NotEqual(default, vt); Assert.Equal(vt, b.Task); b.SetResult(42); Assert.Equal(vt, b.Task); Assert.True(vt.IsCompletedSuccessfully); Assert.Equal(42, vt.Result); } [Fact] public void NonGeneric_SetException_BeforeAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); var e = new FormatException(); b.SetException(e); ValueTask vt = b.Task; Assert.Equal(vt, b.Task); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Generic_SetException_BeforeAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); var e = new FormatException(); b.SetException(e); ValueTask<int> vt = b.Task; Assert.Equal(vt, b.Task); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void NonGeneric_SetException_AfterAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); ValueTask vt = b.Task; Assert.Equal(vt, b.Task); var e = new FormatException(); b.SetException(e); Assert.Equal(vt, b.Task); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Generic_SetException_AfterAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); ValueTask<int> vt = b.Task; Assert.Equal(vt, b.Task); var e = new FormatException(); b.SetException(e); Assert.Equal(vt, b.Task); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void NonGeneric_SetException_OperationCanceledException_CancelsTask() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); ValueTask vt = b.Task; Assert.Equal(vt, b.Task); var e = new OperationCanceledException(); b.SetException(e); Assert.Equal(vt, b.Task); Assert.True(vt.IsCanceled); Assert.Same(e, Assert.Throws<OperationCanceledException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Generic_SetException_OperationCanceledException_CancelsTask() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); ValueTask<int> vt = b.Task; Assert.Equal(vt, b.Task); var e = new OperationCanceledException(); b.SetException(e); Assert.Equal(vt, b.Task); Assert.True(vt.IsCanceled); Assert.Same(e, Assert.Throws<OperationCanceledException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void NonGeneric_SetExceptionWithNullException_Throws() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); AssertExtensions.Throws<ArgumentNullException>("exception", () => b.SetException(null)); } [Fact] public void Generic_SetExceptionWithNullException_Throws() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); AssertExtensions.Throws<ArgumentNullException>("exception", () => b.SetException(null)); } [Fact] public void NonGeneric_Start_InvokesMoveNext() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); int invokes = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => invokes++ }; b.Start(ref dsm); Assert.Equal(1, invokes); } [Fact] public void Generic_Start_InvokesMoveNext() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); int invokes = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => invokes++ }; b.Start(ref dsm); Assert.Equal(1, invokes); } [Theory] [InlineData(1, false)] [InlineData(2, false)] [InlineData(1, true)] [InlineData(2, true)] public void NonGeneric_AwaitOnCompleted_ForcesTaskCreation(int numAwaits, bool awaitUnsafe) { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); var dsm = new DelegateStateMachine(); TaskAwaiter<int> t = new TaskCompletionSource<int>().Task.GetAwaiter(); Assert.InRange(numAwaits, 1, int.MaxValue); for (int i = 1; i <= numAwaits; i++) { if (awaitUnsafe) { b.AwaitUnsafeOnCompleted(ref t, ref dsm); } else { b.AwaitOnCompleted(ref t, ref dsm); } } b.SetResult(); ValueTask vt = b.Task; Assert.NotEqual(default, vt); Assert.True(vt.IsCompletedSuccessfully); } [Theory] [InlineData(1, false)] [InlineData(2, false)] [InlineData(1, true)] [InlineData(2, true)] public void Generic_AwaitOnCompleted_ForcesTaskCreation(int numAwaits, bool awaitUnsafe) { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); var dsm = new DelegateStateMachine(); TaskAwaiter<int> t = new TaskCompletionSource<int>().Task.GetAwaiter(); Assert.InRange(numAwaits, 1, int.MaxValue); for (int i = 1; i <= numAwaits; i++) { if (awaitUnsafe) { b.AwaitUnsafeOnCompleted(ref t, ref dsm); } else { b.AwaitOnCompleted(ref t, ref dsm); } } b.SetResult(42); ValueTask<int> vt = b.Task; Assert.NotEqual(default, vt); Assert.True(vt.IsCompletedSuccessfully); Assert.Equal(42, vt.Result); } [Fact] public void NonGeneric_SetStateMachine_InvalidArgument_ThrowsException() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); AssertExtensions.Throws<ArgumentNullException>("stateMachine", () => b.SetStateMachine(null)); } [Fact] public void Generic_SetStateMachine_InvalidArgument_ThrowsException() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); AssertExtensions.Throws<ArgumentNullException>("stateMachine", () => b.SetStateMachine(null)); } [Fact] public void NonGeneric_Start_ExecutionContextChangesInMoveNextDontFlowOut() { var al = new AsyncLocal<int> { Value = 0 }; int calls = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => { al.Value++; calls++; } }; dsm.MoveNext(); Assert.Equal(1, al.Value); Assert.Equal(1, calls); dsm.MoveNext(); Assert.Equal(2, al.Value); Assert.Equal(2, calls); AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); b.Start(ref dsm); Assert.Equal(2, al.Value); // change should not be visible Assert.Equal(3, calls); // Make sure we've not caused the Task to be allocated b.SetResult(); Assert.Equal(default, b.Task); } [Fact] public void Generic_Start_ExecutionContextChangesInMoveNextDontFlowOut() { var al = new AsyncLocal<int> { Value = 0 }; int calls = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => { al.Value++; calls++; } }; dsm.MoveNext(); Assert.Equal(1, al.Value); Assert.Equal(1, calls); dsm.MoveNext(); Assert.Equal(2, al.Value); Assert.Equal(2, calls); AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); b.Start(ref dsm); Assert.Equal(2, al.Value); // change should not be visible Assert.Equal(3, calls); // Make sure we've not caused the Task to be allocated b.SetResult(42); Assert.Equal(new ValueTask<int>(42), b.Task); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(10)] public static async Task NonGeneric_UsedWithAsyncMethod_CompletesSuccessfully(int yields) { StrongBox<int> result; result = new StrongBox<int>(); await ValueTaskReturningAsyncMethod(42, result); Assert.Equal(42 + yields, result.Value); result = new StrongBox<int>(); await ValueTaskReturningAsyncMethod(84, result); Assert.Equal(84 + yields, result.Value); async ValueTask ValueTaskReturningAsyncMethod(int result, StrongBox<int> output) { for (int i = 0; i < yields; i++) { await Task.Yield(); result++; } output.Value = result; } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(10)] public static async Task Generic_UsedWithAsyncMethod_CompletesSuccessfully(int yields) { Assert.Equal(42 + yields, await ValueTaskReturningAsyncMethod(42)); Assert.Equal(84 + yields, await ValueTaskReturningAsyncMethod(84)); async ValueTask<int> ValueTaskReturningAsyncMethod(int result) { for (int i = 0; i < yields; i++) { await Task.Yield(); result++; } return result; } } [Fact] public static async Task AwaitTasksAndValueTasks_InTaskAndValueTaskMethods() { for (int i = 0; i < 2; i++) { await TaskReturningMethod(); Assert.Equal(17, await TaskInt32ReturningMethod()); await ValueTaskReturningMethod(); Assert.Equal(18, await ValueTaskInt32ReturningMethod()); } async Task TaskReturningMethod() { for (int i = 0; i < 3; i++) { // Complete await Task.CompletedTask; await Task.FromResult(42); await new ValueTask(); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(42)); Assert.Equal(42, await new ValueTask<int>(Task.FromResult(42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); // Incomplete await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.Delay(1).ContinueWith(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.Delay(1).ContinueWith<int>(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); await Task.Yield(); } } async Task<int> TaskInt32ReturningMethod() { for (int i = 0; i < 3; i++) { // Complete await Task.CompletedTask; await Task.FromResult(42); await new ValueTask(); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(42)); Assert.Equal(42, await new ValueTask<int>(Task.FromResult(42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); // Incomplete await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.Delay(1).ContinueWith(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.Delay(1).ContinueWith<int>(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); await Task.Yield(); } return 17; } async ValueTask ValueTaskReturningMethod() { for (int i = 0; i < 3; i++) { // Complete await Task.CompletedTask; await Task.FromResult(42); await new ValueTask(); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(42)); Assert.Equal(42, await new ValueTask<int>(Task.FromResult(42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); // Incomplete await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.Delay(1).ContinueWith(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.Delay(1).ContinueWith<int>(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); await Task.Yield(); } } async ValueTask<int> ValueTaskInt32ReturningMethod() { for (int i = 0; i < 3; i++) { // Complete await Task.CompletedTask; await Task.FromResult(42); await new ValueTask(); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(42)); Assert.Equal(42, await new ValueTask<int>(Task.FromResult(42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); // Incomplete await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.Delay(1).ContinueWith(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.Delay(1).ContinueWith<int>(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); await Task.Yield(); } return 18; } } [Fact] public async Task NonGeneric_ConcurrentBuilders_WorkCorrectly() { await Task.WhenAll(Enumerable.Range(0, Environment.ProcessorCount).Select(async _ => { for (int i = 0; i < 10; i++) { await ValueTaskAsync(); static async ValueTask ValueTaskAsync() { await Task.Delay(1); } } })); } [Fact] public async Task Generic_ConcurrentBuilders_WorkCorrectly() { await Task.WhenAll(Enumerable.Range(0, Environment.ProcessorCount).Select(async _ => { for (int i = 0; i < 10; i++) { Assert.Equal(42 + i, await ValueTaskAsync(i)); static async ValueTask<int> ValueTaskAsync(int i) { await Task.Delay(1); return 42 + i; } } })); } private struct DelegateStateMachine : IAsyncStateMachine { internal Action MoveNextDelegate; public void MoveNext() => MoveNextDelegate?.Invoke(); public void SetStateMachine(IAsyncStateMachine stateMachine) { } } } }
// 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.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks.Sources.Tests; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Threading.Tasks.Tests { public class AsyncValueTaskMethodBuilderTests { [Fact] public void Create_ReturnsDefaultInstance() // implementation detail being verified { Assert.Equal(default, AsyncValueTaskMethodBuilder.Create()); Assert.Equal(default, AsyncValueTaskMethodBuilder<int>.Create()); } [Fact] public void NonGeneric_SetResult_BeforeAccessTask_ValueTaskIsDefault() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); b.SetResult(); Assert.Equal(default, b.Task); } [Fact] public void Generic_SetResult_BeforeAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); b.SetResult(42); ValueTask<int> vt = b.Task; Assert.Equal(vt, b.Task); Assert.Equal(new ValueTask<int>(42), vt); } [Fact] public void NonGeneric_SetResult_AfterAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); ValueTask vt = b.Task; Assert.NotEqual(default, vt); Assert.Equal(vt, b.Task); b.SetResult(); Assert.Equal(vt, b.Task); Assert.True(vt.IsCompletedSuccessfully); } [Fact] public void Generic_SetResult_AfterAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); ValueTask<int> vt = b.Task; Assert.NotEqual(default, vt); Assert.Equal(vt, b.Task); b.SetResult(42); Assert.Equal(vt, b.Task); Assert.True(vt.IsCompletedSuccessfully); Assert.Equal(42, vt.Result); } [Fact] public void NonGeneric_SetException_BeforeAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); var e = new FormatException(); b.SetException(e); ValueTask vt = b.Task; Assert.Equal(vt, b.Task); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Generic_SetException_BeforeAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); var e = new FormatException(); b.SetException(e); ValueTask<int> vt = b.Task; Assert.Equal(vt, b.Task); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void NonGeneric_SetException_AfterAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); ValueTask vt = b.Task; Assert.Equal(vt, b.Task); var e = new FormatException(); b.SetException(e); Assert.Equal(vt, b.Task); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Generic_SetException_AfterAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); ValueTask<int> vt = b.Task; Assert.Equal(vt, b.Task); var e = new FormatException(); b.SetException(e); Assert.Equal(vt, b.Task); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void NonGeneric_SetException_OperationCanceledException_CancelsTask() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); ValueTask vt = b.Task; Assert.Equal(vt, b.Task); var e = new OperationCanceledException(); b.SetException(e); Assert.Equal(vt, b.Task); Assert.True(vt.IsCanceled); Assert.Same(e, Assert.Throws<OperationCanceledException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Generic_SetException_OperationCanceledException_CancelsTask() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); ValueTask<int> vt = b.Task; Assert.Equal(vt, b.Task); var e = new OperationCanceledException(); b.SetException(e); Assert.Equal(vt, b.Task); Assert.True(vt.IsCanceled); Assert.Same(e, Assert.Throws<OperationCanceledException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void NonGeneric_SetExceptionWithNullException_Throws() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); AssertExtensions.Throws<ArgumentNullException>("exception", () => b.SetException(null)); } [Fact] public void Generic_SetExceptionWithNullException_Throws() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); AssertExtensions.Throws<ArgumentNullException>("exception", () => b.SetException(null)); } [Fact] public void NonGeneric_Start_InvokesMoveNext() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); int invokes = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => invokes++ }; b.Start(ref dsm); Assert.Equal(1, invokes); } [Fact] public void Generic_Start_InvokesMoveNext() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); int invokes = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => invokes++ }; b.Start(ref dsm); Assert.Equal(1, invokes); } [Theory] [InlineData(1, false)] [InlineData(2, false)] [InlineData(1, true)] [InlineData(2, true)] public void NonGeneric_AwaitOnCompleted_ForcesTaskCreation(int numAwaits, bool awaitUnsafe) { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); var dsm = new DelegateStateMachine(); TaskAwaiter<int> t = new TaskCompletionSource<int>().Task.GetAwaiter(); Assert.InRange(numAwaits, 1, int.MaxValue); for (int i = 1; i <= numAwaits; i++) { if (awaitUnsafe) { b.AwaitUnsafeOnCompleted(ref t, ref dsm); } else { b.AwaitOnCompleted(ref t, ref dsm); } } b.SetResult(); ValueTask vt = b.Task; Assert.NotEqual(default, vt); Assert.True(vt.IsCompletedSuccessfully); } [Theory] [InlineData(1, false)] [InlineData(2, false)] [InlineData(1, true)] [InlineData(2, true)] public void Generic_AwaitOnCompleted_ForcesTaskCreation(int numAwaits, bool awaitUnsafe) { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); var dsm = new DelegateStateMachine(); TaskAwaiter<int> t = new TaskCompletionSource<int>().Task.GetAwaiter(); Assert.InRange(numAwaits, 1, int.MaxValue); for (int i = 1; i <= numAwaits; i++) { if (awaitUnsafe) { b.AwaitUnsafeOnCompleted(ref t, ref dsm); } else { b.AwaitOnCompleted(ref t, ref dsm); } } b.SetResult(42); ValueTask<int> vt = b.Task; Assert.NotEqual(default, vt); Assert.True(vt.IsCompletedSuccessfully); Assert.Equal(42, vt.Result); } [Fact] public void NonGeneric_SetStateMachine_InvalidArgument_ThrowsException() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); AssertExtensions.Throws<ArgumentNullException>("stateMachine", () => b.SetStateMachine(null)); } [Fact] public void Generic_SetStateMachine_InvalidArgument_ThrowsException() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); AssertExtensions.Throws<ArgumentNullException>("stateMachine", () => b.SetStateMachine(null)); } [Fact] public void NonGeneric_Start_ExecutionContextChangesInMoveNextDontFlowOut() { var al = new AsyncLocal<int> { Value = 0 }; int calls = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => { al.Value++; calls++; } }; dsm.MoveNext(); Assert.Equal(1, al.Value); Assert.Equal(1, calls); dsm.MoveNext(); Assert.Equal(2, al.Value); Assert.Equal(2, calls); AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); b.Start(ref dsm); Assert.Equal(2, al.Value); // change should not be visible Assert.Equal(3, calls); // Make sure we've not caused the Task to be allocated b.SetResult(); Assert.Equal(default, b.Task); } [Fact] public void Generic_Start_ExecutionContextChangesInMoveNextDontFlowOut() { var al = new AsyncLocal<int> { Value = 0 }; int calls = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => { al.Value++; calls++; } }; dsm.MoveNext(); Assert.Equal(1, al.Value); Assert.Equal(1, calls); dsm.MoveNext(); Assert.Equal(2, al.Value); Assert.Equal(2, calls); AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); b.Start(ref dsm); Assert.Equal(2, al.Value); // change should not be visible Assert.Equal(3, calls); // Make sure we've not caused the Task to be allocated b.SetResult(42); Assert.Equal(new ValueTask<int>(42), b.Task); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(10)] public static async Task NonGeneric_UsedWithAsyncMethod_CompletesSuccessfully(int yields) { StrongBox<int> result; result = new StrongBox<int>(); await ValueTaskReturningAsyncMethod(42, result); Assert.Equal(42 + yields, result.Value); result = new StrongBox<int>(); await ValueTaskReturningAsyncMethod(84, result); Assert.Equal(84 + yields, result.Value); async ValueTask ValueTaskReturningAsyncMethod(int result, StrongBox<int> output) { for (int i = 0; i < yields; i++) { await Task.Yield(); result++; } output.Value = result; } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(10)] public static async Task Generic_UsedWithAsyncMethod_CompletesSuccessfully(int yields) { Assert.Equal(42 + yields, await ValueTaskReturningAsyncMethod(42)); Assert.Equal(84 + yields, await ValueTaskReturningAsyncMethod(84)); async ValueTask<int> ValueTaskReturningAsyncMethod(int result) { for (int i = 0; i < yields; i++) { await Task.Yield(); result++; } return result; } } [Fact] public static async Task AwaitTasksAndValueTasks_InTaskAndValueTaskMethods() { for (int i = 0; i < 2; i++) { await TaskReturningMethod(); Assert.Equal(17, await TaskInt32ReturningMethod()); await ValueTaskReturningMethod(); Assert.Equal(18, await ValueTaskInt32ReturningMethod()); } async Task TaskReturningMethod() { for (int i = 0; i < 3; i++) { // Complete await Task.CompletedTask; await Task.FromResult(42); await new ValueTask(); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(42)); Assert.Equal(42, await new ValueTask<int>(Task.FromResult(42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); // Incomplete await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.Delay(1).ContinueWith(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.Delay(1).ContinueWith<int>(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); await Task.Yield(); } } async Task<int> TaskInt32ReturningMethod() { for (int i = 0; i < 3; i++) { // Complete await Task.CompletedTask; await Task.FromResult(42); await new ValueTask(); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(42)); Assert.Equal(42, await new ValueTask<int>(Task.FromResult(42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); // Incomplete await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.Delay(1).ContinueWith(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.Delay(1).ContinueWith<int>(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); await Task.Yield(); } return 17; } async ValueTask ValueTaskReturningMethod() { for (int i = 0; i < 3; i++) { // Complete await Task.CompletedTask; await Task.FromResult(42); await new ValueTask(); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(42)); Assert.Equal(42, await new ValueTask<int>(Task.FromResult(42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); // Incomplete await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.Delay(1).ContinueWith(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.Delay(1).ContinueWith<int>(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); await Task.Yield(); } } async ValueTask<int> ValueTaskInt32ReturningMethod() { for (int i = 0; i < 3; i++) { // Complete await Task.CompletedTask; await Task.FromResult(42); await new ValueTask(); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(42)); Assert.Equal(42, await new ValueTask<int>(Task.FromResult(42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); // Incomplete await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.Delay(1).ContinueWith(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.Delay(1).ContinueWith<int>(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); await Task.Yield(); } return 18; } } [Fact] public async Task NonGeneric_ConcurrentBuilders_WorkCorrectly() { await Task.WhenAll(Enumerable.Range(0, Environment.ProcessorCount).Select(async _ => { for (int i = 0; i < 10; i++) { await ValueTaskAsync(); static async ValueTask ValueTaskAsync() { await Task.Delay(1); } } })); } [Fact] public async Task Generic_ConcurrentBuilders_WorkCorrectly() { await Task.WhenAll(Enumerable.Range(0, Environment.ProcessorCount).Select(async _ => { for (int i = 0; i < 10; i++) { Assert.Equal(42 + i, await ValueTaskAsync(i)); static async ValueTask<int> ValueTaskAsync(int i) { await Task.Delay(1); return 42 + i; } } })); } private struct DelegateStateMachine : IAsyncStateMachine { internal Action MoveNextDelegate; public void MoveNext() => MoveNextDelegate?.Invoke(); public void SetStateMachine(IAsyncStateMachine stateMachine) { } } } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Net.Http.WinHttpHandler/tests/FunctionalTests/System.Net.Http.WinHttpHandler.Functional.Tests.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>$(NetCoreAppCurrent)-windows;net48</TargetFrameworks> <IncludeRemoteExecutor>true</IncludeRemoteExecutor> <DefineConstants>$(DefineConstants);WINHTTPHANDLER_TEST</DefineConstants> <LangVersion>10.0</LangVersion> </PropertyGroup> <ItemGroup> <Compile Include="$(CommonTestPath)System\Net\Configuration.cs" Link="Common\System\Net\Configuration.cs" /> <Compile Include="$(CommonTestPath)System\Net\Configuration.Http.cs" Link="Common\System\Net\Configuration.Http.cs" /> <Compile Include="AssemblyInfo.cs" /> <Compile Include="BaseCertificateTest.cs" /> <Compile Include="ServerCertificateTest.cs" /> <Compile Include="WinHttpHandlerTest.cs" /> <Compile Include="XunitTestAssemblyAtrributes.cs" /> <Compile Include="$(CommonPath)\System\Net\Http\HttpHandlerDefaults.cs" Link="Common\System\Net\Http\HttpHandlerDefaults.cs" /> <Compile Include="$(CommonTestPath)System\IO\DelegateStream.cs" Link="Common\System\IO\DelegateStream.cs" /> <Compile Include="$(CommonTestPath)System\Net\Configuration.Certificates.cs" Link="Common\System\Net\Configuration.Certificates.cs" /> <Compile Include="$(CommonTestPath)System\Net\Configuration.Security.cs" Link="Common\System\Net\Configuration.Security.cs" /> <Compile Include="$(CommonTestPath)System\Net\Configuration.Sockets.cs" Link="Common\System\Net\Configuration.Sockets.cs" /> <Compile Include="$(CommonTestPath)System\Net\Capability.Security.cs" Link="Common\System\Net\Capability.Security.cs" /> <Compile Include="$(CommonTestPath)System\Net\Capability.Security.Windows.cs" Link="Common\System\Net\Capability.Security.Windows.cs" /> <Compile Include="$(CommonTestPath)System\Net\EventSourceTestLogging.cs" Link="Common\System\Net\EventSourceTestLogging.cs" /> <Compile Include="$(CommonTestPath)System\Net\HttpsTestServer.cs" Link="Common\System\Net\HttpsTestServer.cs" /> <Compile Include="$(CommonTestPath)System\Net\RemoteServerQuery.cs" Link="Common\System\Net\RemoteServerQuery.cs" /> <Compile Include="$(CommonTestPath)System\Net\VerboseTestLogging.cs" Link="Common\System\Net\VerboseTestLogging.cs" /> <Compile Include="$(CommonTestPath)System\Net\TestWebProxies.cs" Link="Common\System\Net\TestWebProxies.cs" /> <Compile Include="$(CommonTestPath)System\Net\StreamArrayExtensions.cs" Link="Common\System\Net\StreamArrayExtensions.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\ByteAtATimeContent.cs" Link="Common\System\Net\Http\ByteAtATimeContent.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\ChannelBindingAwareContent.cs" Link="Common\System\Net\Http\ChannelBindingAwareContent.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\CustomContent.cs" Link="Common\System\Net\Http\CustomContent.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\DefaultCredentialsTest.cs" Link="Common\System\Net\Http\DefaultCredentialsTest.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\DribbleStream.cs" Link="Common\System\Net\Http\DribbleStream.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\GenericLoopbackServer.cs" Link="Common\System\Net\Http\GenericLoopbackServer.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTestBase.cs" Link="Common\System\Net\Http\HttpClientHandlerTestBase.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\Http2Frames.cs" Link="Common\System\Net\Http\Http2Frames.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HPackEncoder.cs" Link="Common\System\Net\Http\HPackEncoder.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\Http2LoopbackServer.cs" Link="Common\System\Net\Http\Http2LoopbackServer.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\Http2LoopbackConnection.cs" Link="Common\System\Net\Http\Http2LoopbackConnection.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\QPackTestDecoder.cs" Link="Common\System\Net\Http\QPackTestDecoder.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\QPackTestEncoder.cs" Link="Common\System\Net\Http\QPackTestEncoder.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HuffmanDecoder.cs" Link="Common\System\Net\Http\HuffmanDecoder.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HuffmanEncoder.cs" Link="Common\System\Net\Http\HuffmanEncoder.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.AcceptAllCerts.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.AcceptAllCerts.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.Asynchrony.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.Asynchrony.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.Authentication.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.Authentication.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.AutoRedirect.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.AutoRedirect.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.Cancellation.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.Cancellation.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.ClientCertificates.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.ClientCertificates.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.Cookies.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.Cookies.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.Decompression.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.Decompression.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.DefaultProxyCredentials.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.DefaultProxyCredentials.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.MaxConnectionsPerServer.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.MaxConnectionsPerServer.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.MaxResponseHeadersLength.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.MaxResponseHeadersLength.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.Proxy.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.Proxy.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.RemoteServer.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.RemoteServer.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.ServerCertificates.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.ServerCertificates.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.SslProtocols.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.SslProtocols.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpProtocolTests.cs" Link="Common\System\Net\Http\HttpProtocolTests.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClient.SelectedSitesTest.cs" Link="Common\System\Net\Http\HttpClient.SelectedSitesTest.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientEKUTest.cs" Link="Common\System\Net\Http\HttpClientEKUTest.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\IdnaProtocolTests.cs" Link="Common\System\Net\Http\IdnaProtocolTests.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\LoopbackProxyServer.cs" Link="Common\System\Net\Http\LoopbackProxyServer.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\LoopbackServer.cs" Link="Common\System\Net\Http\LoopbackServer.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\LoopbackServer.AuthenticationHelpers.cs" Link="Common\System\Net\Http\LoopbackServer.AuthenticationHelpers.cs" /> <Compile Include="$(CommonTestPath)System\Net\SslProtocolSupport.cs" Link="Common\System\Net\SslProtocolSupport.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\TestHelper.cs" Link="Common\System\Net\Http\TestHelper.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\PostScenarioTest.cs" Link="Common\System\Net\Http\PostScenarioTest.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\RepeatedFlushContent.cs" Link="Common\System\Net\Http\RepeatedFlushContent.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\ResponseStreamTest.cs" Link="Common\System\Net\Http\ResponseStreamTest.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\SyncBlockingContent.cs" Link="Common\System\Net\Http\SyncBlockingContent.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\ThrowingContent.cs" Link="Common\System\Net\Http\ThrowingContent.cs" /> <Compile Include="$(CommonTestPath)System\Security\Cryptography\PlatformSupport.cs" Link="CommonTest\System\Security\Cryptography\PlatformSupport.cs" /> <Compile Include="$(CommonTestPath)System\Threading\Tasks\TaskTimeoutExtensions.cs" Link="Common\System\Threading\Tasks\TaskTimeoutExtensions.cs" /> <Compile Include="$(CommonTestPath)System\Threading\TrackingSynchronizationContext.cs" Link="Common\System\Threading\TrackingSynchronizationContext.cs" /> <Compile Include="HttpClientHandlerTestBase.WinHttpHandler.cs" /> <Compile Include="WinHttpClientHandler.cs" /> <Compile Include="PlatformHandlerTest.cs" /> <Compile Include="ClientCertificateTest.cs" /> <Compile Include="TrailingHeadersTest.cs" /> <Compile Include="BidirectionStreamingTest.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> <PackageReference Include="System.Net.TestData" Version="$(SystemNetTestDataVersion)" /> <ProjectReference Include="..\..\src\System.Net.Http.WinHttpHandler.csproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'"> <ProjectReference Include="$(LibrariesProjectRoot)System.DirectoryServices.Protocols\src\System.DirectoryServices.Protocols.csproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'"> <Reference Include="System.DirectoryServices.Protocols" /> <Reference Include="System.Net.Http" /> <ProjectReference Include="$(LibrariesProjectRoot)System.Net.Http.Json\src\System.Net.Http.Json.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>$(NetCoreAppCurrent)-windows;net48</TargetFrameworks> <IncludeRemoteExecutor>true</IncludeRemoteExecutor> <DefineConstants>$(DefineConstants);WINHTTPHANDLER_TEST</DefineConstants> <LangVersion>10.0</LangVersion> </PropertyGroup> <ItemGroup> <Compile Include="$(CommonTestPath)System\Net\Configuration.cs" Link="Common\System\Net\Configuration.cs" /> <Compile Include="$(CommonTestPath)System\Net\Configuration.Http.cs" Link="Common\System\Net\Configuration.Http.cs" /> <Compile Include="AssemblyInfo.cs" /> <Compile Include="BaseCertificateTest.cs" /> <Compile Include="ServerCertificateTest.cs" /> <Compile Include="WinHttpHandlerTest.cs" /> <Compile Include="XunitTestAssemblyAtrributes.cs" /> <Compile Include="$(CommonPath)\System\Net\Http\HttpHandlerDefaults.cs" Link="Common\System\Net\Http\HttpHandlerDefaults.cs" /> <Compile Include="$(CommonTestPath)System\IO\DelegateStream.cs" Link="Common\System\IO\DelegateStream.cs" /> <Compile Include="$(CommonTestPath)System\Net\Configuration.Certificates.cs" Link="Common\System\Net\Configuration.Certificates.cs" /> <Compile Include="$(CommonTestPath)System\Net\Configuration.Security.cs" Link="Common\System\Net\Configuration.Security.cs" /> <Compile Include="$(CommonTestPath)System\Net\Configuration.Sockets.cs" Link="Common\System\Net\Configuration.Sockets.cs" /> <Compile Include="$(CommonTestPath)System\Net\Capability.Security.cs" Link="Common\System\Net\Capability.Security.cs" /> <Compile Include="$(CommonTestPath)System\Net\Capability.Security.Windows.cs" Link="Common\System\Net\Capability.Security.Windows.cs" /> <Compile Include="$(CommonTestPath)System\Net\EventSourceTestLogging.cs" Link="Common\System\Net\EventSourceTestLogging.cs" /> <Compile Include="$(CommonTestPath)System\Net\HttpsTestServer.cs" Link="Common\System\Net\HttpsTestServer.cs" /> <Compile Include="$(CommonTestPath)System\Net\RemoteServerQuery.cs" Link="Common\System\Net\RemoteServerQuery.cs" /> <Compile Include="$(CommonTestPath)System\Net\VerboseTestLogging.cs" Link="Common\System\Net\VerboseTestLogging.cs" /> <Compile Include="$(CommonTestPath)System\Net\TestWebProxies.cs" Link="Common\System\Net\TestWebProxies.cs" /> <Compile Include="$(CommonTestPath)System\Net\StreamArrayExtensions.cs" Link="Common\System\Net\StreamArrayExtensions.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\ByteAtATimeContent.cs" Link="Common\System\Net\Http\ByteAtATimeContent.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\ChannelBindingAwareContent.cs" Link="Common\System\Net\Http\ChannelBindingAwareContent.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\CustomContent.cs" Link="Common\System\Net\Http\CustomContent.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\DefaultCredentialsTest.cs" Link="Common\System\Net\Http\DefaultCredentialsTest.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\DribbleStream.cs" Link="Common\System\Net\Http\DribbleStream.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\GenericLoopbackServer.cs" Link="Common\System\Net\Http\GenericLoopbackServer.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTestBase.cs" Link="Common\System\Net\Http\HttpClientHandlerTestBase.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\Http2Frames.cs" Link="Common\System\Net\Http\Http2Frames.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HPackEncoder.cs" Link="Common\System\Net\Http\HPackEncoder.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\Http2LoopbackServer.cs" Link="Common\System\Net\Http\Http2LoopbackServer.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\Http2LoopbackConnection.cs" Link="Common\System\Net\Http\Http2LoopbackConnection.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\QPackTestDecoder.cs" Link="Common\System\Net\Http\QPackTestDecoder.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\QPackTestEncoder.cs" Link="Common\System\Net\Http\QPackTestEncoder.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HuffmanDecoder.cs" Link="Common\System\Net\Http\HuffmanDecoder.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HuffmanEncoder.cs" Link="Common\System\Net\Http\HuffmanEncoder.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.AcceptAllCerts.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.AcceptAllCerts.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.Asynchrony.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.Asynchrony.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.Authentication.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.Authentication.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.AutoRedirect.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.AutoRedirect.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.Cancellation.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.Cancellation.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.ClientCertificates.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.ClientCertificates.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.Cookies.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.Cookies.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.Decompression.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.Decompression.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.DefaultProxyCredentials.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.DefaultProxyCredentials.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.MaxConnectionsPerServer.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.MaxConnectionsPerServer.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.MaxResponseHeadersLength.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.MaxResponseHeadersLength.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.Proxy.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.Proxy.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.RemoteServer.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.RemoteServer.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.ServerCertificates.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.ServerCertificates.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientHandlerTest.SslProtocols.cs" Link="Common\System\Net\Http\HttpClientHandlerTest.SslProtocols.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpProtocolTests.cs" Link="Common\System\Net\Http\HttpProtocolTests.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClient.SelectedSitesTest.cs" Link="Common\System\Net\Http\HttpClient.SelectedSitesTest.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\HttpClientEKUTest.cs" Link="Common\System\Net\Http\HttpClientEKUTest.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\IdnaProtocolTests.cs" Link="Common\System\Net\Http\IdnaProtocolTests.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\LoopbackProxyServer.cs" Link="Common\System\Net\Http\LoopbackProxyServer.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\LoopbackServer.cs" Link="Common\System\Net\Http\LoopbackServer.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\LoopbackServer.AuthenticationHelpers.cs" Link="Common\System\Net\Http\LoopbackServer.AuthenticationHelpers.cs" /> <Compile Include="$(CommonTestPath)System\Net\SslProtocolSupport.cs" Link="Common\System\Net\SslProtocolSupport.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\TestHelper.cs" Link="Common\System\Net\Http\TestHelper.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\PostScenarioTest.cs" Link="Common\System\Net\Http\PostScenarioTest.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\RepeatedFlushContent.cs" Link="Common\System\Net\Http\RepeatedFlushContent.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\ResponseStreamTest.cs" Link="Common\System\Net\Http\ResponseStreamTest.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\SyncBlockingContent.cs" Link="Common\System\Net\Http\SyncBlockingContent.cs" /> <Compile Include="$(CommonTestPath)System\Net\Http\ThrowingContent.cs" Link="Common\System\Net\Http\ThrowingContent.cs" /> <Compile Include="$(CommonTestPath)System\Security\Cryptography\PlatformSupport.cs" Link="CommonTest\System\Security\Cryptography\PlatformSupport.cs" /> <Compile Include="$(CommonTestPath)System\Threading\Tasks\TaskTimeoutExtensions.cs" Link="Common\System\Threading\Tasks\TaskTimeoutExtensions.cs" /> <Compile Include="$(CommonTestPath)System\Threading\TrackingSynchronizationContext.cs" Link="Common\System\Threading\TrackingSynchronizationContext.cs" /> <Compile Include="HttpClientHandlerTestBase.WinHttpHandler.cs" /> <Compile Include="WinHttpClientHandler.cs" /> <Compile Include="PlatformHandlerTest.cs" /> <Compile Include="ClientCertificateTest.cs" /> <Compile Include="TrailingHeadersTest.cs" /> <Compile Include="BidirectionStreamingTest.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> <PackageReference Include="System.Net.TestData" Version="$(SystemNetTestDataVersion)" /> <ProjectReference Include="..\..\src\System.Net.Http.WinHttpHandler.csproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'"> <ProjectReference Include="$(LibrariesProjectRoot)System.DirectoryServices.Protocols\src\System.DirectoryServices.Protocols.csproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'"> <Reference Include="System.DirectoryServices.Protocols" /> <Reference Include="System.Net.Http" /> <ProjectReference Include="$(LibrariesProjectRoot)System.Net.Http.Json\src\System.Net.Http.Json.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/tests/JIT/HardwareIntrinsics/General/Vector256/CreateScalarUnsafe.SByte.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 CreateScalarUnsafeSByte() { var test = new VectorCreate__CreateScalarUnsafeSByte(); // Validates basic functionality works test.RunBasicScenario(); // 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 VectorCreate__CreateScalarUnsafeSByte { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); SByte value = TestLibrary.Generator.GetSByte(); Vector256<SByte> result = Vector256.CreateScalarUnsafe(value); ValidateResult(result, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); SByte value = TestLibrary.Generator.GetSByte(); object result = typeof(Vector256) .GetMethod(nameof(Vector256.CreateScalarUnsafe), new Type[] { typeof(SByte) }) .Invoke(null, new object[] { value }); ValidateResult((Vector256<SByte>)(result), value); } private void ValidateResult(Vector256<SByte> result, SByte expectedValue, [CallerMemberName] string method = "") { SByte[] resultElements = new SByte[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref resultElements[0]), result); ValidateResult(resultElements, expectedValue, method); } private void ValidateResult(SByte[] resultElements, SByte expectedValue, [CallerMemberName] string method = "") { bool succeeded = true; if (resultElements[0] != expectedValue) { succeeded = false; } else { for (var i = 1; i < ElementCount; i++) { if (false /* value is uninitialized */) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256.CreateScalarUnsafe(SByte): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: {expectedValue}"); 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 CreateScalarUnsafeSByte() { var test = new VectorCreate__CreateScalarUnsafeSByte(); // Validates basic functionality works test.RunBasicScenario(); // 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 VectorCreate__CreateScalarUnsafeSByte { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); SByte value = TestLibrary.Generator.GetSByte(); Vector256<SByte> result = Vector256.CreateScalarUnsafe(value); ValidateResult(result, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); SByte value = TestLibrary.Generator.GetSByte(); object result = typeof(Vector256) .GetMethod(nameof(Vector256.CreateScalarUnsafe), new Type[] { typeof(SByte) }) .Invoke(null, new object[] { value }); ValidateResult((Vector256<SByte>)(result), value); } private void ValidateResult(Vector256<SByte> result, SByte expectedValue, [CallerMemberName] string method = "") { SByte[] resultElements = new SByte[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref resultElements[0]), result); ValidateResult(resultElements, expectedValue, method); } private void ValidateResult(SByte[] resultElements, SByte expectedValue, [CallerMemberName] string method = "") { bool succeeded = true; if (resultElements[0] != expectedValue) { succeeded = false; } else { for (var i = 1; i < ElementCount; i++) { if (false /* value is uninitialized */) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256.CreateScalarUnsafe(SByte): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: {expectedValue}"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/And.Vector64.Byte.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 And_Vector64_Byte() { var test = new SimpleBinaryOpTest__And_Vector64_Byte(); 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__And_Vector64_Byte { 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(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); 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<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, 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 Vector64<Byte> _fld1; public Vector64<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__And_Vector64_Byte testClass) { var result = AdvSimd.And(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__And_Vector64_Byte testClass) { fixed (Vector64<Byte>* pFld1 = &_fld1) fixed (Vector64<Byte>* pFld2 = &_fld2) { var result = AdvSimd.And( AdvSimd.LoadVector64((Byte*)(pFld1)), AdvSimd.LoadVector64((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector64<Byte> _clsVar1; private static Vector64<Byte> _clsVar2; private Vector64<Byte> _fld1; private Vector64<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__And_Vector64_Byte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); } public SimpleBinaryOpTest__And_Vector64_Byte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[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.And( Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Byte>>(_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.And( AdvSimd.LoadVector64((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Byte*)(_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).GetMethod(nameof(AdvSimd.And), new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.And), new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.And( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Byte>* pClsVar1 = &_clsVar1) fixed (Vector64<Byte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.And( AdvSimd.LoadVector64((Byte*)(pClsVar1)), AdvSimd.LoadVector64((Byte*)(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<Vector64<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr); var result = AdvSimd.And(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.LoadVector64((Byte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Byte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__And_Vector64_Byte(); var result = AdvSimd.And(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__And_Vector64_Byte(); fixed (Vector64<Byte>* pFld1 = &test._fld1) fixed (Vector64<Byte>* pFld2 = &test._fld2) { var result = AdvSimd.And( AdvSimd.LoadVector64((Byte*)(pFld1)), AdvSimd.LoadVector64((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.And(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Byte>* pFld1 = &_fld1) fixed (Vector64<Byte>* pFld2 = &_fld2) { var result = AdvSimd.And( AdvSimd.LoadVector64((Byte*)(pFld1)), AdvSimd.LoadVector64((Byte*)(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.And(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.And( AdvSimd.LoadVector64((Byte*)(&test._fld1)), AdvSimd.LoadVector64((Byte*)(&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(Vector64<Byte> op1, Vector64<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.And(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.And)}<Byte>(Vector64<Byte>, Vector64<Byte>): {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 And_Vector64_Byte() { var test = new SimpleBinaryOpTest__And_Vector64_Byte(); 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__And_Vector64_Byte { 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(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); 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<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, 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 Vector64<Byte> _fld1; public Vector64<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__And_Vector64_Byte testClass) { var result = AdvSimd.And(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__And_Vector64_Byte testClass) { fixed (Vector64<Byte>* pFld1 = &_fld1) fixed (Vector64<Byte>* pFld2 = &_fld2) { var result = AdvSimd.And( AdvSimd.LoadVector64((Byte*)(pFld1)), AdvSimd.LoadVector64((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector64<Byte> _clsVar1; private static Vector64<Byte> _clsVar2; private Vector64<Byte> _fld1; private Vector64<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__And_Vector64_Byte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); } public SimpleBinaryOpTest__And_Vector64_Byte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[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.And( Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Byte>>(_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.And( AdvSimd.LoadVector64((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Byte*)(_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).GetMethod(nameof(AdvSimd.And), new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.And), new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.And( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Byte>* pClsVar1 = &_clsVar1) fixed (Vector64<Byte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.And( AdvSimd.LoadVector64((Byte*)(pClsVar1)), AdvSimd.LoadVector64((Byte*)(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<Vector64<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr); var result = AdvSimd.And(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.LoadVector64((Byte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Byte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__And_Vector64_Byte(); var result = AdvSimd.And(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__And_Vector64_Byte(); fixed (Vector64<Byte>* pFld1 = &test._fld1) fixed (Vector64<Byte>* pFld2 = &test._fld2) { var result = AdvSimd.And( AdvSimd.LoadVector64((Byte*)(pFld1)), AdvSimd.LoadVector64((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.And(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Byte>* pFld1 = &_fld1) fixed (Vector64<Byte>* pFld2 = &_fld2) { var result = AdvSimd.And( AdvSimd.LoadVector64((Byte*)(pFld1)), AdvSimd.LoadVector64((Byte*)(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.And(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.And( AdvSimd.LoadVector64((Byte*)(&test._fld1)), AdvSimd.LoadVector64((Byte*)(&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(Vector64<Byte> op1, Vector64<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.And(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.And)}<Byte>(Vector64<Byte>, Vector64<Byte>): {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,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/OptionalFields.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.InteropServices; using Internal.NativeFormat; namespace Internal.Runtime.TypeLoader { internal unsafe class OptionalFieldsRuntimeBuilder { private struct OptionalField { internal bool m_fPresent; internal uint m_uiValue; } internal OptionalFieldsRuntimeBuilder(byte* pInitializeFromOptionalFields = null) { if (pInitializeFromOptionalFields == null) return; bool isLastField = false; while (!isLastField) { byte fieldHeader = NativePrimitiveDecoder.ReadUInt8(ref pInitializeFromOptionalFields); isLastField = (fieldHeader & 0x80) != 0; EETypeOptionalFieldTag eCurrentTag = (EETypeOptionalFieldTag)(fieldHeader & 0x7f); uint uiCurrentValue = NativePrimitiveDecoder.DecodeUnsigned(ref pInitializeFromOptionalFields); _rgFields[(int)eCurrentTag].m_fPresent = true; _rgFields[(int)eCurrentTag].m_uiValue = uiCurrentValue; } } internal uint GetFieldValue(EETypeOptionalFieldTag eTag, uint defaultValueIfNotFound) { return _rgFields[(int)eTag].m_fPresent ? _rgFields[(int)eTag].m_uiValue : defaultValueIfNotFound; } internal void SetFieldValue(EETypeOptionalFieldTag eTag, uint value) { _rgFields[(int)eTag].m_fPresent = true; _rgFields[(int)eTag].m_uiValue = value; } internal void ClearField(EETypeOptionalFieldTag eTag) { _rgFields[(int)eTag].m_fPresent = false; } internal int Encode() { EETypeOptionalFieldTag eLastTag = EETypeOptionalFieldTag.Count; for (EETypeOptionalFieldTag eTag = 0; eTag < EETypeOptionalFieldTag.Count; eTag++) eLastTag = _rgFields[(int)eTag].m_fPresent ? eTag : eLastTag; if (eLastTag == EETypeOptionalFieldTag.Count) return 0; _encoder = new NativePrimitiveEncoder(); _encoder.Init(); for (EETypeOptionalFieldTag eTag = 0; eTag < EETypeOptionalFieldTag.Count; eTag++) { if (!_rgFields[(int)eTag].m_fPresent) continue; _encoder.WriteByte((byte)((byte)eTag | (eTag == eLastTag ? 0x80 : 0))); _encoder.WriteUnsigned(_rgFields[(int)eTag].m_uiValue); } return _encoder.Size; } internal void WriteToEEType(MethodTable* pEEType, int sizeOfOptionalFieldsDataInEEType) { byte* pOptionalFieldsPtr = pEEType->OptionalFieldsPtr; _encoder.Save(pOptionalFieldsPtr, sizeOfOptionalFieldsDataInEEType); } private NativePrimitiveEncoder _encoder; private OptionalField[] _rgFields = new OptionalField[(int)EETypeOptionalFieldTag.Count]; } }
// 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.InteropServices; using Internal.NativeFormat; namespace Internal.Runtime.TypeLoader { internal unsafe class OptionalFieldsRuntimeBuilder { private struct OptionalField { internal bool m_fPresent; internal uint m_uiValue; } internal OptionalFieldsRuntimeBuilder(byte* pInitializeFromOptionalFields = null) { if (pInitializeFromOptionalFields == null) return; bool isLastField = false; while (!isLastField) { byte fieldHeader = NativePrimitiveDecoder.ReadUInt8(ref pInitializeFromOptionalFields); isLastField = (fieldHeader & 0x80) != 0; EETypeOptionalFieldTag eCurrentTag = (EETypeOptionalFieldTag)(fieldHeader & 0x7f); uint uiCurrentValue = NativePrimitiveDecoder.DecodeUnsigned(ref pInitializeFromOptionalFields); _rgFields[(int)eCurrentTag].m_fPresent = true; _rgFields[(int)eCurrentTag].m_uiValue = uiCurrentValue; } } internal uint GetFieldValue(EETypeOptionalFieldTag eTag, uint defaultValueIfNotFound) { return _rgFields[(int)eTag].m_fPresent ? _rgFields[(int)eTag].m_uiValue : defaultValueIfNotFound; } internal void SetFieldValue(EETypeOptionalFieldTag eTag, uint value) { _rgFields[(int)eTag].m_fPresent = true; _rgFields[(int)eTag].m_uiValue = value; } internal void ClearField(EETypeOptionalFieldTag eTag) { _rgFields[(int)eTag].m_fPresent = false; } internal int Encode() { EETypeOptionalFieldTag eLastTag = EETypeOptionalFieldTag.Count; for (EETypeOptionalFieldTag eTag = 0; eTag < EETypeOptionalFieldTag.Count; eTag++) eLastTag = _rgFields[(int)eTag].m_fPresent ? eTag : eLastTag; if (eLastTag == EETypeOptionalFieldTag.Count) return 0; _encoder = new NativePrimitiveEncoder(); _encoder.Init(); for (EETypeOptionalFieldTag eTag = 0; eTag < EETypeOptionalFieldTag.Count; eTag++) { if (!_rgFields[(int)eTag].m_fPresent) continue; _encoder.WriteByte((byte)((byte)eTag | (eTag == eLastTag ? 0x80 : 0))); _encoder.WriteUnsigned(_rgFields[(int)eTag].m_uiValue); } return _encoder.Size; } internal void WriteToEEType(MethodTable* pEEType, int sizeOfOptionalFieldsDataInEEType) { byte* pOptionalFieldsPtr = pEEType->OptionalFieldsPtr; _encoder.Save(pOptionalFieldsPtr, sizeOfOptionalFieldsDataInEEType); } private NativePrimitiveEncoder _encoder; private OptionalField[] _rgFields = new OptionalField[(int)EETypeOptionalFieldTag.Count]; } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltApi/MyObject_Overloads.xsl
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:myObj="urn:my-object"> <xsl:template match="/"> <result> Overloaded Double: <xsl:value-of select="myObj:OverloadType(1234.012)"/> Overloaded Int: <xsl:value-of select="myObj:OverloadType(1234)"/> Overloaded String: <xsl:value-of select="myObj:OverloadType('This is a test')"/> </result> </xsl:template> </xsl:stylesheet>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:myObj="urn:my-object"> <xsl:template match="/"> <result> Overloaded Double: <xsl:value-of select="myObj:OverloadType(1234.012)"/> Overloaded Int: <xsl:value-of select="myObj:OverloadType(1234)"/> Overloaded String: <xsl:value-of select="myObj:OverloadType('This is a test')"/> </result> </xsl:template> </xsl:stylesheet>
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/coreclr/System.Private.CoreLib/src/System/Reflection/AssemblyName.CoreCLR.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.Configuration.Assemblies; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace System.Reflection { public sealed partial class AssemblyName : ICloneable, IDeserializationCallback, ISerializable { internal AssemblyName(string? name, byte[]? publicKey, byte[]? publicKeyToken, Version? version, CultureInfo? cultureInfo, AssemblyHashAlgorithm hashAlgorithm, AssemblyVersionCompatibility versionCompatibility, string? codeBase, AssemblyNameFlags flags) { _name = name; _publicKey = publicKey; _publicKeyToken = publicKeyToken; _version = version; _cultureInfo = cultureInfo; _hashAlgorithm = hashAlgorithm; _versionCompatibility = versionCompatibility; _codeBase = codeBase; _flags = flags; } internal void SetProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm) { #pragma warning disable SYSLIB0037 // AssemblyName.ProcessorArchitecture is obsolete ProcessorArchitecture = CalculateProcArchIndex(pek, ifm, _flags); #pragma warning restore SYSLIB0037 } internal static ProcessorArchitecture CalculateProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm, AssemblyNameFlags flags) { if (((uint)flags & 0xF0) == 0x70) return ProcessorArchitecture.None; if ((pek & PortableExecutableKinds.PE32Plus) == PortableExecutableKinds.PE32Plus) { switch (ifm) { case ImageFileMachine.IA64: return ProcessorArchitecture.IA64; case ImageFileMachine.AMD64: return ProcessorArchitecture.Amd64; case ImageFileMachine.I386: if ((pek & PortableExecutableKinds.ILOnly) == PortableExecutableKinds.ILOnly) return ProcessorArchitecture.MSIL; break; } } else { if (ifm == ImageFileMachine.I386) { if ((pek & PortableExecutableKinds.Required32Bit) == PortableExecutableKinds.Required32Bit) return ProcessorArchitecture.X86; if ((pek & PortableExecutableKinds.ILOnly) == PortableExecutableKinds.ILOnly) return ProcessorArchitecture.MSIL; return ProcessorArchitecture.X86; } if (ifm == ImageFileMachine.ARM) { return ProcessorArchitecture.Arm; } } return ProcessorArchitecture.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.Configuration.Assemblies; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace System.Reflection { public sealed partial class AssemblyName : ICloneable, IDeserializationCallback, ISerializable { internal AssemblyName(string? name, byte[]? publicKey, byte[]? publicKeyToken, Version? version, CultureInfo? cultureInfo, AssemblyHashAlgorithm hashAlgorithm, AssemblyVersionCompatibility versionCompatibility, string? codeBase, AssemblyNameFlags flags) { _name = name; _publicKey = publicKey; _publicKeyToken = publicKeyToken; _version = version; _cultureInfo = cultureInfo; _hashAlgorithm = hashAlgorithm; _versionCompatibility = versionCompatibility; _codeBase = codeBase; _flags = flags; } internal void SetProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm) { #pragma warning disable SYSLIB0037 // AssemblyName.ProcessorArchitecture is obsolete ProcessorArchitecture = CalculateProcArchIndex(pek, ifm, _flags); #pragma warning restore SYSLIB0037 } internal static ProcessorArchitecture CalculateProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm, AssemblyNameFlags flags) { if (((uint)flags & 0xF0) == 0x70) return ProcessorArchitecture.None; if ((pek & PortableExecutableKinds.PE32Plus) == PortableExecutableKinds.PE32Plus) { switch (ifm) { case ImageFileMachine.IA64: return ProcessorArchitecture.IA64; case ImageFileMachine.AMD64: return ProcessorArchitecture.Amd64; case ImageFileMachine.I386: if ((pek & PortableExecutableKinds.ILOnly) == PortableExecutableKinds.ILOnly) return ProcessorArchitecture.MSIL; break; } } else { if (ifm == ImageFileMachine.I386) { if ((pek & PortableExecutableKinds.Required32Bit) == PortableExecutableKinds.Required32Bit) return ProcessorArchitecture.X86; if ((pek & PortableExecutableKinds.ILOnly) == PortableExecutableKinds.ILOnly) return ProcessorArchitecture.MSIL; return ProcessorArchitecture.X86; } if (ifm == ImageFileMachine.ARM) { return ProcessorArchitecture.Arm; } } return ProcessorArchitecture.None; } } }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest463/Generated463.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="Generated463.il" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\TestFramework\TestFramework.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="Generated463.il" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\TestFramework\TestFramework.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/native/external/rapidjson/filewritestream.h
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef RAPIDJSON_FILEWRITESTREAM_H_ #define RAPIDJSON_FILEWRITESTREAM_H_ #include "stream.h" #include <cstdio> #ifdef __clang__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(unreachable-code) #endif RAPIDJSON_NAMESPACE_BEGIN //! Wrapper of C file stream for output using fwrite(). /*! \note implements Stream concept */ class FileWriteStream { public: typedef char Ch; //!< Character type. Only support char. FileWriteStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferEnd_(buffer + bufferSize), current_(buffer_) { RAPIDJSON_ASSERT(fp_ != 0); } void Put(char c) { if (current_ >= bufferEnd_) Flush(); *current_++ = c; } void PutN(char c, size_t n) { size_t avail = static_cast<size_t>(bufferEnd_ - current_); while (n > avail) { std::memset(current_, c, avail); current_ += avail; Flush(); n -= avail; avail = static_cast<size_t>(bufferEnd_ - current_); } if (n > 0) { std::memset(current_, c, n); current_ += n; } } void Flush() { if (current_ != buffer_) { size_t result = std::fwrite(buffer_, 1, static_cast<size_t>(current_ - buffer_), fp_); if (result < static_cast<size_t>(current_ - buffer_)) { // failure deliberately ignored at this time // added to avoid warn_unused_result build errors } current_ = buffer_; } } // Not implemented char Peek() const { RAPIDJSON_ASSERT(false); return 0; } char Take() { RAPIDJSON_ASSERT(false); return 0; } size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; } char* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } size_t PutEnd(char*) { RAPIDJSON_ASSERT(false); return 0; } private: // Prohibit copy constructor & assignment operator. FileWriteStream(const FileWriteStream&); FileWriteStream& operator=(const FileWriteStream&); std::FILE* fp_; char *buffer_; char *bufferEnd_; char *current_; }; //! Implement specialized version of PutN() with memset() for better performance. template<> inline void PutN(FileWriteStream& stream, char c, size_t n) { stream.PutN(c, n); } RAPIDJSON_NAMESPACE_END #ifdef __clang__ RAPIDJSON_DIAG_POP #endif #endif // RAPIDJSON_FILESTREAM_H_
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef RAPIDJSON_FILEWRITESTREAM_H_ #define RAPIDJSON_FILEWRITESTREAM_H_ #include "stream.h" #include <cstdio> #ifdef __clang__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(unreachable-code) #endif RAPIDJSON_NAMESPACE_BEGIN //! Wrapper of C file stream for output using fwrite(). /*! \note implements Stream concept */ class FileWriteStream { public: typedef char Ch; //!< Character type. Only support char. FileWriteStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferEnd_(buffer + bufferSize), current_(buffer_) { RAPIDJSON_ASSERT(fp_ != 0); } void Put(char c) { if (current_ >= bufferEnd_) Flush(); *current_++ = c; } void PutN(char c, size_t n) { size_t avail = static_cast<size_t>(bufferEnd_ - current_); while (n > avail) { std::memset(current_, c, avail); current_ += avail; Flush(); n -= avail; avail = static_cast<size_t>(bufferEnd_ - current_); } if (n > 0) { std::memset(current_, c, n); current_ += n; } } void Flush() { if (current_ != buffer_) { size_t result = std::fwrite(buffer_, 1, static_cast<size_t>(current_ - buffer_), fp_); if (result < static_cast<size_t>(current_ - buffer_)) { // failure deliberately ignored at this time // added to avoid warn_unused_result build errors } current_ = buffer_; } } // Not implemented char Peek() const { RAPIDJSON_ASSERT(false); return 0; } char Take() { RAPIDJSON_ASSERT(false); return 0; } size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; } char* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } size_t PutEnd(char*) { RAPIDJSON_ASSERT(false); return 0; } private: // Prohibit copy constructor & assignment operator. FileWriteStream(const FileWriteStream&); FileWriteStream& operator=(const FileWriteStream&); std::FILE* fp_; char *buffer_; char *bufferEnd_; char *current_; }; //! Implement specialized version of PutN() with memset() for better performance. template<> inline void PutN(FileWriteStream& stream, char c, size_t n) { stream.PutN(c, n); } RAPIDJSON_NAMESPACE_END #ifdef __clang__ RAPIDJSON_DIAG_POP #endif #endif // RAPIDJSON_FILESTREAM_H_
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/native/corehost/hostmisc/trace.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "trace.h" #include <mutex> // g_trace_verbosity is used to encode COREHOST_TRACE and COREHOST_TRACE_VERBOSITY to selectively control output of // trace::warn(), trace::info(), and trace::verbose() // COREHOST_TRACE=0 COREHOST_TRACE_VERBOSITY=N/A implies g_trace_verbosity = 0. // Trace "disabled". error() messages will be produced. // COREHOST_TRACE=1 COREHOST_TRACE_VERBOSITY=4 or unset implies g_trace_verbosity = 4. // Trace "enabled". verbose(), info(), warn() and error() messages will be produced // COREHOST_TRACE=1 COREHOST_TRACE_VERBOSITY=3 implies g_trace_verbosity = 3. // Trace "enabled". info(), warn() and error() messages will be produced // COREHOST_TRACE=1 COREHOST_TRACE_VERBOSITY=2 implies g_trace_verbosity = 2. // Trace "enabled". warn() and error() messages will be produced // COREHOST_TRACE=1 COREHOST_TRACE_VERBOSITY=1 implies g_trace_verbosity = 1. // Trace "enabled". error() messages will be produced static int g_trace_verbosity = 0; static FILE * g_trace_file = stderr; static pal::mutex_t g_trace_mutex; thread_local static trace::error_writer_fn g_error_writer = nullptr; // // Turn on tracing for the corehost based on "COREHOST_TRACE" & "COREHOST_TRACEFILE" env. // void trace::setup() { // Read trace environment variable pal::string_t trace_str; if (!pal::getenv(_X("COREHOST_TRACE"), &trace_str)) { return; } auto trace_val = pal::xtoi(trace_str.c_str()); if (trace_val > 0) { if (trace::enable()) { auto ts = pal::get_timestamp(); trace::info(_X("Tracing enabled @ %s"), ts.c_str()); } } } bool trace::enable() { bool file_open_error = false; pal::string_t tracefile_str; if (g_trace_verbosity) { return false; } else { std::lock_guard<pal::mutex_t> lock(g_trace_mutex); g_trace_file = stderr; if (pal::getenv(_X("COREHOST_TRACEFILE"), &tracefile_str)) { FILE *tracefile = pal::file_open(tracefile_str, _X("a")); if (tracefile) { setvbuf(tracefile, nullptr, _IONBF, 0); g_trace_file = tracefile; } else { file_open_error = true; } } pal::string_t trace_str; if (!pal::getenv(_X("COREHOST_TRACE_VERBOSITY"), &trace_str)) { g_trace_verbosity = 4; // Verbose trace by default } else { g_trace_verbosity = pal::xtoi(trace_str.c_str()); } } if (file_open_error) { trace::error(_X("Unable to open COREHOST_TRACEFILE=%s for writing"), tracefile_str.c_str()); } return true; } bool trace::is_enabled() { return g_trace_verbosity; } void trace::verbose(const pal::char_t* format, ...) { if (g_trace_verbosity > 3) { std::lock_guard<pal::mutex_t> lock(g_trace_mutex); va_list args; va_start(args, format); pal::file_vprintf(g_trace_file, format, args); va_end(args); } } void trace::info(const pal::char_t* format, ...) { if (g_trace_verbosity > 2) { std::lock_guard<pal::mutex_t> lock(g_trace_mutex); va_list args; va_start(args, format); pal::file_vprintf(g_trace_file, format, args); va_end(args); } } void trace::error(const pal::char_t* format, ...) { std::lock_guard<pal::mutex_t> lock(g_trace_mutex); // Always print errors va_list args; va_start(args, format); va_list trace_args; va_copy(trace_args, args); va_list dup_args; va_copy(dup_args, args); int count = pal::strlen_vprintf(format, args) + 1; std::vector<pal::char_t> buffer(count); pal::str_vprintf(&buffer[0], count, format, dup_args); if (g_error_writer == nullptr) { pal::err_fputs(buffer.data()); } else { g_error_writer(buffer.data()); } #if defined(_WIN32) ::OutputDebugStringW(buffer.data()); #endif if (g_trace_verbosity && ((g_trace_file != stderr) || g_error_writer != nullptr)) { pal::file_vprintf(g_trace_file, format, trace_args); } va_end(args); } void trace::println(const pal::char_t* format, ...) { std::lock_guard<pal::mutex_t> lock(g_trace_mutex); va_list args; va_start(args, format); pal::out_vprintf(format, args); va_end(args); } void trace::println() { println(_X("")); } void trace::warning(const pal::char_t* format, ...) { if (g_trace_verbosity > 1) { std::lock_guard<pal::mutex_t> lock(g_trace_mutex); va_list args; va_start(args, format); pal::file_vprintf(g_trace_file, format, args); va_end(args); } } void trace::flush() { std::lock_guard<pal::mutex_t> lock(g_trace_mutex); pal::file_flush(g_trace_file); pal::err_flush(); pal::out_flush(); } trace::error_writer_fn trace::set_error_writer(trace::error_writer_fn error_writer) { // No need for locking since g_error_writer is thread local. error_writer_fn previous_writer = g_error_writer; g_error_writer = error_writer; return previous_writer; } trace::error_writer_fn trace::get_error_writer() { // No need for locking since g_error_writer is thread local. return g_error_writer; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "trace.h" #include <mutex> // g_trace_verbosity is used to encode COREHOST_TRACE and COREHOST_TRACE_VERBOSITY to selectively control output of // trace::warn(), trace::info(), and trace::verbose() // COREHOST_TRACE=0 COREHOST_TRACE_VERBOSITY=N/A implies g_trace_verbosity = 0. // Trace "disabled". error() messages will be produced. // COREHOST_TRACE=1 COREHOST_TRACE_VERBOSITY=4 or unset implies g_trace_verbosity = 4. // Trace "enabled". verbose(), info(), warn() and error() messages will be produced // COREHOST_TRACE=1 COREHOST_TRACE_VERBOSITY=3 implies g_trace_verbosity = 3. // Trace "enabled". info(), warn() and error() messages will be produced // COREHOST_TRACE=1 COREHOST_TRACE_VERBOSITY=2 implies g_trace_verbosity = 2. // Trace "enabled". warn() and error() messages will be produced // COREHOST_TRACE=1 COREHOST_TRACE_VERBOSITY=1 implies g_trace_verbosity = 1. // Trace "enabled". error() messages will be produced static int g_trace_verbosity = 0; static FILE * g_trace_file = stderr; static pal::mutex_t g_trace_mutex; thread_local static trace::error_writer_fn g_error_writer = nullptr; // // Turn on tracing for the corehost based on "COREHOST_TRACE" & "COREHOST_TRACEFILE" env. // void trace::setup() { // Read trace environment variable pal::string_t trace_str; if (!pal::getenv(_X("COREHOST_TRACE"), &trace_str)) { return; } auto trace_val = pal::xtoi(trace_str.c_str()); if (trace_val > 0) { if (trace::enable()) { auto ts = pal::get_timestamp(); trace::info(_X("Tracing enabled @ %s"), ts.c_str()); } } } bool trace::enable() { bool file_open_error = false; pal::string_t tracefile_str; if (g_trace_verbosity) { return false; } else { std::lock_guard<pal::mutex_t> lock(g_trace_mutex); g_trace_file = stderr; if (pal::getenv(_X("COREHOST_TRACEFILE"), &tracefile_str)) { FILE *tracefile = pal::file_open(tracefile_str, _X("a")); if (tracefile) { setvbuf(tracefile, nullptr, _IONBF, 0); g_trace_file = tracefile; } else { file_open_error = true; } } pal::string_t trace_str; if (!pal::getenv(_X("COREHOST_TRACE_VERBOSITY"), &trace_str)) { g_trace_verbosity = 4; // Verbose trace by default } else { g_trace_verbosity = pal::xtoi(trace_str.c_str()); } } if (file_open_error) { trace::error(_X("Unable to open COREHOST_TRACEFILE=%s for writing"), tracefile_str.c_str()); } return true; } bool trace::is_enabled() { return g_trace_verbosity; } void trace::verbose(const pal::char_t* format, ...) { if (g_trace_verbosity > 3) { std::lock_guard<pal::mutex_t> lock(g_trace_mutex); va_list args; va_start(args, format); pal::file_vprintf(g_trace_file, format, args); va_end(args); } } void trace::info(const pal::char_t* format, ...) { if (g_trace_verbosity > 2) { std::lock_guard<pal::mutex_t> lock(g_trace_mutex); va_list args; va_start(args, format); pal::file_vprintf(g_trace_file, format, args); va_end(args); } } void trace::error(const pal::char_t* format, ...) { std::lock_guard<pal::mutex_t> lock(g_trace_mutex); // Always print errors va_list args; va_start(args, format); va_list trace_args; va_copy(trace_args, args); va_list dup_args; va_copy(dup_args, args); int count = pal::strlen_vprintf(format, args) + 1; std::vector<pal::char_t> buffer(count); pal::str_vprintf(&buffer[0], count, format, dup_args); if (g_error_writer == nullptr) { pal::err_fputs(buffer.data()); } else { g_error_writer(buffer.data()); } #if defined(_WIN32) ::OutputDebugStringW(buffer.data()); #endif if (g_trace_verbosity && ((g_trace_file != stderr) || g_error_writer != nullptr)) { pal::file_vprintf(g_trace_file, format, trace_args); } va_end(args); } void trace::println(const pal::char_t* format, ...) { std::lock_guard<pal::mutex_t> lock(g_trace_mutex); va_list args; va_start(args, format); pal::out_vprintf(format, args); va_end(args); } void trace::println() { println(_X("")); } void trace::warning(const pal::char_t* format, ...) { if (g_trace_verbosity > 1) { std::lock_guard<pal::mutex_t> lock(g_trace_mutex); va_list args; va_start(args, format); pal::file_vprintf(g_trace_file, format, args); va_end(args); } } void trace::flush() { std::lock_guard<pal::mutex_t> lock(g_trace_mutex); pal::file_flush(g_trace_file); pal::err_flush(); pal::out_flush(); } trace::error_writer_fn trace::set_error_writer(trace::error_writer_fn error_writer) { // No need for locking since g_error_writer is thread local. error_writer_fn previous_writer = g_error_writer; g_error_writer = error_writer; return previous_writer; } trace::error_writer_fn trace::get_error_writer() { // No need for locking since g_error_writer is thread local. return g_error_writer; }
-1
dotnet/runtime
66,334
Add timestamp-based expiration to cached SafeFreeCredentials
Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
rzikm
2022-03-08T14:47:09Z
2022-03-24T12:03:11Z
7d1191e32208702899eec55aa622b6aff99986e1
e97af550093757503365b2fe175ea1d5b6f6c7ed
Add timestamp-based expiration to cached SafeFreeCredentials. Fixes #43879 This PR adds timestamp-based invalidation of `SafeFreeCredentials` in `SslSessionCache`. The expiration timestamp is calculated based on `NotAfter` fields of the certificates in the `SslAuthenticationOptions.CertificateContext` (both the actual certificates and the intermediate certs in the chain). Since this PR does not add any `X509Chain.Build()` calls to the hot path, I believe there should not be a significant perf hit from this change. I can run benchmarks next week once I have access to my desktop machine. Also to consider: does it make sense to try to create a test for this? It would probably go to OuterLoop since it would run around 2 minutes, but since the repro requires admin privileges (at least on Windows), I am not sure how viable it is. Maybe running the test on Linux would be sufficient.
./src/libraries/Common/src/System/Net/Http/WinInetProxyHelper.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.InteropServices; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http { // This class is only used on OS versions where WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY // is not supported (i.e. before Win8.1/Win2K12R2) in the WinHttpOpen() function. internal sealed class WinInetProxyHelper { private const int RecentAutoDetectionInterval = 120_000; // 2 minutes in milliseconds. private readonly string? _autoConfigUrl, _proxy, _proxyBypass; private readonly bool _autoDetect; private readonly bool _useProxy; private bool _autoDetectionFailed; private int _lastTimeAutoDetectionFailed; // Environment.TickCount units (milliseconds). public WinInetProxyHelper() { Interop.WinHttp.WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig = default; try { if (Interop.WinHttp.WinHttpGetIEProxyConfigForCurrentUser(out proxyConfig)) { _autoConfigUrl = Marshal.PtrToStringUni(proxyConfig.AutoConfigUrl)!; _autoDetect = proxyConfig.AutoDetect != 0; _proxy = Marshal.PtrToStringUni(proxyConfig.Proxy)!; _proxyBypass = Marshal.PtrToStringUni(proxyConfig.ProxyBypass)!; if (NetEventSource.Log.IsEnabled()) { NetEventSource.Info(this, $"AutoConfigUrl={AutoConfigUrl}, AutoDetect={AutoDetect}, Proxy={Proxy}, ProxyBypass={ProxyBypass}"); } _useProxy = true; } else { // We match behavior of WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY and ignore errors. int lastError = Marshal.GetLastWin32Error(); if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"error={lastError}"); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_useProxy={_useProxy}"); } finally { // FreeHGlobal already checks for null pointer before freeing the memory. Marshal.FreeHGlobal(proxyConfig.AutoConfigUrl); Marshal.FreeHGlobal(proxyConfig.Proxy); Marshal.FreeHGlobal(proxyConfig.ProxyBypass); } } public string? AutoConfigUrl => _autoConfigUrl; public bool AutoDetect => _autoDetect; public bool AutoSettingsUsed => AutoDetect || !string.IsNullOrEmpty(AutoConfigUrl); public bool ManualSettingsUsed => !string.IsNullOrEmpty(Proxy); public bool ManualSettingsOnly => !AutoSettingsUsed && ManualSettingsUsed; public string? Proxy => _proxy; public string? ProxyBypass => _proxyBypass; public bool RecentAutoDetectionFailure => _autoDetectionFailed && Environment.TickCount - _lastTimeAutoDetectionFailed <= RecentAutoDetectionInterval; public bool GetProxyForUrl( SafeWinHttpHandle? sessionHandle, Uri uri, out Interop.WinHttp.WINHTTP_PROXY_INFO proxyInfo) { proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY; proxyInfo.Proxy = IntPtr.Zero; proxyInfo.ProxyBypass = IntPtr.Zero; if (!_useProxy) { return false; } bool useProxy = false; Interop.WinHttp.WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions; autoProxyOptions.AutoConfigUrl = AutoConfigUrl; autoProxyOptions.AutoDetectFlags = AutoDetect ? (Interop.WinHttp.WINHTTP_AUTO_DETECT_TYPE_DHCP | Interop.WinHttp.WINHTTP_AUTO_DETECT_TYPE_DNS_A) : 0; autoProxyOptions.AutoLoginIfChallenged = false; autoProxyOptions.Flags = (AutoDetect ? Interop.WinHttp.WINHTTP_AUTOPROXY_AUTO_DETECT : 0) | (!string.IsNullOrEmpty(AutoConfigUrl) ? Interop.WinHttp.WINHTTP_AUTOPROXY_CONFIG_URL : 0); autoProxyOptions.Reserved1 = IntPtr.Zero; autoProxyOptions.Reserved2 = 0; // AutoProxy Cache. // https://docs.microsoft.com/en-us/windows/desktop/WinHttp/autoproxy-cache // If the out-of-process service is active when WinHttpGetProxyForUrl is called, the cached autoproxy // URL and script are available to the whole computer. However, if the out-of-process service is used, // and the fAutoLogonIfChallenged flag in the pAutoProxyOptions structure is true, then the autoproxy // URL and script are not cached. Therefore, calling WinHttpGetProxyForUrl with the fAutoLogonIfChallenged // member set to TRUE results in additional overhead operations that may affect performance. // The following steps can be used to improve performance: // 1. Call WinHttpGetProxyForUrl with the fAutoLogonIfChallenged parameter set to false. The autoproxy // URL and script are cached for future calls to WinHttpGetProxyForUrl. // 2. If Step 1 fails, with ERROR_WINHTTP_LOGIN_FAILURE, then call WinHttpGetProxyForUrl with the // fAutoLogonIfChallenged member set to TRUE. // // We match behavior of WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY and ignore errors. #pragma warning disable CA1845 // file is shared with a build that lacks string.Concat for spans // Underlying code does not understand WebSockets so we need to convert it to http or https. string destination = uri.AbsoluteUri; if (uri.Scheme == UriScheme.Wss) { destination = UriScheme.Https + destination.Substring(UriScheme.Wss.Length); } else if (uri.Scheme == UriScheme.Ws) { destination = UriScheme.Http + destination.Substring(UriScheme.Ws.Length); } #pragma warning restore CA1845 var repeat = false; do { _autoDetectionFailed = false; if (Interop.WinHttp.WinHttpGetProxyForUrl( sessionHandle!, destination, ref autoProxyOptions, out proxyInfo)) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Using autoconfig proxy settings"); useProxy = true; break; } else { var lastError = Marshal.GetLastWin32Error(); if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"error={lastError}"); if (lastError == Interop.WinHttp.ERROR_WINHTTP_LOGIN_FAILURE) { if (repeat) { // We don't retry more than once. break; } else { repeat = true; autoProxyOptions.AutoLoginIfChallenged = true; } } else { if (lastError == Interop.WinHttp.ERROR_WINHTTP_AUTODETECTION_FAILED) { _autoDetectionFailed = true; _lastTimeAutoDetectionFailed = Environment.TickCount; } break; } } } while (repeat); // Fall back to manual settings if available. if (!useProxy && !string.IsNullOrEmpty(Proxy)) { proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY; proxyInfo.Proxy = Marshal.StringToHGlobalUni(Proxy); proxyInfo.ProxyBypass = string.IsNullOrEmpty(ProxyBypass) ? IntPtr.Zero : Marshal.StringToHGlobalUni(ProxyBypass); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Fallback to Proxy={Proxy}, ProxyBypass={ProxyBypass}"); useProxy = true; } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"useProxy={useProxy}"); return useProxy; } } }
// 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.InteropServices; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http { // This class is only used on OS versions where WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY // is not supported (i.e. before Win8.1/Win2K12R2) in the WinHttpOpen() function. internal sealed class WinInetProxyHelper { private const int RecentAutoDetectionInterval = 120_000; // 2 minutes in milliseconds. private readonly string? _autoConfigUrl, _proxy, _proxyBypass; private readonly bool _autoDetect; private readonly bool _useProxy; private bool _autoDetectionFailed; private int _lastTimeAutoDetectionFailed; // Environment.TickCount units (milliseconds). public WinInetProxyHelper() { Interop.WinHttp.WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig = default; try { if (Interop.WinHttp.WinHttpGetIEProxyConfigForCurrentUser(out proxyConfig)) { _autoConfigUrl = Marshal.PtrToStringUni(proxyConfig.AutoConfigUrl)!; _autoDetect = proxyConfig.AutoDetect != 0; _proxy = Marshal.PtrToStringUni(proxyConfig.Proxy)!; _proxyBypass = Marshal.PtrToStringUni(proxyConfig.ProxyBypass)!; if (NetEventSource.Log.IsEnabled()) { NetEventSource.Info(this, $"AutoConfigUrl={AutoConfigUrl}, AutoDetect={AutoDetect}, Proxy={Proxy}, ProxyBypass={ProxyBypass}"); } _useProxy = true; } else { // We match behavior of WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY and ignore errors. int lastError = Marshal.GetLastWin32Error(); if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"error={lastError}"); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_useProxy={_useProxy}"); } finally { // FreeHGlobal already checks for null pointer before freeing the memory. Marshal.FreeHGlobal(proxyConfig.AutoConfigUrl); Marshal.FreeHGlobal(proxyConfig.Proxy); Marshal.FreeHGlobal(proxyConfig.ProxyBypass); } } public string? AutoConfigUrl => _autoConfigUrl; public bool AutoDetect => _autoDetect; public bool AutoSettingsUsed => AutoDetect || !string.IsNullOrEmpty(AutoConfigUrl); public bool ManualSettingsUsed => !string.IsNullOrEmpty(Proxy); public bool ManualSettingsOnly => !AutoSettingsUsed && ManualSettingsUsed; public string? Proxy => _proxy; public string? ProxyBypass => _proxyBypass; public bool RecentAutoDetectionFailure => _autoDetectionFailed && Environment.TickCount - _lastTimeAutoDetectionFailed <= RecentAutoDetectionInterval; public bool GetProxyForUrl( SafeWinHttpHandle? sessionHandle, Uri uri, out Interop.WinHttp.WINHTTP_PROXY_INFO proxyInfo) { proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY; proxyInfo.Proxy = IntPtr.Zero; proxyInfo.ProxyBypass = IntPtr.Zero; if (!_useProxy) { return false; } bool useProxy = false; Interop.WinHttp.WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions; autoProxyOptions.AutoConfigUrl = AutoConfigUrl; autoProxyOptions.AutoDetectFlags = AutoDetect ? (Interop.WinHttp.WINHTTP_AUTO_DETECT_TYPE_DHCP | Interop.WinHttp.WINHTTP_AUTO_DETECT_TYPE_DNS_A) : 0; autoProxyOptions.AutoLoginIfChallenged = false; autoProxyOptions.Flags = (AutoDetect ? Interop.WinHttp.WINHTTP_AUTOPROXY_AUTO_DETECT : 0) | (!string.IsNullOrEmpty(AutoConfigUrl) ? Interop.WinHttp.WINHTTP_AUTOPROXY_CONFIG_URL : 0); autoProxyOptions.Reserved1 = IntPtr.Zero; autoProxyOptions.Reserved2 = 0; // AutoProxy Cache. // https://docs.microsoft.com/en-us/windows/desktop/WinHttp/autoproxy-cache // If the out-of-process service is active when WinHttpGetProxyForUrl is called, the cached autoproxy // URL and script are available to the whole computer. However, if the out-of-process service is used, // and the fAutoLogonIfChallenged flag in the pAutoProxyOptions structure is true, then the autoproxy // URL and script are not cached. Therefore, calling WinHttpGetProxyForUrl with the fAutoLogonIfChallenged // member set to TRUE results in additional overhead operations that may affect performance. // The following steps can be used to improve performance: // 1. Call WinHttpGetProxyForUrl with the fAutoLogonIfChallenged parameter set to false. The autoproxy // URL and script are cached for future calls to WinHttpGetProxyForUrl. // 2. If Step 1 fails, with ERROR_WINHTTP_LOGIN_FAILURE, then call WinHttpGetProxyForUrl with the // fAutoLogonIfChallenged member set to TRUE. // // We match behavior of WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY and ignore errors. #pragma warning disable CA1845 // file is shared with a build that lacks string.Concat for spans // Underlying code does not understand WebSockets so we need to convert it to http or https. string destination = uri.AbsoluteUri; if (uri.Scheme == UriScheme.Wss) { destination = UriScheme.Https + destination.Substring(UriScheme.Wss.Length); } else if (uri.Scheme == UriScheme.Ws) { destination = UriScheme.Http + destination.Substring(UriScheme.Ws.Length); } #pragma warning restore CA1845 var repeat = false; do { _autoDetectionFailed = false; if (Interop.WinHttp.WinHttpGetProxyForUrl( sessionHandle!, destination, ref autoProxyOptions, out proxyInfo)) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Using autoconfig proxy settings"); useProxy = true; break; } else { var lastError = Marshal.GetLastWin32Error(); if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, $"error={lastError}"); if (lastError == Interop.WinHttp.ERROR_WINHTTP_LOGIN_FAILURE) { if (repeat) { // We don't retry more than once. break; } else { repeat = true; autoProxyOptions.AutoLoginIfChallenged = true; } } else { if (lastError == Interop.WinHttp.ERROR_WINHTTP_AUTODETECTION_FAILED) { _autoDetectionFailed = true; _lastTimeAutoDetectionFailed = Environment.TickCount; } break; } } } while (repeat); // Fall back to manual settings if available. if (!useProxy && !string.IsNullOrEmpty(Proxy)) { proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY; proxyInfo.Proxy = Marshal.StringToHGlobalUni(Proxy); proxyInfo.ProxyBypass = string.IsNullOrEmpty(ProxyBypass) ? IntPtr.Zero : Marshal.StringToHGlobalUni(ProxyBypass); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Fallback to Proxy={Proxy}, ProxyBypass={ProxyBypass}"); useProxy = true; } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"useProxy={useProxy}"); return useProxy; } } }
-1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/installer/tests/HostActivation.Tests/DependencyResolution/ComponentDependencyResolutionBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.DotNet.Cli.Build; using Microsoft.DotNet.Cli.Build.Framework; using System; using System.IO; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.DependencyResolution { public abstract class ComponentDependencyResolutionBase : DependencyResolutionBase { public abstract class ComponentSharedTestStateBase : SharedTestStateBase { private const string resolve_component_dependencies = "resolve_component_dependencies"; private const string run_app_and_resolve = "run_app_and_resolve"; private const string run_app_and_resolve_multithreaded = "run_app_and_resolve_multithreaded"; public DotNetCli DotNetWithNetCoreApp { get; } public TestApp FrameworkReferenceApp { get; } public string NativeHostPath { get => _nativeHostingState.NativeHostPath; } private readonly NativeHosting.SharedTestStateBase _nativeHostingState; public ComponentSharedTestStateBase() { DotNetWithNetCoreApp = DotNet("WithNetCoreApp") .AddMicrosoftNETCoreAppFrameworkMockCoreClr("4.0.0", builder => CustomizeDotNetWithNetCoreAppMicrosoftNETCoreApp(builder)) .Build(); TestApp app = CreateFrameworkReferenceApp(MicrosoftNETCoreApp, "4.0.0"); FrameworkReferenceApp = NetCoreAppBuilder.PortableForNETCoreApp(app) .WithProject(p => p.WithAssemblyGroup(null, g => g.WithMainAssembly())) .Build(app); _nativeHostingState = new NativeHosting.SharedTestStateBase(); } protected virtual void CustomizeDotNetWithNetCoreAppMicrosoftNETCoreApp(NetCoreAppBuilder builder) { } public CommandResult RunComponentResolutionTest(TestApp component, Action<Command> commandCustomizer = null) { return RunComponentResolutionTest(component.AppDll, FrameworkReferenceApp, DotNetWithNetCoreApp.GreatestVersionHostFxrPath, commandCustomizer); } public CommandResult RunComponentResolutionTest(string componentPath, TestApp hostApp, string hostFxrFolder, Action<Command> commandCustomizer = null) { string[] args = { resolve_component_dependencies, run_app_and_resolve, Path.Combine(hostFxrFolder, RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostfxr")), hostApp.AppDll, componentPath }; Command command = Command.Create(NativeHostPath, args) .EnableTracingAndCaptureOutputs() .MultilevelLookup(false); commandCustomizer?.Invoke(command); return command.Execute() .StdErrAfter("corehost_resolve_component_dependencies = {"); } public CommandResult RunComponentResolutionMultiThreadedTest(TestApp componentOne, TestApp componentTwo) { return RunComponentResolutionMultiThreadedTest(componentOne.AppDll, componentTwo.AppDll, FrameworkReferenceApp, DotNetWithNetCoreApp.GreatestVersionHostFxrPath); } public CommandResult RunComponentResolutionMultiThreadedTest(string componentOnePath, string componentTwoPath, TestApp hostApp, string hostFxrFolder) { string[] args = { resolve_component_dependencies, run_app_and_resolve_multithreaded, Path.Combine(hostFxrFolder, RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostfxr")), hostApp.AppDll, componentOnePath, componentTwoPath }; return Command.Create(NativeHostPath, args) .EnableTracingAndCaptureOutputs() .MultilevelLookup(false) .Execute(); } public override void Dispose() { base.Dispose(); FrameworkReferenceApp.Dispose(); _nativeHostingState.Dispose(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.DotNet.Cli.Build; using Microsoft.DotNet.Cli.Build.Framework; using System; using System.IO; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.DependencyResolution { public abstract class ComponentDependencyResolutionBase : DependencyResolutionBase { public abstract class ComponentSharedTestStateBase : SharedTestStateBase { private const string resolve_component_dependencies = "resolve_component_dependencies"; private const string run_app_and_resolve = "run_app_and_resolve"; private const string run_app_and_resolve_multithreaded = "run_app_and_resolve_multithreaded"; public DotNetCli DotNetWithNetCoreApp { get; } public TestApp FrameworkReferenceApp { get; } public string NativeHostPath { get => _nativeHostingState.NativeHostPath; } private readonly NativeHosting.SharedTestStateBase _nativeHostingState; public ComponentSharedTestStateBase() { var dotNetBuilder = DotNet("WithNetCoreApp") .AddMicrosoftNETCoreAppFrameworkMockCoreClr("4.0.0", builder => CustomizeDotNetWithNetCoreAppMicrosoftNETCoreApp(builder)); CustomizeDotNetWithNetCoreApp(dotNetBuilder); DotNetWithNetCoreApp = dotNetBuilder.Build(); TestApp app = CreateTestFrameworkReferenceApp(); FrameworkReferenceApp = NetCoreAppBuilder.PortableForNETCoreApp(app) .WithProject(p => p.WithAssemblyGroup(null, g => g.WithMainAssembly())) .Build(app); _nativeHostingState = new NativeHosting.SharedTestStateBase(); } protected virtual TestApp CreateTestFrameworkReferenceApp() => CreateFrameworkReferenceApp(MicrosoftNETCoreApp, "4.0.0"); protected virtual void CustomizeDotNetWithNetCoreAppMicrosoftNETCoreApp(NetCoreAppBuilder builder) { } protected virtual void CustomizeDotNetWithNetCoreApp(DotNetBuilder builder) { } public CommandResult RunComponentResolutionTest(TestApp component, Action<Command> commandCustomizer = null) { return RunComponentResolutionTest(component.AppDll, FrameworkReferenceApp, DotNetWithNetCoreApp.GreatestVersionHostFxrPath, commandCustomizer); } public CommandResult RunComponentResolutionTest(string componentPath, TestApp hostApp, string hostFxrFolder, Action<Command> commandCustomizer = null) { string[] args = { resolve_component_dependencies, run_app_and_resolve, Path.Combine(hostFxrFolder, RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostfxr")), hostApp.AppDll, componentPath }; Command command = Command.Create(NativeHostPath, args) .EnableTracingAndCaptureOutputs() .MultilevelLookup(false); commandCustomizer?.Invoke(command); return command.Execute() .StdErrAfter("corehost_resolve_component_dependencies = {"); } public CommandResult RunComponentResolutionMultiThreadedTest(TestApp componentOne, TestApp componentTwo) { return RunComponentResolutionMultiThreadedTest(componentOne.AppDll, componentTwo.AppDll, FrameworkReferenceApp, DotNetWithNetCoreApp.GreatestVersionHostFxrPath); } public CommandResult RunComponentResolutionMultiThreadedTest(string componentOnePath, string componentTwoPath, TestApp hostApp, string hostFxrFolder) { string[] args = { resolve_component_dependencies, run_app_and_resolve_multithreaded, Path.Combine(hostFxrFolder, RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostfxr")), hostApp.AppDll, componentOnePath, componentTwoPath }; return Command.Create(NativeHostPath, args) .EnableTracingAndCaptureOutputs() .MultilevelLookup(false) .Execute(); } public override void Dispose() { base.Dispose(); FrameworkReferenceApp.Dispose(); _nativeHostingState.Dispose(); } } } }
1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/installer/tests/HostActivation.Tests/DependencyResolution/PerAssemblyVersionResolution.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 Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.DependencyResolution { public abstract class PerAssemblyVersionResolutionBase : ComponentDependencyResolutionBase, IClassFixture<PerAssemblyVersionResolutionBase.SharedTestState> { protected readonly SharedTestState SharedState; public PerAssemblyVersionResolutionBase(SharedTestState fixture) { SharedState = fixture; } protected const string TestVersionsPackage = "Test.Versions.Package"; // The test framework above has 4 assemblies in it each with different set of assembly and file versions. // The version values are always (if present) // - assembly version: 2.1.1.1 // - file version: 3.2.2.2 private const string TestAssemblyWithNoVersions = "Test.Assembly.NoVersions"; private const string TestAssemblyWithAssemblyVersion = "Test.Assembly.AssemblyVersion"; private const string TestAssemblyWithFileVersion = "Test.Assembly.FileVersion"; private const string TestAssemblyWithBothVersions = "Test.Assembly.BothVersions"; [Theory] [InlineData(TestAssemblyWithBothVersions, null, null, false)] [InlineData(TestAssemblyWithBothVersions, "1.0.0.0", "1.0.0.0", false)] [InlineData(TestAssemblyWithBothVersions, "3.0.0.0", "4.0.0.0", true)] [InlineData(TestAssemblyWithBothVersions, "2.1.1.1", "1.0.0.0", false)] [InlineData(TestAssemblyWithBothVersions, "2.1.1.1", "3.3.0.0", true)] [InlineData(TestAssemblyWithBothVersions, "2.1.1.1", "3.2.2.2", false)] // Lower level framework always wins on equality (this is intentional) [InlineData(TestAssemblyWithBothVersions, null, "4.0.0.0", false)] // The one with version wins [InlineData(TestAssemblyWithBothVersions, null, "2.0.0.0", false)] // The one with version wins [InlineData(TestAssemblyWithBothVersions, "3.0.0.0", null, true)] [InlineData(TestAssemblyWithBothVersions, "2.1.1.1", null, false)] [InlineData(TestAssemblyWithNoVersions, null, null, false)] // No versions are treated as equal (so lower one wins) [InlineData(TestAssemblyWithNoVersions, "1.0.0.0", null, true)] [InlineData(TestAssemblyWithNoVersions, "1.0.0.0", "1.0.0.0", true)] [InlineData(TestAssemblyWithNoVersions, null, "1.0.0.0", true)] [InlineData(TestAssemblyWithAssemblyVersion, null, null, false)] [InlineData(TestAssemblyWithAssemblyVersion, "1.0.0.0", null, false)] [InlineData(TestAssemblyWithAssemblyVersion, null, "1.0.0.0", false)] [InlineData(TestAssemblyWithAssemblyVersion, "3.0.0.0", "1.0.0.0", true)] [InlineData(TestAssemblyWithAssemblyVersion, "2.1.1.1", null, false)] [InlineData(TestAssemblyWithAssemblyVersion, "2.1.1.1", "1.0.0.0", true)] [InlineData(TestAssemblyWithFileVersion, null, null, false)] [InlineData(TestAssemblyWithFileVersion, "1.0.0.0", null, true)] [InlineData(TestAssemblyWithFileVersion, null, "1.0.0.0", false)] [InlineData(TestAssemblyWithFileVersion, null, "4.0.0.0", true)] [InlineData(TestAssemblyWithFileVersion, null, "3.2.2.2", false)] public void AppWithSameAssemblyAsFramework(string testAssemblyName, string appAsmVersion, string appFileVersion, bool appWins) { RunTest(b => b .WithPackage(TestVersionsPackage, "1.0.0", lib => lib .WithAssemblyGroup(null, g => g .WithAsset(testAssemblyName + ".dll", rf => rf .WithVersion(appAsmVersion, appFileVersion)))), testAssemblyName, appAsmVersion, appFileVersion, appWins); } protected abstract void RunTest(Action<NetCoreAppBuilder> customizer, string testAssemblyName, string appAsmVersion, string appFileVersion, bool appWins); public class SharedTestState : ComponentSharedTestStateBase { public SharedTestState() { } protected override void CustomizeDotNetWithNetCoreAppMicrosoftNETCoreApp(NetCoreAppBuilder builder) { builder .WithPackage(TestVersionsPackage, "1.0.0", b => b .WithAssemblyGroup(null, g => g .WithAsset(TestAssemblyWithNoVersions + ".dll") .WithAsset(TestAssemblyWithAssemblyVersion + ".dll", rf => rf.WithVersion("2.1.1.1", null)) .WithAsset(TestAssemblyWithFileVersion + ".dll", rf => rf.WithVersion(null, "3.2.2.2")) .WithAsset(TestAssemblyWithBothVersions + ".dll", rf => rf.WithVersion("2.1.1.1", "3.2.2.2")))); } public TestApp CreateTestFrameworkReferenceApp(Action<NetCoreAppBuilder> customizer) { TestApp testApp = FrameworkReferenceApp.Copy(); NetCoreAppBuilder builder = NetCoreAppBuilder.PortableForNETCoreApp(testApp); builder.WithProject(p => p .WithAssemblyGroup(null, g => g.WithMainAssembly())); customizer(builder); return builder.Build(testApp); } } } public class AppPerAssemblyVersionResolution : PerAssemblyVersionResolutionBase, IClassFixture<PerAssemblyVersionResolutionBase.SharedTestState> { public AppPerAssemblyVersionResolution(SharedTestState sharedState) : base(sharedState) { } protected override void RunTest(Action<NetCoreAppBuilder> customizer, string testAssemblyName, string appAsmVersion, string appFileVersion, bool appWins) { var app = SharedState.CreateTestFrameworkReferenceApp(b => b .WithPackage(TestVersionsPackage, "1.0.0", lib => lib .WithAssemblyGroup(null, g => g .WithAsset(testAssemblyName + ".dll", rf => rf .WithVersion(appAsmVersion, appFileVersion))))); string expectedTestAssemblyPath = Path.Combine(appWins ? app.Location : SharedState.DotNetWithNetCoreApp.GreatestVersionSharedFxPath, testAssemblyName + ".dll"); SharedState.DotNetWithNetCoreApp.Exec(app.AppDll) .EnableTracingAndCaptureOutputs() .Execute() .Should().Pass() .And.HaveResolvedAssembly(expectedTestAssemblyPath); } } public class ComponentPerAssemblyVersionResolution : PerAssemblyVersionResolutionBase, IClassFixture<PerAssemblyVersionResolutionBase.SharedTestState> { public ComponentPerAssemblyVersionResolution(SharedTestState sharedState) : base(sharedState) { } protected override void RunTest(Action<NetCoreAppBuilder> customizer, string testAssemblyName, string appAsmVersion, string appFileVersion, bool appWins) { var component = SharedState.CreateComponentWithNoDependencies(b => b .WithPackage(TestVersionsPackage, "1.0.0", lib => lib .WithAssemblyGroup(null, g => g .WithAsset(testAssemblyName + ".dll", rf => rf .WithVersion(appAsmVersion, appFileVersion))))); // For component dependency resolution, frameworks are not considered, so the assembly from the component always wins string expectedTestAssemblyPath = Path.Combine(component.Location, testAssemblyName + ".dll"); SharedState.RunComponentResolutionTest(component) .Should().Pass() .And.HaveSuccessfullyResolvedComponentDependencies() .And.HaveResolvedComponentDependencyAssembly($"{component.AppDll};{expectedTestAssemblyPath}"); } } }
// 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 Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.DependencyResolution { public abstract class PerAssemblyVersionResolutionBase : ComponentDependencyResolutionBase, IClassFixture<PerAssemblyVersionResolutionBase.SharedTestState> { protected readonly SharedTestState SharedState; public PerAssemblyVersionResolutionBase(SharedTestState fixture) { SharedState = fixture; } protected const string TestVersionsPackage = "Test.Versions.Package"; // The test framework above has 4 assemblies in it each with different set of assembly and file versions. // The version values are always (if present) // - assembly version: 2.1.1.1 // - file version: 3.2.2.2 private const string TestAssemblyWithNoVersions = "Test.Assembly.NoVersions"; private const string TestAssemblyWithAssemblyVersion = "Test.Assembly.AssemblyVersion"; private const string TestAssemblyWithFileVersion = "Test.Assembly.FileVersion"; private const string TestAssemblyWithBothVersions = "Test.Assembly.BothVersions"; [Theory] [InlineData(TestAssemblyWithBothVersions, null, null, false)] [InlineData(TestAssemblyWithBothVersions, "1.0.0.0", "1.0.0.0", false)] [InlineData(TestAssemblyWithBothVersions, "3.0.0.0", "4.0.0.0", true)] [InlineData(TestAssemblyWithBothVersions, "2.1.1.1", "1.0.0.0", false)] [InlineData(TestAssemblyWithBothVersions, "2.1.1.1", "3.3.0.0", true)] [InlineData(TestAssemblyWithBothVersions, "2.1.1.1", "3.2.2.2", false)] // Lower level framework always wins on equality (this is intentional) [InlineData(TestAssemblyWithBothVersions, null, "4.0.0.0", false)] // The one with version wins [InlineData(TestAssemblyWithBothVersions, null, "2.0.0.0", false)] // The one with version wins [InlineData(TestAssemblyWithBothVersions, "3.0.0.0", null, true)] [InlineData(TestAssemblyWithBothVersions, "2.1.1.1", null, false)] [InlineData(TestAssemblyWithNoVersions, null, null, false)] // No versions are treated as equal (so lower one wins) [InlineData(TestAssemblyWithNoVersions, "1.0.0.0", null, true)] [InlineData(TestAssemblyWithNoVersions, "1.0.0.0", "1.0.0.0", true)] [InlineData(TestAssemblyWithNoVersions, null, "1.0.0.0", true)] [InlineData(TestAssemblyWithAssemblyVersion, null, null, false)] [InlineData(TestAssemblyWithAssemblyVersion, "1.0.0.0", null, false)] [InlineData(TestAssemblyWithAssemblyVersion, null, "1.0.0.0", false)] [InlineData(TestAssemblyWithAssemblyVersion, "3.0.0.0", "1.0.0.0", true)] [InlineData(TestAssemblyWithAssemblyVersion, "2.1.1.1", null, false)] [InlineData(TestAssemblyWithAssemblyVersion, "2.1.1.1", "1.0.0.0", true)] [InlineData(TestAssemblyWithFileVersion, null, null, false)] [InlineData(TestAssemblyWithFileVersion, "1.0.0.0", null, true)] [InlineData(TestAssemblyWithFileVersion, null, "1.0.0.0", false)] [InlineData(TestAssemblyWithFileVersion, null, "4.0.0.0", true)] [InlineData(TestAssemblyWithFileVersion, null, "3.2.2.2", false)] public void AppWithSameAssemblyAsFramework(string testAssemblyName, string appAsmVersion, string appFileVersion, bool appWins) { RunTest(testAssemblyName, appAsmVersion, appFileVersion, appWins); } protected abstract void RunTest(string testAssemblyName, string appAsmVersion, string appFileVersion, bool appWins); public class SharedTestState : ComponentSharedTestStateBase { public SharedTestState() { } protected override void CustomizeDotNetWithNetCoreAppMicrosoftNETCoreApp(NetCoreAppBuilder builder) { builder .WithPackage(TestVersionsPackage, "1.0.0", b => b .WithAssemblyGroup(null, g => g .WithAsset(TestAssemblyWithNoVersions + ".dll") .WithAsset(TestAssemblyWithAssemblyVersion + ".dll", rf => rf.WithVersion("2.1.1.1", null)) .WithAsset(TestAssemblyWithFileVersion + ".dll", rf => rf.WithVersion(null, "3.2.2.2")) .WithAsset(TestAssemblyWithBothVersions + ".dll", rf => rf.WithVersion("2.1.1.1", "3.2.2.2")))); } public TestApp CreateTestFrameworkReferenceApp(Action<NetCoreAppBuilder> customizer) { TestApp testApp = FrameworkReferenceApp.Copy(); NetCoreAppBuilder builder = NetCoreAppBuilder.PortableForNETCoreApp(testApp); builder.WithProject(p => p .WithAssemblyGroup(null, g => g.WithMainAssembly())); customizer(builder); return builder.Build(testApp); } } } public class AppPerAssemblyVersionResolution : PerAssemblyVersionResolutionBase, IClassFixture<PerAssemblyVersionResolutionBase.SharedTestState> { public AppPerAssemblyVersionResolution(SharedTestState sharedState) : base(sharedState) { } protected override void RunTest(string testAssemblyName, string appAsmVersion, string appFileVersion, bool appWins) { var app = SharedState.CreateTestFrameworkReferenceApp(b => b .WithPackage(TestVersionsPackage, "1.0.0", lib => lib .WithAssemblyGroup(null, g => g .WithAsset(testAssemblyName + ".dll", rf => rf .WithVersion(appAsmVersion, appFileVersion))))); string expectedTestAssemblyPath = Path.Combine(appWins ? app.Location : SharedState.DotNetWithNetCoreApp.GreatestVersionSharedFxPath, testAssemblyName + ".dll"); SharedState.DotNetWithNetCoreApp.Exec(app.AppDll) .EnableTracingAndCaptureOutputs() .Execute() .Should().Pass() .And.HaveResolvedAssembly(expectedTestAssemblyPath); } } public class ComponentPerAssemblyVersionResolution : PerAssemblyVersionResolutionBase, IClassFixture<PerAssemblyVersionResolutionBase.SharedTestState> { public ComponentPerAssemblyVersionResolution(SharedTestState sharedState) : base(sharedState) { } protected override void RunTest(string testAssemblyName, string appAsmVersion, string appFileVersion, bool appWins) { var component = SharedState.CreateComponentWithNoDependencies(b => b .WithPackage(TestVersionsPackage, "1.0.0", lib => lib .WithAssemblyGroup(null, g => g .WithAsset(testAssemblyName + ".dll", rf => rf .WithVersion(appAsmVersion, appFileVersion))))); // For component dependency resolution, frameworks are not considered, so the assembly from the component always wins string expectedTestAssemblyPath = Path.Combine(component.Location, testAssemblyName + ".dll"); SharedState.RunComponentResolutionTest(component) .Should().Pass() .And.HaveSuccessfullyResolvedComponentDependencies() .And.HaveResolvedComponentDependencyAssembly($"{component.AppDll};{expectedTestAssemblyPath}"); } } }
1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/installer/tests/HostActivation.Tests/FrameworkResolution/FrameworkResolutionBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.DotNet.Cli.Build; using Microsoft.DotNet.Cli.Build.Framework; using System; using System.IO; using System.Linq; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.FrameworkResolution { public abstract partial class FrameworkResolutionBase { protected const string MicrosoftNETCoreApp = "Microsoft.NETCore.App"; public static class ResolvedFramework { public const string NotFound = "[not found]"; public const string FailedToReconcile = "[failed to reconcile]"; } protected CommandResult RunTest( DotNetCli dotnet, TestApp app, TestSettings settings, Action<CommandResult> resultAction = null, bool multiLevelLookup = false) { using (DotNetCliExtensions.DotNetCliCustomizer dotnetCustomizer = settings.DotnetCustomizer == null ? null : dotnet.Customize()) { settings.DotnetCustomizer?.Invoke(dotnetCustomizer); if (settings.RuntimeConfigCustomizer != null) { settings.RuntimeConfigCustomizer(RuntimeConfig.Path(app.RuntimeConfigJson)).Save(); } settings.WithCommandLine(app.AppDll); Command command = dotnet.Exec(settings.CommandLine.First(), settings.CommandLine.Skip(1).ToArray()); if (settings.WorkingDirectory != null) { command = command.WorkingDirectory(settings.WorkingDirectory); } CommandResult result = command .EnableTracingAndCaptureOutputs() .MultilevelLookup(multiLevelLookup) .Environment(settings.Environment) .Execute(); resultAction?.Invoke(result); return result; } } protected CommandResult RunSelfContainedTest( TestApp app, TestSettings settings) { if (settings.RuntimeConfigCustomizer != null) { settings.RuntimeConfigCustomizer(RuntimeConfig.Path(app.RuntimeConfigJson)).Save(); } settings.WithCommandLine(app.AppDll); Command command = Command.Create(app.AppExe, settings.CommandLine); if (settings.WorkingDirectory != null) { command = command.WorkingDirectory(settings.WorkingDirectory); } CommandResult result = command .EnableTracingAndCaptureOutputs() .Environment(settings.Environment) .Execute(); return result; } public class SharedTestStateBase : IDisposable { private readonly string _builtDotnet; private readonly RepoDirectoriesProvider _repoDirectories; private readonly string _baseDir; public SharedTestStateBase() { _builtDotnet = Path.Combine(TestArtifact.TestArtifactsPath, "sharedFrameworkPublish"); _repoDirectories = new RepoDirectoriesProvider(); string baseDir = Path.Combine(TestArtifact.TestArtifactsPath, "frameworkResolution"); _baseDir = SharedFramework.CalculateUniqueTestDirectory(baseDir); } public DotNetBuilder DotNet(string name) { return new DotNetBuilder(_baseDir, _builtDotnet, name); } public TestApp CreateFrameworkReferenceApp() { // Prepare the app mock - we're not going to run anything really, so we just need the basic files string testAppDir = Path.Combine(_baseDir, "FrameworkReferenceApp"); Directory.CreateDirectory(testAppDir); // ./FrameworkReferenceApp.dll File.WriteAllText(Path.Combine(testAppDir, "FrameworkReferenceApp.dll"), string.Empty); // ./FrameworkReferenceApp.runtimeconfig.json File.WriteAllText(Path.Combine(testAppDir, "FrameworkReferenceApp.runtimeconfig.json"), "{}"); return new TestApp(testAppDir); } public TestApp CreateSelfContainedAppWithMockHostPolicy() { string testAppDir = Path.Combine(_baseDir, "SelfContainedApp"); Directory.CreateDirectory(testAppDir); TestApp testApp = new TestApp(testAppDir); string hostFxrFileName = RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostfxr"); string hostPolicyFileName = RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostpolicy"); string mockHostPolicyFileName = RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("mockhostpolicy"); string appHostFileName = RuntimeInformationExtensions.GetExeFileNameForCurrentPlatform("apphost"); DotNetCli builtDotNetCli = new DotNetCli(_builtDotnet); // ./hostfxr - the product version File.Copy(builtDotNetCli.GreatestVersionHostFxrFilePath, Path.Combine(testAppDir, hostFxrFileName)); // ./hostpolicy - the mock File.Copy( Path.Combine(_repoDirectories.Artifacts, "corehost_test", mockHostPolicyFileName), Path.Combine(testAppDir, hostPolicyFileName)); // ./SelfContainedApp.dll File.WriteAllText(Path.Combine(testAppDir, "SelfContainedApp.dll"), string.Empty); // ./SelfContainedApp.runtimeconfig.json File.WriteAllText(Path.Combine(testAppDir, "SelfContainedApp.runtimeconfig.json"), "{}"); // ./SelfContainedApp.exe string selfContainedAppExePath = Path.Combine(testAppDir, RuntimeInformationExtensions.GetExeFileNameForCurrentPlatform("SelfContainedApp")); File.Copy( Path.Combine(_repoDirectories.HostArtifacts, appHostFileName), selfContainedAppExePath); AppHostExtensions.BindAppHost(selfContainedAppExePath); return testApp; } public void Dispose() { if (!TestArtifact.PreserveTestRuns() && Directory.Exists(_baseDir)) { Directory.Delete(_baseDir, true); } } } } }
// 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.Linq; using Microsoft.DotNet.Cli.Build; using Microsoft.DotNet.Cli.Build.Framework; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.FrameworkResolution { public abstract partial class FrameworkResolutionBase { protected const string MicrosoftNETCoreApp = "Microsoft.NETCore.App"; public static class ResolvedFramework { public const string NotFound = "[not found]"; public const string FailedToReconcile = "[failed to reconcile]"; } protected CommandResult RunTest( DotNetCli dotnet, TestApp app, TestSettings settings, Action<CommandResult> resultAction = null, bool? multiLevelLookup = false) { using (DotNetCliExtensions.DotNetCliCustomizer dotnetCustomizer = settings.DotnetCustomizer == null ? null : dotnet.Customize()) { settings.DotnetCustomizer?.Invoke(dotnetCustomizer); if (app is not null) { if (settings.RuntimeConfigCustomizer != null) { settings.RuntimeConfigCustomizer(RuntimeConfig.Path(app.RuntimeConfigJson)).Save(); } settings.WithCommandLine(app.AppDll); } Command command = dotnet.Exec(settings.CommandLine.First(), settings.CommandLine.Skip(1).ToArray()); if (settings.WorkingDirectory != null) { command = command.WorkingDirectory(settings.WorkingDirectory); } CommandResult result = command .EnableTracingAndCaptureOutputs() .MultilevelLookup(multiLevelLookup) .Environment(settings.Environment) .Execute(); resultAction?.Invoke(result); return result; } } protected CommandResult RunSelfContainedTest( TestApp app, TestSettings settings) { if (settings.RuntimeConfigCustomizer != null) { settings.RuntimeConfigCustomizer(RuntimeConfig.Path(app.RuntimeConfigJson)).Save(); } settings.WithCommandLine(app.AppDll); Command command = Command.Create(app.AppExe, settings.CommandLine); if (settings.WorkingDirectory != null) { command = command.WorkingDirectory(settings.WorkingDirectory); } CommandResult result = command .EnableTracingAndCaptureOutputs() .Environment(settings.Environment) .Execute(); return result; } public class SharedTestStateBase : IDisposable { private readonly string _builtDotnet; private readonly RepoDirectoriesProvider _repoDirectories; private readonly string _baseDir; public SharedTestStateBase() { _builtDotnet = Path.Combine(TestArtifact.TestArtifactsPath, "sharedFrameworkPublish"); _repoDirectories = new RepoDirectoriesProvider(); string baseDir = Path.Combine(TestArtifact.TestArtifactsPath, "frameworkResolution"); _baseDir = SharedFramework.CalculateUniqueTestDirectory(baseDir); } public DotNetBuilder DotNet(string name) { return new DotNetBuilder(_baseDir, _builtDotnet, name); } public TestApp CreateFrameworkReferenceApp() { // Prepare the app mock - we're not going to run anything really, so we just need the basic files string testAppDir = Path.Combine(_baseDir, "FrameworkReferenceApp"); Directory.CreateDirectory(testAppDir); // ./FrameworkReferenceApp.dll File.WriteAllText(Path.Combine(testAppDir, "FrameworkReferenceApp.dll"), string.Empty); // ./FrameworkReferenceApp.runtimeconfig.json File.WriteAllText(Path.Combine(testAppDir, "FrameworkReferenceApp.runtimeconfig.json"), "{}"); return new TestApp(testAppDir); } public TestApp CreateSelfContainedAppWithMockHostPolicy() { string testAppDir = Path.Combine(_baseDir, "SelfContainedApp"); Directory.CreateDirectory(testAppDir); TestApp testApp = new TestApp(testAppDir); string hostFxrFileName = RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostfxr"); string hostPolicyFileName = RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostpolicy"); string mockHostPolicyFileName = RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("mockhostpolicy"); string appHostFileName = RuntimeInformationExtensions.GetExeFileNameForCurrentPlatform("apphost"); DotNetCli builtDotNetCli = new DotNetCli(_builtDotnet); // ./hostfxr - the product version File.Copy(builtDotNetCli.GreatestVersionHostFxrFilePath, Path.Combine(testAppDir, hostFxrFileName)); // ./hostpolicy - the mock File.Copy( Path.Combine(_repoDirectories.Artifacts, "corehost_test", mockHostPolicyFileName), Path.Combine(testAppDir, hostPolicyFileName)); // ./SelfContainedApp.dll File.WriteAllText(Path.Combine(testAppDir, "SelfContainedApp.dll"), string.Empty); // ./SelfContainedApp.runtimeconfig.json File.WriteAllText(Path.Combine(testAppDir, "SelfContainedApp.runtimeconfig.json"), "{}"); // ./SelfContainedApp.exe string selfContainedAppExePath = Path.Combine(testAppDir, RuntimeInformationExtensions.GetExeFileNameForCurrentPlatform("SelfContainedApp")); File.Copy( Path.Combine(_repoDirectories.HostArtifacts, appHostFileName), selfContainedAppExePath); AppHostExtensions.BindAppHost(selfContainedAppExePath); return testApp; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (!TestArtifact.PreserveTestRuns() && Directory.Exists(_baseDir)) { Directory.Delete(_baseDir, true); } } } } } }
1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/installer/tests/HostActivation.Tests/FrameworkResolution/FrameworkResolutionCommandResultExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using FluentAssertions; using Microsoft.DotNet.Cli.Build.Framework; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.FrameworkResolution { internal static class FrameworkResolutionCommandResultExtensions { public static AndConstraint<CommandResultAssertions> HaveResolvedFramework(this CommandResultAssertions assertion, string name, string version) { return assertion.HaveStdOutContaining($"mock frameworks: {name} {version}"); } public static AndConstraint<CommandResultAssertions> ShouldHaveResolvedFramework(this CommandResult result, string resolvedFrameworkName, string resolvedFrameworkVersion) { return result.Should().Pass() .And.HaveResolvedFramework(resolvedFrameworkName, resolvedFrameworkVersion); } /// <summary> /// Verifies that the command result either passes with a resolved framework or fails with inability to find compatible framework version. /// </summary> /// <param name="result">The result to verify.</param> /// <param name="resolvedFrameworkName">The name of the framework to verify.</param> /// <param name="resolvedFrameworkVersion"> /// Either null in which case the command result is expected to fail and not find compatible framework version, /// or the framework versions in which case the command result is expected to succeed and resolve the specified framework version.</param> /// <returns>Constraint</returns> public static AndConstraint<CommandResultAssertions> ShouldHaveResolvedFrameworkOrFailToFind(this CommandResult result, string resolvedFrameworkName, string resolvedFrameworkVersion) { if (resolvedFrameworkName == null || resolvedFrameworkVersion == null || resolvedFrameworkVersion == FrameworkResolutionBase.ResolvedFramework.NotFound) { return result.ShouldFailToFindCompatibleFrameworkVersion(); } else { return result.ShouldHaveResolvedFramework(resolvedFrameworkName, resolvedFrameworkVersion); } } public static AndConstraint<CommandResultAssertions> DidNotFindCompatibleFrameworkVersion(this CommandResultAssertions assertion) { return assertion.HaveStdErrContaining("It was not possible to find any compatible framework version"); } public static AndConstraint<CommandResultAssertions> ShouldFailToFindCompatibleFrameworkVersion(this CommandResult result) { return result.Should().Fail() .And.DidNotFindCompatibleFrameworkVersion(); } public static AndConstraint<CommandResultAssertions> FailedToReconcileFrameworkReference( this CommandResultAssertions assertion, string frameworkName, string newVersion, string previousVersion) { return assertion.HaveStdErrMatching($".*The specified framework '{frameworkName}', version '{newVersion}', apply_patches=[0-1], version_compatibility_range=[^ ]* cannot roll-forward to the previously referenced version '{previousVersion}'.*"); } public static AndConstraint<CommandResultAssertions> ShouldHaveResolvedFrameworkOrFailedToReconcileFrameworkReference( this CommandResult result, string frameworkName, string resolvedVersion, string lowerVersion, string higherVersion) { if (resolvedVersion == null || resolvedVersion == FrameworkResolutionBase.ResolvedFramework.FailedToReconcile) { return result.Should().Fail().And.FailedToReconcileFrameworkReference(frameworkName, lowerVersion, higherVersion); } else { return result.ShouldHaveResolvedFramework(frameworkName, resolvedVersion); } } public static AndConstraint<CommandResultAssertions> ShouldHaveResolvedFrameworkOrFail( this CommandResult result, string frameworkName, string resolvedVersion, string lowerVersion, string higherVersion) { if (resolvedVersion == FrameworkResolutionBase.ResolvedFramework.FailedToReconcile) { return result.Should().Fail().And.FailedToReconcileFrameworkReference(frameworkName, lowerVersion, higherVersion); } else if (resolvedVersion == FrameworkResolutionBase.ResolvedFramework.NotFound) { return result.ShouldFailToFindCompatibleFrameworkVersion(); } else { return result.ShouldHaveResolvedFramework(frameworkName, resolvedVersion); } } public static AndConstraint<CommandResultAssertions> RestartedFrameworkResolution(this CommandResultAssertions assertion, string resolvedVersion, string newVersion) { return assertion.HaveStdErrContaining($"--- Restarting all framework resolution because the previously resolved framework 'Microsoft.NETCore.App', version '{resolvedVersion}' must be re-resolved with the new version '{newVersion}'"); } public static AndConstraint<CommandResultAssertions> DidNotRecognizeRollForwardValue(this CommandResultAssertions assertion, string value) { return assertion.HaveStdErrContaining($"Unrecognized roll forward setting value '{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.IO; using FluentAssertions; using Microsoft.DotNet.Cli.Build.Framework; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.FrameworkResolution { internal static class FrameworkResolutionCommandResultExtensions { public static AndConstraint<CommandResultAssertions> HaveResolvedFramework(this CommandResultAssertions assertion, string name, string version, string resolvedFrameworkBasePath = null) { string expectedOutput = $"mock frameworks: {name} {version}"; if (resolvedFrameworkBasePath is not null) expectedOutput += $" [path: {Path.Combine(resolvedFrameworkBasePath, "shared", name, version)}]"; return assertion.HaveStdOutContaining(expectedOutput); } public static AndConstraint<CommandResultAssertions> ShouldHaveResolvedFramework(this CommandResult result, string resolvedFrameworkName, string resolvedFrameworkVersion, string resolvedFrameworkBasePath = null) { return result.Should().Pass() .And.HaveResolvedFramework(resolvedFrameworkName, resolvedFrameworkVersion, resolvedFrameworkBasePath); } /// <summary> /// Verifies that the command result either passes with a resolved framework or fails with inability to find compatible framework version. /// </summary> /// <param name="result">The result to verify.</param> /// <param name="resolvedFrameworkName">The name of the framework to verify.</param> /// <param name="resolvedFrameworkVersion"> /// Either null in which case the command result is expected to fail and not find compatible framework version, /// or the framework versions in which case the command result is expected to succeed and resolve the specified framework version.</param> /// <returns>Constraint</returns> public static AndConstraint<CommandResultAssertions> ShouldHaveResolvedFrameworkOrFailToFind(this CommandResult result, string resolvedFrameworkName, string resolvedFrameworkVersion, string resolvedFrameworkBasePath = null) { if (resolvedFrameworkName == null || resolvedFrameworkVersion == null || resolvedFrameworkVersion == FrameworkResolutionBase.ResolvedFramework.NotFound) { return result.ShouldFailToFindCompatibleFrameworkVersion(); } else { return result.ShouldHaveResolvedFramework(resolvedFrameworkName, resolvedFrameworkVersion, resolvedFrameworkBasePath); } } public static AndConstraint<CommandResultAssertions> DidNotFindCompatibleFrameworkVersion(this CommandResultAssertions assertion) { return assertion.HaveStdErrContaining("It was not possible to find any compatible framework version"); } public static AndConstraint<CommandResultAssertions> ShouldFailToFindCompatibleFrameworkVersion(this CommandResult result) { return result.Should().Fail() .And.DidNotFindCompatibleFrameworkVersion(); } public static AndConstraint<CommandResultAssertions> FailedToReconcileFrameworkReference( this CommandResultAssertions assertion, string frameworkName, string newVersion, string previousVersion) { return assertion.HaveStdErrMatching($".*The specified framework '{frameworkName}', version '{newVersion}', apply_patches=[0-1], version_compatibility_range=[^ ]* cannot roll-forward to the previously referenced version '{previousVersion}'.*"); } public static AndConstraint<CommandResultAssertions> ShouldHaveResolvedFrameworkOrFailedToReconcileFrameworkReference( this CommandResult result, string frameworkName, string resolvedVersion, string lowerVersion, string higherVersion) { if (resolvedVersion == null || resolvedVersion == FrameworkResolutionBase.ResolvedFramework.FailedToReconcile) { return result.Should().Fail().And.FailedToReconcileFrameworkReference(frameworkName, lowerVersion, higherVersion); } else { return result.ShouldHaveResolvedFramework(frameworkName, resolvedVersion); } } public static AndConstraint<CommandResultAssertions> ShouldHaveResolvedFrameworkOrFail( this CommandResult result, string frameworkName, string resolvedVersion, string lowerVersion, string higherVersion) { if (resolvedVersion == FrameworkResolutionBase.ResolvedFramework.FailedToReconcile) { return result.Should().Fail().And.FailedToReconcileFrameworkReference(frameworkName, lowerVersion, higherVersion); } else if (resolvedVersion == FrameworkResolutionBase.ResolvedFramework.NotFound) { return result.ShouldFailToFindCompatibleFrameworkVersion(); } else { return result.ShouldHaveResolvedFramework(frameworkName, resolvedVersion); } } public static AndConstraint<CommandResultAssertions> RestartedFrameworkResolution(this CommandResultAssertions assertion, string resolvedVersion, string newVersion) { return assertion.HaveStdErrContaining($"--- Restarting all framework resolution because the previously resolved framework 'Microsoft.NETCore.App', version '{resolvedVersion}' must be re-resolved with the new version '{newVersion}'"); } public static AndConstraint<CommandResultAssertions> DidNotRecognizeRollForwardValue(this CommandResultAssertions assertion, string value) { return assertion.HaveStdErrContaining($"Unrecognized roll forward setting value '{value}'."); } } }
1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/installer/tests/HostActivation.Tests/FrameworkResolution/MultipleHives.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.DotNet.Cli.Build; using Microsoft.DotNet.Cli.Build.Framework; using System; using System.Runtime.InteropServices; using Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.FrameworkResolution { public class MultipleHives : FrameworkResolutionBase, IClassFixture<MultipleHives.SharedTestState> { private SharedTestState SharedState { get; } public MultipleHives(SharedTestState sharedState) { SharedState = sharedState; } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Multiple hives are only supported on Windows. public void FrameworkHiveSelection_GlobalHiveWithBetterMatch() { RunTest( runtimeConfig => runtimeConfig .WithFramework(MicrosoftNETCoreApp, "5.0.0")) .ShouldHaveResolvedFramework(MicrosoftNETCoreApp, "5.1.2"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Multiple hives are only supported on Windows. public void FrameworkHiveSelection_MainHiveWithBetterMatch() { RunTest( runtimeConfig => runtimeConfig .WithFramework(MicrosoftNETCoreApp, "6.0.0")) .ShouldHaveResolvedFramework(MicrosoftNETCoreApp, "6.1.2"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Multiple hives are only supported on Windows. public void FrameworkHiveSelection_CurrentDirectoryIsIgnored() { RunTest( SharedState.DotNetMainHive, SharedState.FrameworkReferenceApp, new TestSettings() .WithRuntimeConfigCustomizer(runtimeConfig => runtimeConfig .WithFramework(MicrosoftNETCoreApp, "5.0.0")) .WithWorkingDirectory(SharedState.DotNetCurrentHive.BinPath)) .ShouldHaveResolvedFramework(MicrosoftNETCoreApp, "5.2.0"); } private CommandResult RunTest(Func<RuntimeConfig, RuntimeConfig> runtimeConfig) { using (TestOnlyProductBehavior.Enable(SharedState.DotNetMainHive.GreatestVersionHostFxrFilePath)) { return RunTest( SharedState.DotNetMainHive, SharedState.FrameworkReferenceApp, new TestSettings() .WithRuntimeConfigCustomizer(runtimeConfig) .WithEnvironment(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, SharedState.DotNetGlobalHive.BinPath) .WithEnvironment( // Redirect the default install location to an invalid location so that a machine-wide install is not used Constants.TestOnlyEnvironmentVariables.DefaultInstallPath, System.IO.Path.Combine(SharedState.DotNetMainHive.BinPath, "invalid")), // Must enable multi-level lookup otherwise multiple hives are not enabled multiLevelLookup: true); } } public class SharedTestState : SharedTestStateBase { public TestApp FrameworkReferenceApp { get; } public DotNetCli DotNetMainHive { get; } public DotNetCli DotNetGlobalHive { get; } public DotNetCli DotNetCurrentHive { get; } public SharedTestState() { DotNetMainHive = DotNet("MainHive") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("5.2.0") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("6.1.2") .Build(); DotNetGlobalHive = DotNet("GlobalHive") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("5.1.2") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("6.2.0") .Build(); DotNetCurrentHive = DotNet("CurrentHive") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("5.1.0") .Build(); FrameworkReferenceApp = CreateFrameworkReferenceApp(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DotNet.Cli.Build; using Microsoft.DotNet.Cli.Build.Framework; using Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.FrameworkResolution { public class MultipleHives : FrameworkResolutionBase, IClassFixture<MultipleHives.SharedTestState> { private SharedTestState SharedState { get; } public MultipleHives(SharedTestState sharedState) { SharedState = sharedState; } [Theory] // MLL where global hive has a better match [InlineData("5.0.0", "net5.0", true, "5.1.2")] [InlineData("5.0.0", "net5.0", null, "5.1.2")] // MLL is on by default, so same as true [InlineData("5.0.0", "net5.0", false, "5.2.0")] // No global hive allowed // MLL (where global hive has better match) with various TFMs [InlineData("5.0.0", "netcoreapp3.0", true, "5.1.2")] [InlineData("5.0.0", "netcoreapp3.0", null, "5.1.2")] [InlineData("5.0.0", "netcoreapp3.0", false, "5.2.0")] [InlineData("5.0.0", "netcoreapp3.1", true, "5.1.2")] [InlineData("5.0.0", "netcoreapp3.1", null, "5.1.2")] [InlineData("5.0.0", "netcoreapp3.1", false, "5.2.0")] [InlineData("5.0.0", "net6.0", true, "5.1.2")] [InlineData("5.0.0", "net6.0", null, "5.1.2")] [InlineData("5.0.0", "net6.0", false, "5.2.0")] [InlineData("7.0.0", "net7.0", true, "7.0.1")] [InlineData("7.0.0", "net7.0", null, "7.0.1")] [InlineData("7.0.0", "net7.0", false, "7.1.2")] [InlineData("7.0.0", "net8.0", true, "7.0.1")] [InlineData("7.0.0", "net8.0", null, "7.0.1")] [InlineData("7.0.0", "net8.0", false, "7.1.2")] // MLL where main hive has a better match [InlineData("6.0.0", "net6.0", true, "6.1.4")] // Global hive with better version (higher patch) [InlineData("6.0.0", "net6.0", null, "6.1.4")] // MLL is on by default, so same as true [InlineData("6.0.0", "net6.0", false, "6.1.3")] // No globla hive, so the main hive version is picked public void FrameworkHiveSelection(string requestedVersion, string tfm, bool? multiLevelLookup, string resolvedVersion) { // Multi-level lookup is only supported on Windows. if (!OperatingSystem.IsWindows() && multiLevelLookup != false) return; RunTest( runtimeConfig => runtimeConfig .WithTfm(tfm) .WithFramework(MicrosoftNETCoreApp, requestedVersion), multiLevelLookup) .ShouldHaveResolvedFramework(MicrosoftNETCoreApp, resolvedVersion); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Multiple hives are only supported on Windows. public void FrameworkHiveSelection_CurrentDirectoryIsIgnored() { RunTest(new TestSettings() .WithRuntimeConfigCustomizer(runtimeConfig => runtimeConfig .WithTfm(Constants.Tfm.Net5) .WithFramework(MicrosoftNETCoreApp, "5.0.0")) .WithWorkingDirectory(SharedState.DotNetCurrentHive.BinPath), multiLevelLookup: true) .ShouldHaveResolvedFramework(MicrosoftNETCoreApp, "5.1.2"); } [Theory] [InlineData("6.1.2", "net6.0", true, "6.1.2", false)] // No roll forward if --fx-version is used [InlineData("6.1.2", "net6.0", null, "6.1.2", false)] [InlineData("6.1.2", "net6.0", false, "6.1.2", false)] [InlineData("6.1.2", "net7.0", true, "6.1.2", false)] [InlineData("6.1.4", "net6.0", true, "6.1.4", true)] [InlineData("6.1.4", "net6.0", null, "6.1.4", true)] [InlineData("6.1.4", "net6.0", false, ResolvedFramework.NotFound, false)] [InlineData("6.1.4", "net7.0", true, "6.1.4", true)] [InlineData("7.1.2", "net6.0", true, "7.1.2", false)] // 7.1.2 is in both main and global hives - the main should always win with exact match [InlineData("7.1.2", "net6.0", null, "7.1.2", false)] [InlineData("7.1.2", "net6.0", false, "7.1.2", false)] [InlineData("7.1.2", "net7.0", true, "7.1.2", false)] public void FxVersionCLI(string fxVersion, string tfm, bool? multiLevelLookup, string resolvedVersion, bool fromGlobalHive) { // Multi-level lookup is only supported on Windows. if (!OperatingSystem.IsWindows() && multiLevelLookup != false) return; RunTest( new TestSettings() .WithRuntimeConfigCustomizer( runtimeConfig => runtimeConfig .WithTfm(tfm) .WithFramework(MicrosoftNETCoreApp, "4.0.0")) .WithCommandLine(Constants.FxVersion.CommandLineArgument, fxVersion), multiLevelLookup) .ShouldHaveResolvedFrameworkOrFailToFind(MicrosoftNETCoreApp, resolvedVersion, fromGlobalHive ? SharedState.DotNetGlobalHive.BinPath : SharedState.DotNetMainHive.BinPath); } private record struct FrameworkInfo(string Name, string Version, int Level, string Path); private List<FrameworkInfo> GetExpectedFrameworks(bool? multiLevelLookup) { // The runtimes should be ordered by version number List<FrameworkInfo> expectedList = new(); expectedList.Add(new FrameworkInfo(MicrosoftNETCoreApp, "5.2.0", 1, SharedState.DotNetMainHive.BinPath)); expectedList.Add(new FrameworkInfo(MicrosoftNETCoreApp, "6.1.2", 1, SharedState.DotNetMainHive.BinPath)); expectedList.Add(new FrameworkInfo(MicrosoftNETCoreApp, "6.1.3", 1, SharedState.DotNetMainHive.BinPath)); expectedList.Add(new FrameworkInfo(MicrosoftNETCoreApp, "7.1.2", 1, SharedState.DotNetMainHive.BinPath)); if (multiLevelLookup is null || multiLevelLookup == true) { expectedList.Add(new FrameworkInfo(MicrosoftNETCoreApp, "5.1.2", 2, SharedState.DotNetGlobalHive.BinPath)); expectedList.Add(new FrameworkInfo(MicrosoftNETCoreApp, "6.1.4", 2, SharedState.DotNetGlobalHive.BinPath)); expectedList.Add(new FrameworkInfo(MicrosoftNETCoreApp, "6.2.0", 2, SharedState.DotNetGlobalHive.BinPath)); expectedList.Add(new FrameworkInfo(MicrosoftNETCoreApp, "7.0.1", 2, SharedState.DotNetGlobalHive.BinPath)); expectedList.Add(new FrameworkInfo(MicrosoftNETCoreApp, "7.1.2", 2, SharedState.DotNetGlobalHive.BinPath)); } expectedList.Sort((a, b) => { int result = a.Name.CompareTo(b.Name); if (result != 0) return result; if (!Version.TryParse(a.Version, out var aVersion)) return -1; if (!Version.TryParse(b.Version, out var bVersion)) return 1; result = aVersion.CompareTo(bVersion); if (result != 0) return result; return b.Level.CompareTo(a.Level); }); return expectedList; } [Theory] [InlineData(true)] [InlineData(null)] [InlineData(false)] public void ListRuntimes(bool? multiLevelLookup) { // Multi-level lookup is only supported on Windows. if (!OperatingSystem.IsWindows() && multiLevelLookup != false) return; string expectedOutput = string.Join( string.Empty, GetExpectedFrameworks(multiLevelLookup) .Select(t => $"{MicrosoftNETCoreApp} {t.Version} [{Path.Combine(t.Path, "shared", MicrosoftNETCoreApp)}]{Environment.NewLine}")); // !!IMPORTANT!!: This test verifies the exact match of the entire output of the command (not a substring!) // This is important as the output of --list-runtimes is considered machine readable and thus must not change even in a minor way (unintentionally) RunTest( new TestSettings().WithCommandLine("--list-runtimes"), multiLevelLookup, testApp: null) .Should().HaveStdOut(expectedOutput); } [Theory] [InlineData(true)] [InlineData(null)] [InlineData(false)] public void DotnetInfo(bool? multiLevelLookup) { // Multi-level lookup is only supported on Windows. if (!OperatingSystem.IsWindows() && multiLevelLookup != false) return; string expectedOutput = $".NET runtimes installed:{Environment.NewLine}" + string.Join(string.Empty, GetExpectedFrameworks(multiLevelLookup) .Select(t => $" {MicrosoftNETCoreApp} {t.Version} [{Path.Combine(t.Path, "shared", MicrosoftNETCoreApp)}]{Environment.NewLine}")); RunTest( new TestSettings().WithCommandLine("--info"), multiLevelLookup, testApp: null) .Should().HaveStdOutContaining(expectedOutput); } [Theory] [InlineData("net5.0", true)] [InlineData("net5.0", null)] [InlineData("net5.0", false)] [InlineData("net7.0", true)] [InlineData("net7.0", null)] [InlineData("net7.0", false)] public void FrameworkResolutionError(string tfm, bool? multiLevelLookup) { // Multi-level lookup is only supported on Windows. if (!OperatingSystem.IsWindows() && multiLevelLookup != false) return; string expectedOutput = $"The following frameworks were found:{Environment.NewLine}" + string.Join(string.Empty, GetExpectedFrameworks(multiLevelLookup) .Select(t => $" {t.Version} at [{Path.Combine(t.Path, "shared", MicrosoftNETCoreApp)}]{Environment.NewLine}")); RunTest( runtimeConfig => runtimeConfig .WithTfm(tfm) .WithFramework(MicrosoftNETCoreApp, "9999.9.9"), multiLevelLookup) .Should().Fail() .And.HaveStdErrContaining(expectedOutput); } private CommandResult RunTest(Func<RuntimeConfig, RuntimeConfig> runtimeConfig, bool? multiLevelLookup = true) => RunTest(new TestSettings().WithRuntimeConfigCustomizer(runtimeConfig), multiLevelLookup); private CommandResult RunTest(TestSettings testSettings, bool? multiLevelLookup) => RunTest(testSettings, multiLevelLookup, SharedState.FrameworkReferenceApp); private CommandResult RunTest(TestSettings testSettings, bool? multiLevelLookup, TestApp testApp) { return RunTest( SharedState.DotNetMainHive, testApp, testSettings .WithEnvironment(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, SharedState.DotNetGlobalHive.BinPath) .WithEnvironment( // Redirect the default install location to an invalid location so that a machine-wide install is not used Constants.TestOnlyEnvironmentVariables.DefaultInstallPath, System.IO.Path.Combine(SharedState.DotNetMainHive.BinPath, "invalid")), // Must enable multi-level lookup otherwise multiple hives are not enabled multiLevelLookup: multiLevelLookup); } public class SharedTestState : SharedTestStateBase { public TestApp FrameworkReferenceApp { get; } public DotNetCli DotNetMainHive { get; } public DotNetCli DotNetGlobalHive { get; } public DotNetCli DotNetCurrentHive { get; } private readonly IDisposable _testOnlyProductBehaviorScope; public SharedTestState() { DotNetMainHive = DotNet("MainHive") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("5.2.0") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("6.1.2") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("6.1.3") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("7.1.2") .Build(); DotNetGlobalHive = DotNet("GlobalHive") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("5.1.2") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("6.1.4") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("6.2.0") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("7.0.1") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("7.1.2") .Build(); DotNetCurrentHive = DotNet("CurrentHive") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("5.1.0") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("7.3.0") .Build(); FrameworkReferenceApp = CreateFrameworkReferenceApp(); _testOnlyProductBehaviorScope = TestOnlyProductBehavior.Enable(DotNetMainHive.GreatestVersionHostFxrFilePath); } protected override void Dispose(bool disposing) { if (disposing) { _testOnlyProductBehaviorScope.Dispose(); } base.Dispose(disposing); } } } }
1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/installer/tests/HostActivation.Tests/MultilevelSDKLookup.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.DotNet.Cli.Build; using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation { public class MultilevelSDKLookup : IDisposable { private static readonly IDictionary<string, string> s_DefaultEnvironment = new Dictionary<string, string>() { {"COREHOST_TRACE", "1" }, // The SDK being used may be crossgen'd for a different architecture than we are building for. // Turn off ready to run, so an x64 crossgen'd SDK can be loaded in an x86 process. {"COMPlus_ReadyToRun", "0" }, }; private readonly RepoDirectoriesProvider RepoDirectories; private readonly DotNetCli DotNet; private readonly string _currentWorkingDir; private readonly string _userDir; private readonly string _exeDir; private readonly string _regDir; private readonly string _cwdSdkBaseDir; private readonly string _userSdkBaseDir; private readonly string _exeSdkBaseDir; private readonly string _regSdkBaseDir; private readonly string _exeSelectedMessage; private readonly string _regSelectedMessage; private readonly string _multilevelDir; private const string _dotnetSdkDllMessageTerminator = "dotnet.dll]"; private readonly IDisposable _testOnlyProductBehaviorMarker; public MultilevelSDKLookup() { // The dotnetMultilevelSDKLookup dir will contain some folders and files that will be // necessary to perform the tests string baseMultilevelDir = Path.Combine(TestArtifact.TestArtifactsPath, "dotnetMultilevelSDKLookup"); _multilevelDir = SharedFramework.CalculateUniqueTestDirectory(baseMultilevelDir); // The tested locations will be the cwd, user folder, exe dir, and registered directory. cwd and user are no longer supported. // All dirs will be placed inside the multilevel folder _currentWorkingDir = Path.Combine(_multilevelDir, "cwd"); _userDir = Path.Combine(_multilevelDir, "user"); _exeDir = Path.Combine(_multilevelDir, "exe"); _regDir = Path.Combine(_multilevelDir, "reg"); DotNet = new DotNetBuilder(_multilevelDir, Path.Combine(TestArtifact.TestArtifactsPath, "sharedFrameworkPublish"), "exe") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("9999.0.0") .Build(); RepoDirectories = new RepoDirectoriesProvider(builtDotnet: DotNet.BinPath); // SdkBaseDirs contain all available version folders _cwdSdkBaseDir = Path.Combine(_currentWorkingDir, "sdk"); _userSdkBaseDir = Path.Combine(_userDir, ".dotnet", RepoDirectories.BuildArchitecture, "sdk"); _exeSdkBaseDir = Path.Combine(_exeDir, "sdk"); _regSdkBaseDir = Path.Combine(_regDir, "sdk"); // Create directories Directory.CreateDirectory(_cwdSdkBaseDir); Directory.CreateDirectory(_userSdkBaseDir); Directory.CreateDirectory(_exeSdkBaseDir); Directory.CreateDirectory(_regSdkBaseDir); // Trace messages used to identify from which folder the SDK was picked _exeSelectedMessage = $"Using .NET SDK dll=[{_exeSdkBaseDir}"; _regSelectedMessage = $"Using .NET SDK dll=[{_regSdkBaseDir}"; _testOnlyProductBehaviorMarker = TestOnlyProductBehavior.Enable(DotNet.GreatestVersionHostFxrFilePath); } public void Dispose() { _testOnlyProductBehaviorMarker?.Dispose(); if (!TestArtifact.PreserveTestRuns()) { Directory.Delete(_multilevelDir, true); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Multi-level lookup is only supported on Windows. public void SdkMultilevelLookup_Global_Json_Single_Digit_Patch_Rollup() { // Set specified SDK version = 9999.3.4-global-dummy SetGlobalJsonVersion("SingleDigit-global.json"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // User: empty // Exe: empty // Reg: empty // Expected: no compatible version and a specific error messages DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.4.1", "9999.3.4-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy // Reg: empty // Expected: no compatible version and a specific error message DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.3"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy // Reg: 9999.3.3 // Expected: no compatible version and a specific error message DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.4"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.4 // Reg: 9999.3.3 // Expected: 9999.3.4 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.4", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.5-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.4 // Reg: 9999.3.3, 9999.3.5-dummy // Expected: 9999.3.5-dummy from reg dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.3.5-dummy", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.600"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.4, 9999.3.600 // Reg: 9999.3.3, 9999.3.5-dummy // Expected: 9999.3.5-dummy from reg dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.3.5-dummy", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.4-global-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // User: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.4, 9999.3.600, 9999.3.4-global-dummy // Reg: 9999.3.3, 9999.3.5-dummy // Expected: 9999.3.4-global-dummy from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.4-global-dummy", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions DotNet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("9999.3.4-dummy") .And.HaveStdOutContaining("9999.3.4-global-dummy") .And.HaveStdOutContaining("9999.4.1") .And.HaveStdOutContaining("9999.3.3") .And.HaveStdOutContaining("9999.3.4") .And.HaveStdOutContaining("9999.3.600") .And.HaveStdOutContaining("9999.3.5-dummy"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Multi-level lookup is only supported on Windows. public void SdkMultilevelLookup_Global_Json_Two_Part_Patch_Rollup() { // Set specified SDK version = 9999.3.304-global-dummy SetGlobalJsonVersion("TwoPart-global.json"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // User: empty // Exe: empty // Reg: empty // Expected: no compatible version and a specific error messages DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.57", "9999.3.4-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // User: empty // Exe: empty // Reg: 9999.3.57, 9999.3.4-dummy // Expected: no compatible version and a specific error message DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.300", "9999.7.304-global-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // User: empty // Exe: 9999.3.300, 9999.7.304-global-dummy // Reg: 9999.3.57, 9999.3.4-dummy // Expected: no compatible version and a specific error message DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.304"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // User: empty // Exe: 9999.3.300, 9999.7.304-global-dummy // Reg: 9999.3.57, 9999.3.4-dummy, 9999.3.304 // Expected: 9999.3.304 from reg dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.3.304", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.399", "9999.3.399-dummy", "9999.3.400"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // User: empty // Exe: 9999.3.300, 9999.7.304-global-dummy, 9999.3.399, 9999.3.399-dummy, 9999.3.400 // Reg: 9999.3.57, 9999.3.4-dummy, 9999.3.304 // Expected: 9999.3.399 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.399", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.2400", "9999.3.3004"); AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.2400", "9999.3.3004"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // User: empty // Exe: 9999.3.300, 9999.7.304-global-dummy, 9999.3.399, 9999.3.399-dummy, 9999.3.400, 9999.3.2400, 9999.3.3004 // Reg: 9999.3.57, 9999.3.4-dummy, 9999.3.304, 9999.3.2400, 9999.3.3004 // Expected: 9999.3.399 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.399", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.304-global-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // User: empty // Exe: 9999.3.300, 9999.7.304-global-dummy, 9999.3.399, 9999.3.399-dummy, 9999.3.400, 9999.3.2400, 9999.3.3004 // Reg: 9999.3.57, 9999.3.4-dummy, 9999.3.304, 9999.3.2400, 9999.3.3004, 9999.3.304-global-dummy // Expected: 9999.3.304-global-dummy from reg dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.3.304-global-dummy", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions DotNet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("9999.3.57") .And.HaveStdOutContaining("9999.3.4-dummy") .And.HaveStdOutContaining("9999.3.300") .And.HaveStdOutContaining("9999.7.304-global-dummy") .And.HaveStdOutContaining("9999.3.399") .And.HaveStdOutContaining("9999.3.399-dummy") .And.HaveStdOutContaining("9999.3.400") .And.HaveStdOutContaining("9999.3.2400") .And.HaveStdOutContaining("9999.3.3004") .And.HaveStdOutContaining("9999.3.304") .And.HaveStdOutContaining("9999.3.304-global-dummy"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Multi-level lookup is only supported on Windows. public void SdkMultilevelLookup_Precedential_Order() { WriteEmptyGlobalJson(); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.0.4"); // Specified SDK version: none // Cwd: empty // User: empty // Exe: empty // Reg: 9999.0.4 // Expected: 9999.0.4 from reg dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.4", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.4"); // Specified SDK version: none // Cwd: empty // User: empty // Exe: 9999.0.4 // Reg: 9999.0.4 // Expected: 9999.0.4 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.4", _dotnetSdkDllMessageTerminator)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Multi-level lookup is only supported on Windows. public void SdkMultilevelLookup_RegistryAccess() { // The purpose of this test is to verify that the product uses correct code to access // the registry to extract the path to search for SDKs. // Most of our tests rely on a shortcut which is to set _DOTNET_TEST_SDK_SELF_REGISTERED_DIR env variable // which will skip the registry reading code in the product and simply use the specified value. // This test is different since it actually runs the registry reading code. // Normally the reg key the product uses is in HKEY_LOCAL_MACHINE which is only writable as admin // so we would require the tests to run as admin to modify that key (and it may introduce races with other code running on the machine). // So instead the tests use _DOTENT_TEST_SDK_REGISTRY_PATH env variable to point to the produce to use // different registry key, inside the HKEY_CURRENT_USER hive which is writable without admin. // Note that the test creates a unique key (based on PID) for every run, to avoid collisions between parallel running tests. WriteEmptyGlobalJson(); using (var registeredInstallLocationOverride = new RegisteredInstallLocationOverride(DotNet.GreatestVersionHostFxrFilePath)) { registeredInstallLocationOverride.SetInstallLocation(new (string, string)[] { (RepoDirectories.BuildArchitecture, _regDir) }); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.0.4"); // Specified SDK version: none // Cwd: empty // User: empty // Exe: empty // Reg: 9999.0.4 // Expected: 9999.0.4 from reg dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .ApplyRegisteredInstallLocationOverride(registeredInstallLocationOverride) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.4", _dotnetSdkDllMessageTerminator)); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Multi-level lookup is only supported on Windows. public void SdkMultilevelLookup_Must_Pick_The_Highest_Semantic_Version() { WriteEmptyGlobalJson(); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.0.0", "9999.0.3-dummy"); // Specified SDK version: none // Cwd: empty // User: empty // Exe: empty // Reg: 9999.0.0, 9999.0.3-dummy // Expected: 9999.0.3-dummy from reg dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.3-dummy", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.3"); // Specified SDK version: none // Cwd: empty // User: empty // Exe: 9999.0.3 // Reg: 9999.0.0, 9999.0.3-dummy // Expected: 9999.0.3 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.3", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_userSdkBaseDir, "9999.0.200"); AddAvailableSdkVersions(_cwdSdkBaseDir, "10000.0.0"); AddAvailableSdkVersions(_regSdkBaseDir, "9999.0.100"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.3 // Reg: 9999.0.0, 9999.0.3-dummy, 9999.0.100 // Expected: 9999.0.100 from reg dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.100", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.80"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.3, 9999.0.80 // Reg: 9999.0.0, 9999.0.3-dummy, 9999.0.100 // Expected: 9999.0.100 from reg dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.100", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.5500000"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.3, 9999.0.80, 9999.0.5500000 // Reg: 9999.0.0, 9999.0.3-dummy, 9999.0.100 // Expected: 9999.0.5500000 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.5500000", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.0.52000000"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.3, 9999.0.80, 9999.0.5500000 // Reg: 9999.0.0, 9999.0.3-dummy, 9999.0.100, 9999.0.52000000 // Expected: 9999.0.52000000 from reg dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.52000000", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions DotNet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "1") .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("9999.0.0") .And.HaveStdOutContaining("9999.0.3-dummy") .And.HaveStdOutContaining("9999.0.3") .And.HaveStdOutContaining("9999.0.100") .And.HaveStdOutContaining("9999.0.80") .And.HaveStdOutContaining("9999.0.5500000") .And.HaveStdOutContaining("9999.0.52000000"); } // This method adds a list of new sdk version folders in the specified directory. // The actual contents are 'fake' and the mininum required for SDK discovery. // The dotnet.runtimeconfig.json created uses a dummy framework version (9999.0.0) private void AddAvailableSdkVersions(string sdkBaseDir, params string[] availableVersions) { string dummyRuntimeConfig = Path.Combine(RepoDirectories.TestAssetsFolder, "TestUtils", "SDKLookup", "dotnet.runtimeconfig.json"); foreach (string version in availableVersions) { string newSdkDir = Path.Combine(sdkBaseDir, version); Directory.CreateDirectory(newSdkDir); // ./dotnet.dll File.WriteAllText(Path.Combine(newSdkDir, "dotnet.dll"), string.Empty); // ./dotnet.runtimeconfig.json string runtimeConfig = Path.Combine(newSdkDir, "dotnet.runtimeconfig.json"); File.Copy(dummyRuntimeConfig, runtimeConfig, true); } } // Put a global.json file in the cwd in order to specify a CLI private void SetGlobalJsonVersion(string globalJsonFileName) { string destFile = Path.Combine(_currentWorkingDir, "global.json"); string srcFile = Path.Combine(RepoDirectories.TestAssetsFolder, "TestUtils", "SDKLookup", globalJsonFileName); File.Copy(srcFile, destFile, true); } private void WriteGlobalJson(string contents) { File.WriteAllText(Path.Combine(_currentWorkingDir, "global.json"), contents); } private void WriteEmptyGlobalJson() => WriteGlobalJson("{}"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.DotNet.Cli.Build; using Microsoft.DotNet.Cli.Build.Framework; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation { public class MultilevelSDKLookup : IDisposable { private readonly RepoDirectoriesProvider RepoDirectories; private readonly DotNetCli DotNet; private readonly string _currentWorkingDir; private readonly string _exeDir; private readonly string _regDir; private readonly string _cwdSdkBaseDir; private readonly string _exeSdkBaseDir; private readonly string _regSdkBaseDir; private readonly string _exeSelectedMessage; private readonly string _regSelectedMessage; private readonly string _multilevelDir; private const string _dotnetSdkDllMessageTerminator = "dotnet.dll]"; private readonly IDisposable _testOnlyProductBehaviorMarker; public MultilevelSDKLookup() { // The dotnetMultilevelSDKLookup dir will contain some folders and files that will be // necessary to perform the tests string baseMultilevelDir = Path.Combine(TestArtifact.TestArtifactsPath, "dotnetMultilevelSDKLookup"); _multilevelDir = SharedFramework.CalculateUniqueTestDirectory(baseMultilevelDir); // The tested locations will be the cwd, exe dir, and registered directory. cwd is no longer supported. // All dirs will be placed inside the multilevel folder _currentWorkingDir = Path.Combine(_multilevelDir, "cwd"); _exeDir = Path.Combine(_multilevelDir, "exe"); _regDir = Path.Combine(_multilevelDir, "reg"); DotNet = new DotNetBuilder(_multilevelDir, Path.Combine(TestArtifact.TestArtifactsPath, "sharedFrameworkPublish"), "exe") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("9999.0.0") .Build(); RepoDirectories = new RepoDirectoriesProvider(builtDotnet: DotNet.BinPath); // SdkBaseDirs contain all available version folders _cwdSdkBaseDir = Path.Combine(_currentWorkingDir, "sdk"); _exeSdkBaseDir = Path.Combine(_exeDir, "sdk"); _regSdkBaseDir = Path.Combine(_regDir, "sdk"); // Create directories Directory.CreateDirectory(_cwdSdkBaseDir); Directory.CreateDirectory(_exeSdkBaseDir); Directory.CreateDirectory(_regSdkBaseDir); // Trace messages used to identify from which folder the SDK was picked _exeSelectedMessage = $"Using .NET SDK dll=[{_exeSdkBaseDir}"; _regSelectedMessage = $"Using .NET SDK dll=[{_regSdkBaseDir}"; _testOnlyProductBehaviorMarker = TestOnlyProductBehavior.Enable(DotNet.GreatestVersionHostFxrFilePath); } public void Dispose() { _testOnlyProductBehaviorMarker?.Dispose(); if (!TestArtifact.PreserveTestRuns()) { Directory.Delete(_multilevelDir, true); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Multi-level lookup is only supported on Windows. public void SdkMultilevelLookup_Global_Json_Single_Digit_Patch_Rollup() { // Set specified SDK version = 9999.3.4-global-dummy SetGlobalJsonVersion("SingleDigit-global.json"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // Exe: empty // Reg: empty // Expected: no compatible version and a specific error messages RunTest() .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.4.1", "9999.3.4-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // Exe: 9999.4.1, 9999.3.4-dummy // Reg: empty // Expected: no compatible version and a specific error message RunTest() .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.3"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // Exe: 9999.4.1, 9999.3.4-dummy // Reg: 9999.3.3 // Expected: no compatible version and a specific error message RunTest() .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.4"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.4 // Reg: 9999.3.3 // Expected: 9999.3.4 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.4", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.5-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.4 // Reg: 9999.3.3, 9999.3.5-dummy // Expected: 9999.3.5-dummy from reg dir RunTest() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.3.5-dummy", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.600"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.4, 9999.3.600 // Reg: 9999.3.3, 9999.3.5-dummy // Expected: 9999.3.5-dummy from reg dir RunTest() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.3.5-dummy", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.4-global-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Cwd: empty // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.4, 9999.3.600, 9999.3.4-global-dummy // Reg: 9999.3.3, 9999.3.5-dummy // Expected: 9999.3.4-global-dummy from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.4-global-dummy", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions RunTest("--list-sdks") .Should().Pass() .And.HaveStdOutContaining("9999.3.4-dummy") .And.HaveStdOutContaining("9999.3.4-global-dummy") .And.HaveStdOutContaining("9999.4.1") .And.HaveStdOutContaining("9999.3.3") .And.HaveStdOutContaining("9999.3.4") .And.HaveStdOutContaining("9999.3.600") .And.HaveStdOutContaining("9999.3.5-dummy"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Multi-level lookup is only supported on Windows. public void SdkMultilevelLookup_Global_Json_Two_Part_Patch_Rollup() { // Set specified SDK version = 9999.3.304-global-dummy SetGlobalJsonVersion("TwoPart-global.json"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // Exe: empty // Reg: empty // Expected: no compatible version and a specific error messages RunTest() .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.57", "9999.3.4-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // Exe: empty // Reg: 9999.3.57, 9999.3.4-dummy // Expected: no compatible version and a specific error message RunTest() .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.300", "9999.7.304-global-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // Exe: 9999.3.300, 9999.7.304-global-dummy // Reg: 9999.3.57, 9999.3.4-dummy // Expected: no compatible version and a specific error message RunTest() .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version"); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.304"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // Exe: 9999.3.300, 9999.7.304-global-dummy // Reg: 9999.3.57, 9999.3.4-dummy, 9999.3.304 // Expected: 9999.3.304 from reg dir RunTest() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.3.304", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.399", "9999.3.399-dummy", "9999.3.400"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // Exe: 9999.3.300, 9999.7.304-global-dummy, 9999.3.399, 9999.3.399-dummy, 9999.3.400 // Reg: 9999.3.57, 9999.3.4-dummy, 9999.3.304 // Expected: 9999.3.399 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.399", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.2400", "9999.3.3004"); AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.2400", "9999.3.3004"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // Exe: 9999.3.300, 9999.7.304-global-dummy, 9999.3.399, 9999.3.399-dummy, 9999.3.400, 9999.3.2400, 9999.3.3004 // Reg: 9999.3.57, 9999.3.4-dummy, 9999.3.304, 9999.3.2400, 9999.3.3004 // Expected: 9999.3.399 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.399", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.3.304-global-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Cwd: empty // Exe: 9999.3.300, 9999.7.304-global-dummy, 9999.3.399, 9999.3.399-dummy, 9999.3.400, 9999.3.2400, 9999.3.3004 // Reg: 9999.3.57, 9999.3.4-dummy, 9999.3.304, 9999.3.2400, 9999.3.3004, 9999.3.304-global-dummy // Expected: 9999.3.304-global-dummy from reg dir RunTest() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.3.304-global-dummy", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions RunTest("--list-sdks") .Should().Pass() .And.HaveStdOutContaining("9999.3.57") .And.HaveStdOutContaining("9999.3.4-dummy") .And.HaveStdOutContaining("9999.3.300") .And.HaveStdOutContaining("9999.7.304-global-dummy") .And.HaveStdOutContaining("9999.3.399") .And.HaveStdOutContaining("9999.3.399-dummy") .And.HaveStdOutContaining("9999.3.400") .And.HaveStdOutContaining("9999.3.2400") .And.HaveStdOutContaining("9999.3.3004") .And.HaveStdOutContaining("9999.3.304") .And.HaveStdOutContaining("9999.3.304-global-dummy"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Multi-level lookup is only supported on Windows. public void SdkMultilevelLookup_Precedential_Order() { WriteEmptyGlobalJson(); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.0.4"); // Specified SDK version: none // Cwd: empty // Exe: empty // Reg: 9999.0.4 // Expected: 9999.0.4 from reg dir RunTest() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.4", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.4"); // Specified SDK version: none // Cwd: empty // Exe: 9999.0.4 // Reg: 9999.0.4 // Expected: 9999.0.4 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.4", _dotnetSdkDllMessageTerminator)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Multi-level lookup is only supported on Windows. public void SdkMultilevelLookup_RegistryAccess() { // The purpose of this test is to verify that the product uses correct code to access // the registry to extract the path to search for SDKs. // Most of our tests rely on a shortcut which is to set _DOTNET_TEST_SDK_SELF_REGISTERED_DIR env variable // which will skip the registry reading code in the product and simply use the specified value. // This test is different since it actually runs the registry reading code. // Normally the reg key the product uses is in HKEY_LOCAL_MACHINE which is only writable as admin // so we would require the tests to run as admin to modify that key (and it may introduce races with other code running on the machine). // So instead the tests use _DOTENT_TEST_SDK_REGISTRY_PATH env variable to point to the produce to use // different registry key, inside the HKEY_CURRENT_USER hive which is writable without admin. // Note that the test creates a unique key (based on PID) for every run, to avoid collisions between parallel running tests. WriteEmptyGlobalJson(); using (var registeredInstallLocationOverride = new RegisteredInstallLocationOverride(DotNet.GreatestVersionHostFxrFilePath)) { registeredInstallLocationOverride.SetInstallLocation(new (string, string)[] { (RepoDirectories.BuildArchitecture, _regDir) }); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.0.4"); // Specified SDK version: none // Cwd: empty // Exe: empty // Reg: 9999.0.4 // Expected: 9999.0.4 from reg dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .MultilevelLookup(true) .ApplyRegisteredInstallLocationOverride(registeredInstallLocationOverride) .EnableTracingAndCaptureOutputs() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.4", _dotnetSdkDllMessageTerminator)); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Multi-level lookup is only supported on Windows. public void SdkMultilevelLookup_Must_Pick_The_Highest_Semantic_Version() { WriteEmptyGlobalJson(); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.0.0", "9999.0.3-dummy"); // Specified SDK version: none // Cwd: empty // Exe: empty // Reg: 9999.0.0, 9999.0.3-dummy // Expected: 9999.0.3-dummy from reg dir RunTest() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.3-dummy", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.3"); // Specified SDK version: none // Cwd: empty // Exe: 9999.0.3 // Reg: 9999.0.0, 9999.0.3-dummy // Expected: 9999.0.3 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.3", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_cwdSdkBaseDir, "10000.0.0"); AddAvailableSdkVersions(_regSdkBaseDir, "9999.0.100"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // Exe: 9999.0.3 // Reg: 9999.0.0, 9999.0.3-dummy, 9999.0.100 // Expected: 9999.0.100 from reg dir RunTest() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.100", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.80"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // Exe: 9999.0.3, 9999.0.80 // Reg: 9999.0.0, 9999.0.3-dummy, 9999.0.100 // Expected: 9999.0.100 from reg dir RunTest() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.100", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.5500000"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // Exe: 9999.0.3, 9999.0.80, 9999.0.5500000 // Reg: 9999.0.0, 9999.0.3-dummy, 9999.0.100 // Expected: 9999.0.5500000 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.5500000", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_regSdkBaseDir, "9999.0.52000000"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // Exe: 9999.0.3, 9999.0.80, 9999.0.5500000 // Reg: 9999.0.0, 9999.0.3-dummy, 9999.0.100, 9999.0.52000000 // Expected: 9999.0.52000000 from reg dir RunTest() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_regSelectedMessage, "9999.0.52000000", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions RunTest("--list-sdks") .Should().Pass() .And.HaveStdOutContaining("9999.0.0") .And.HaveStdOutContaining("9999.0.3-dummy") .And.HaveStdOutContaining("9999.0.3") .And.HaveStdOutContaining("9999.0.100") .And.HaveStdOutContaining("9999.0.80") .And.HaveStdOutContaining("9999.0.5500000") .And.HaveStdOutContaining("9999.0.52000000"); } private List<(string version, string rootPath)> AddSdkVersionsAndGetExpectedList(bool? multiLevelLookup) { AddAvailableSdkVersions(_exeSdkBaseDir, "5.0.2"); AddAvailableSdkVersions(_exeSdkBaseDir, "6.1.1"); AddAvailableSdkVersions(_exeSdkBaseDir, "7.1.2"); AddAvailableSdkVersions(_regSdkBaseDir, "6.2.0"); AddAvailableSdkVersions(_regSdkBaseDir, "7.0.1"); // The SDKs should be ordered by version number List<(string version, string rootPath)> expectedList = new(); expectedList.Add(("5.0.2", _exeSdkBaseDir)); expectedList.Add(("6.1.1", _exeSdkBaseDir)); expectedList.Add(("7.1.2", _exeSdkBaseDir)); if (multiLevelLookup is null || multiLevelLookup == true) { expectedList.Add(("6.2.0", _regSdkBaseDir)); expectedList.Add(("7.0.1", _regSdkBaseDir)); } expectedList.Sort((a, b) => { if (!Version.TryParse(a.version, out var aVersion)) return -1; if (!Version.TryParse(b.version, out var bVersion)) return 1; return aVersion.CompareTo(bVersion); }); return expectedList; } [Theory] [InlineData(true)] [InlineData(null)] [InlineData(false)] public void ListSdks(bool? multiLevelLookup) { // Multi-level lookup is only supported on Windows. if (!OperatingSystem.IsWindows() && multiLevelLookup != false) return; var expectedList = AddSdkVersionsAndGetExpectedList(multiLevelLookup); string expectedOutput = string.Join(string.Empty, expectedList.Select(t => $"{t.version} [{t.rootPath}]{Environment.NewLine}")); // !!IMPORTANT!!: This test verifies the exact match of the entire output of the command (not a substring!) // This is important as the output of --list-sdks is considered machine readable and thus must not change even in a minor way (unintentionally) RunTest("--list-sdks", multiLevelLookup) .Should().Pass() .And.HaveStdOut(expectedOutput); } [Theory] [InlineData(true)] [InlineData(null)] [InlineData(false)] public void SdkResolutionError(bool? multiLevelLookup) { // Multi-level lookup is only supported on Windows. if (!OperatingSystem.IsWindows() && multiLevelLookup != false) return; // Set specified SDK version = 9999.3.4-global-dummy - such SDK doesn't exist SetGlobalJsonVersion("SingleDigit-global.json"); // When we fail to resolve SDK version, we print out all available SDKs var expectedList = AddSdkVersionsAndGetExpectedList(multiLevelLookup); string expectedOutput = string.Join(string.Empty, expectedList.Select(t => $" {t.version} [{t.rootPath}]{Environment.NewLine}")); RunTest("help", multiLevelLookup) .Should().Fail() .And.HaveStdOutContaining(expectedOutput); } [Theory] [InlineData(true)] [InlineData(null)] [InlineData(false)] public void DotnetInfo(bool? multiLevelLookup) { // Multi-level lookup is only supported on Windows. if (!OperatingSystem.IsWindows() && multiLevelLookup != false) return; var expectedList = AddSdkVersionsAndGetExpectedList(multiLevelLookup); string expectedOutput = $".NET SDKs installed:{Environment.NewLine}" + string.Join(string.Empty, expectedList.Select(t => $" {t.version} [{t.rootPath}]{Environment.NewLine}")); RunTest("--info", multiLevelLookup) .Should().Pass() .And.HaveStdOutContaining(expectedOutput); } private CommandResult RunTest() => RunTest("help"); private CommandResult RunTest(string command, bool? multiLevelLookup = true) { return DotNet.Exec(command) .WorkingDirectory(_currentWorkingDir) .MultilevelLookup(multiLevelLookup) .EnvironmentVariable(Constants.TestOnlyEnvironmentVariables.GloballyRegisteredPath, _regDir) .EnvironmentVariable( // Redirect the default install location to an invalid location so that a machine-wide install is not used Constants.TestOnlyEnvironmentVariables.DefaultInstallPath, System.IO.Path.Combine(_currentWorkingDir, "invalid")) .EnableTracingAndCaptureOutputs() .Execute(); } // This method adds a list of new sdk version folders in the specified directory. // The actual contents are 'fake' and the mininum required for SDK discovery. // The dotnet.runtimeconfig.json created uses a dummy framework version (9999.0.0) private void AddAvailableSdkVersions(string sdkBaseDir, params string[] availableVersions) { string dummyRuntimeConfig = Path.Combine(RepoDirectories.TestAssetsFolder, "TestUtils", "SDKLookup", "dotnet.runtimeconfig.json"); foreach (string version in availableVersions) { string newSdkDir = Path.Combine(sdkBaseDir, version); Directory.CreateDirectory(newSdkDir); // ./dotnet.dll File.WriteAllText(Path.Combine(newSdkDir, "dotnet.dll"), string.Empty); // ./dotnet.runtimeconfig.json string runtimeConfig = Path.Combine(newSdkDir, "dotnet.runtimeconfig.json"); File.Copy(dummyRuntimeConfig, runtimeConfig, true); } } // Put a global.json file in the cwd in order to specify a CLI private void SetGlobalJsonVersion(string globalJsonFileName) { string destFile = Path.Combine(_currentWorkingDir, "global.json"); string srcFile = Path.Combine(RepoDirectories.TestAssetsFolder, "TestUtils", "SDKLookup", globalJsonFileName); File.Copy(srcFile, destFile, true); } private void WriteGlobalJson(string contents) { File.WriteAllText(Path.Combine(_currentWorkingDir, "global.json"), contents); } private void WriteEmptyGlobalJson() => WriteGlobalJson("{}"); } }
1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/installer/tests/HostActivation.Tests/SDKLookup.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.DotNet.Cli.Build; using System; using System.Collections.Generic; using System.IO; using Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation { public class SDKLookup : IDisposable { private static readonly IDictionary<string, string> s_DefaultEnvironment = new Dictionary<string, string>() { {"COREHOST_TRACE", "1" }, // The SDK being used may be crossgen'd for a different architecture than we are building for. // Turn off ready to run, so an x64 crossgen'd SDK can be loaded in an x86 process. {"COMPlus_ReadyToRun", "0" }, }; private readonly RepoDirectoriesProvider RepoDirectories; private readonly DotNetCli DotNet; private readonly string _baseDir; private readonly string _currentWorkingDir; private readonly string _userDir; private readonly string _executableDir; private readonly string _cwdSdkBaseDir; private readonly string _userSdkBaseDir; private readonly string _exeSdkBaseDir; private readonly string _exeSelectedMessage; private const string _dotnetSdkDllMessageTerminator = "dotnet.dll]"; public SDKLookup() { // The dotnetSDKLookup dir will contain some folders and files that will be // necessary to perform the tests string baseDir = Path.Combine(TestArtifact.TestArtifactsPath, "dotnetSDKLookup"); _baseDir = SharedFramework.CalculateUniqueTestDirectory(baseDir); // The three tested locations will be the cwd, the user folder and the exe dir. cwd and user are no longer supported. // All dirs will be placed inside the base folder _currentWorkingDir = Path.Combine(_baseDir, "cwd"); _userDir = Path.Combine(_baseDir, "user"); _executableDir = Path.Combine(_baseDir, "exe"); DotNet = new DotNetBuilder(_baseDir, Path.Combine(TestArtifact.TestArtifactsPath, "sharedFrameworkPublish"), "exe") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("9999.0.0") .Build(); RepoDirectories = new RepoDirectoriesProvider(builtDotnet: DotNet.BinPath); // SdkBaseDirs contain all available version folders _cwdSdkBaseDir = Path.Combine(_currentWorkingDir, "sdk"); _userSdkBaseDir = Path.Combine(_userDir, ".dotnet", RepoDirectories.BuildArchitecture, "sdk"); _exeSdkBaseDir = Path.Combine(_executableDir, "sdk"); // Create directories Directory.CreateDirectory(_cwdSdkBaseDir); Directory.CreateDirectory(_userSdkBaseDir); Directory.CreateDirectory(_exeSdkBaseDir); // Trace messages used to identify from which folder the SDK was picked _exeSelectedMessage = $"Using .NET SDK dll=[{_exeSdkBaseDir}"; } public void Dispose() { if (!TestArtifact.PreserveTestRuns()) { Directory.Delete(_baseDir, true); } } [Fact] public void SdkLookup_Global_Json_Single_Digit_Patch_Rollup() { // Set specified SDK version = 9999.3.4-global-dummy CopyGlobalJson("SingleDigit-global.json"); // Specified SDK version: 9999.3.4-global-dummy // Exe: empty // Expected: no compatible version and a specific error messages DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version") .And.HaveStdErrContaining("It was not possible to find any installed .NET SDKs") .And.HaveStdErrContaining("aka.ms/dotnet-download") .And.NotHaveStdErrContaining("Checking if resolved SDK dir"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.4.1", "9999.3.4-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy // Expected: no compatible version and a specific error message DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version") .And.NotHaveStdErrContaining("It was not possible to find any installed .NET SDKs"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.3"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3 // Expected: no compatible version and a specific error message DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version") .And.NotHaveStdErrContaining("It was not possible to find any installed .NET SDKs"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.4"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4 // Expected: 9999.3.4 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.4", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.5-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4, 9999.3.5-dummy // Expected: 9999.3.5-dummy from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.5-dummy", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.600"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4, 9999.3.5-dummy, 9999.3.600 // Expected: 9999.3.5-dummy from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.5-dummy", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.4-global-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4, 9999.3.5-dummy, 9999.3.600, 9999.3.4-global-dummy // Expected: 9999.3.4-global-dummy from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.4-global-dummy", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions DotNet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("9999.3.4-dummy") .And.HaveStdOutContaining("9999.3.4-global-dummy") .And.HaveStdOutContaining("9999.4.1") .And.HaveStdOutContaining("9999.3.3") .And.HaveStdOutContaining("9999.3.4") .And.HaveStdOutContaining("9999.3.600") .And.HaveStdOutContaining("9999.3.5-dummy"); } [Fact] public void SdkLookup_Global_Json_Two_Part_Patch_Rollup() { // Set specified SDK version = 9999.3.304-global-dummy CopyGlobalJson("TwoPart-global.json"); // Specified SDK version: 9999.3.304-global-dummy // Exe: empty // Expected: no compatible version and a specific error messages DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version") .And.HaveStdErrContaining("It was not possible to find any installed .NET SDKs"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.57", "9999.3.4-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 9999.3.57, 9999.3.4-dummy // Expected: no compatible version and a specific error message DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version") .And.NotHaveStdErrContaining("It was not possible to find any installed .NET SDKs"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.300", "9999.7.304-global-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy // Expected: no compatible version and a specific error message DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version") .And.NotHaveStdErrContaining("It was not possible to find any installed .NET SDKs"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.304"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 99999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304 // Expected: 9999.3.304 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.304", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.399", "9999.3.399-dummy", "9999.3.400"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304, 9999.3.399, 9999.3.399-dummy, 9999.3.400 // Expected: 9999.3.399 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.399", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.2400", "9999.3.3004"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304, 9999.3.399, 9999.3.399-dummy, 9999.3.400, 9999.3.2400, 9999.3.3004 // Expected: 9999.3.399 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.399", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.304-global-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304, 9999.3.399, 9999.3.399-dummy, 9999.3.400, 9999.3.2400, 9999.3.3004, 9999.3.304-global-dummy // Expected: 9999.3.304-global-dummy from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.304-global-dummy", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions DotNet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("9999.3.57") .And.HaveStdOutContaining("9999.3.4-dummy") .And.HaveStdOutContaining("9999.3.300") .And.HaveStdOutContaining("9999.7.304-global-dummy") .And.HaveStdOutContaining("9999.3.399") .And.HaveStdOutContaining("9999.3.399-dummy") .And.HaveStdOutContaining("9999.3.400") .And.HaveStdOutContaining("9999.3.2400") .And.HaveStdOutContaining("9999.3.3004") .And.HaveStdOutContaining("9999.3.304") .And.HaveStdOutContaining("9999.3.304-global-dummy"); } [Fact] public void SdkLookup_Negative_Version() { WriteEmptyGlobalJson(); // Add a negative SDK version AddAvailableSdkVersions(_exeSdkBaseDir, "-1.-1.-1"); // Specified SDK version: none // Exe: -1.-1.-1 // Expected: no compatible version and a specific error messages DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("It was not possible to find any installed .NET SDKs") .And.HaveStdErrContaining("Install a .NET SDK from"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.4"); // Specified SDK version: none // Exe: -1.-1.-1, 9999.0.4 // Expected: 9999.0.4 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.4", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions DotNet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("9999.0.4"); } [Fact] public void SdkLookup_Must_Pick_The_Highest_Semantic_Version() { WriteEmptyGlobalJson(); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.0", "9999.0.3-dummy.9", "9999.0.3-dummy.10"); // Specified SDK version: none // Cwd: empty // User: empty // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10 // Expected: 9999.0.3-dummy.10 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.3-dummy.10", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.3"); // Specified SDK version: none // Cwd: empty // User: empty // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10, 9999.0.3 // Expected: 9999.0.3 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.3", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_userSdkBaseDir, "9999.0.200"); AddAvailableSdkVersions(_cwdSdkBaseDir, "10000.0.0"); AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.100"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10, 9999.0.3, 9999.0.100 // Expected: 9999.0.100 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.100", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.80"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10, 9999.0.3, 9999.0.100, 9999.0.80 // Expected: 9999.0.100 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.100", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.5500000"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10, 9999.0.3, 9999.0.100, 9999.0.80, 9999.0.5500000 // Expected: 9999.0.5500000 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.5500000", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.52000000"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10, 9999.0.3, 9999.0.100, 9999.0.80, 9999.0.5500000, 9999.0.52000000 // Expected: 9999.0.52000000 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.52000000", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions DotNet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("9999.0.0") .And.HaveStdOutContaining("9999.0.3-dummy.9") .And.HaveStdOutContaining("9999.0.3-dummy.10") .And.HaveStdOutContaining("9999.0.3") .And.HaveStdOutContaining("9999.0.100") .And.HaveStdOutContaining("9999.0.80") .And.HaveStdOutContaining("9999.0.5500000") .And.HaveStdOutContaining("9999.0.52000000"); } [Theory] [InlineData("diSABle")] [InlineData("PaTCh")] [InlineData("FeaturE")] [InlineData("MINOR")] [InlineData("maJor")] [InlineData("LatestPatch")] [InlineData("Latestfeature")] [InlineData("latestMINOR")] [InlineData("latESTMajor")] public void It_allows_case_insensitive_roll_forward_policy_names(string rollForward) { const string Requested = "9999.0.100"; WriteEmptyGlobalJson(); AddAvailableSdkVersions(_exeSdkBaseDir, Requested); WriteGlobalJson(FormatGlobalJson(policy: rollForward, version: Requested)); DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, Requested, _dotnetSdkDllMessageTerminator)); } [Theory] [MemberData(nameof(InvalidGlobalJsonData))] public void It_falls_back_to_latest_sdk_for_invalid_global_json(string globalJsonContents, string[] messages) { AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.100", "9999.0.300-dummy.9", "9999.1.402"); WriteGlobalJson(globalJsonContents); var expectation = DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.1.402", _dotnetSdkDllMessageTerminator)); foreach (var message in messages) { expectation = expectation.And.HaveStdErrContaining(message); } } [Theory] [MemberData(nameof(SdkRollForwardData))] public void It_rolls_forward_as_expected(string policy, string requested, bool allowPrerelease, string expected, string[] installed) { AddAvailableSdkVersions(_exeSdkBaseDir, installed); WriteGlobalJson(FormatGlobalJson(policy: policy, version: requested, allowPrerelease: allowPrerelease)); var result = DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(); var globalJson = Path.Combine(_currentWorkingDir, "global.json"); if (expected == null) { result .Should() .Fail() .And.HaveStdErrContaining($"A compatible installed .NET SDK for global.json version [{requested}] from [{globalJson}] was not found") .And.HaveStdErrContaining($"Install the [{requested}] .NET SDK or update [{globalJson}] with an installed .NET SDK:"); } else { result .Should() .Pass() .And.HaveStdErrContaining($"SDK path resolved to [{Path.Combine(_exeSdkBaseDir, expected)}]"); } } [Fact] public void It_uses_latest_stable_sdk_if_allow_prerelease_is_false() { var installed = new string[] { "9999.1.702", "9999.2.101", "9999.2.203", "9999.2.204-preview1", "10000.0.100-preview3", "10000.0.100-preview7", "10000.0.100", "10000.1.102", "10000.1.106", "10000.0.200-preview5", "10000.1.100-preview3", "10001.0.100-preview3", }; const string ExpectedVersion = "10000.1.106"; AddAvailableSdkVersions(_exeSdkBaseDir, installed); WriteGlobalJson(FormatGlobalJson(allowPrerelease: false)); var result = DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And.HaveStdErrContaining($"SDK path resolved to [{Path.Combine(_exeSdkBaseDir, ExpectedVersion)}]"); } public static IEnumerable<object[]> InvalidGlobalJsonData { get { const string IgnoringSDKSettings = "Ignoring SDK settings in global.json: the latest installed .NET SDK (including prereleases) will be used"; // Use invalid JSON yield return new object[] { "{ sdk: { \"version\": \"9999.0.100\" } }", new[] { "A JSON parsing exception occurred", IgnoringSDKSettings } }; // Use something other than a JSON object yield return new object[] { "true", new[] { "Expected a JSON object", IgnoringSDKSettings } }; // Use a non-string version yield return new object[] { "{ \"sdk\": { \"version\": 1 } }", new[] { "Expected a string for the 'sdk/version' value", IgnoringSDKSettings } }; // Use an invalid version value yield return new object[] { FormatGlobalJson(version: "invalid"), new[] { "Version 'invalid' is not valid for the 'sdk/version' value", IgnoringSDKSettings } }; // Use a non-string policy yield return new object[] { "{ \"sdk\": { \"rollForward\": true } }", new[] { "Expected a string for the 'sdk/rollForward' value", IgnoringSDKSettings } }; // Use a policy but no version yield return new object[] { FormatGlobalJson(policy: "latestPatch"), new[] { "The roll-forward policy 'latestPatch' requires a 'sdk/version' value", IgnoringSDKSettings } }; // Use an invalid policy value yield return new object[] { FormatGlobalJson(policy: "invalid"), new[] { "The roll-forward policy 'invalid' is not supported for the 'sdk/rollForward' value", IgnoringSDKSettings } }; // Use a non-boolean allow prerelease yield return new object[] { "{ \"sdk\": { \"allowPrerelease\": \"true\" } }", new[] { "Expected a boolean for the 'sdk/allowPrerelease' value", IgnoringSDKSettings } }; // Use a prerelease version and allowPrerelease = false yield return new object[] { FormatGlobalJson(version: "9999.1.402-preview1", allowPrerelease: false), new[] { "Ignoring the 'sdk/allowPrerelease' value" } }; } } public static IEnumerable<object[]> SdkRollForwardData { get { const string Requested = "9999.1.501"; var installed = new string[] { "9999.1.500", }; // Array of (policy, expected) tuples var policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", (string)null), ("major", (string)null), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", (string)null), ("latestMajor", (string)null), ("disable", (string)null), ("invalid", "9999.1.500"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9999.1.500", "9999.2.100-preview1", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", (string)null), ("major", (string)null), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", (string)null), ("latestMajor", (string)null), ("disable", (string)null), ("invalid", "9999.2.100-preview1"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // do not allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.501", "9999.1.503-preview5", "9999.1.503", "9999.1.504-preview1", "9999.1.504-preview2", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, "9999.1.501"), ("patch", "9999.1.501"), ("feature", "9999.1.504-preview2"), ("minor", "9999.1.504-preview2"), ("major", "9999.1.504-preview2"), ("latestPatch", "9999.1.504-preview2"), ("latestFeature", "9999.1.504-preview2"), ("latestMinor", "9999.1.504-preview2"), ("latestMajor", "9999.1.504-preview2"), ("disable", "9999.1.501"), ("invalid", "9999.1.504-preview2"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.501", "9999.1.503-preview5", "9999.1.503", "9999.1.504-preview1", "9999.1.504-preview2", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, "9999.1.501"), ("patch", "9999.1.501"), ("feature", "9999.1.503"), ("minor", "9999.1.503"), ("major", "9999.1.503"), ("latestPatch", "9999.1.503"), ("latestFeature", "9999.1.503"), ("latestMinor", "9999.1.503"), ("latestMajor", "9999.1.503"), ("disable", "9999.1.501"), ("invalid", "9999.1.504-preview2"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // don't allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.503", "9999.1.505-preview2", "9999.1.505", "9999.1.506-preview1", "9999.1.601", "9999.1.608-preview3", "9999.1.609", "9999.2.101", "9999.2.203-preview1", "9999.2.203", "10000.0.100", "10000.1.100-preview1" }; // Array of (policy, expected) tuples policies = new[] { (null, "9999.1.506-preview1"), ("patch", "9999.1.506-preview1"), ("feature", "9999.1.506-preview1"), ("minor", "9999.1.506-preview1"), ("major", "9999.1.506-preview1"), ("latestPatch", "9999.1.506-preview1"), ("latestFeature", "9999.1.609"), ("latestMinor", "9999.2.203"), ("latestMajor", "10000.1.100-preview1"), ("disable", (string)null), ("invalid", "10000.1.100-preview1"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.503", "9999.1.505-preview2", "9999.1.505", "9999.1.506-preview1", "9999.1.601", "9999.1.608-preview3", "9999.1.609", "9999.2.101", "9999.2.203-preview1", "9999.2.203", "10000.0.100", "10000.1.100-preview1" }; // Array of (policy, expected) tuples policies = new[] { (null, "9999.1.505"), ("patch", "9999.1.505"), ("feature", "9999.1.505"), ("minor", "9999.1.505"), ("major", "9999.1.505"), ("latestPatch", "9999.1.505"), ("latestFeature", "9999.1.609"), ("latestMinor", "9999.2.203"), ("latestMajor", "10000.0.100"), ("disable", (string)null), ("invalid", "10000.1.100-preview1"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // don't allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.601", "9999.1.604-preview3", "9999.1.604", "9999.1.605-preview4", "9999.1.701", "9999.1.702-preview1", "9999.1.702", "9999.2.101", "9999.2.203", "9999.2.204-preview1", "10000.0.100-preview7", "10000.0.100", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", "9999.1.605-preview4"), ("minor", "9999.1.605-preview4"), ("major", "9999.1.605-preview4"), ("latestPatch", (string)null), ("latestFeature", "9999.1.702"), ("latestMinor", "9999.2.204-preview1"), ("latestMajor", "10000.0.100"), ("disable", (string)null), ("invalid", "10000.0.100"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.601", "9999.1.604-preview3", "9999.1.604", "9999.1.605-preview4", "9999.1.701", "9999.1.702-preview1", "9999.1.702", "9999.2.101", "9999.2.203", "9999.2.204-preview1", "10000.0.100-preview7", "10000.0.100", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", "9999.1.604"), ("minor", "9999.1.604"), ("major", "9999.1.604"), ("latestPatch", (string)null), ("latestFeature", "9999.1.702"), ("latestMinor", "9999.2.203"), ("latestMajor", "10000.0.100"), ("disable", (string)null), ("invalid", "10000.0.100"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // don't allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.2.101-preview4", "9999.2.101", "9999.2.102-preview1", "9999.2.203", "9999.3.501", "9999.4.205-preview3", "10000.0.100", "10000.1.100-preview1" }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", "9999.2.102-preview1"), ("major", "9999.2.102-preview1"), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", "9999.4.205-preview3"), ("latestMajor", "10000.1.100-preview1"), ("disable", (string)null), ("invalid", "10000.1.100-preview1"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.2.101-preview4", "9999.2.101", "9999.2.102-preview1", "9999.2.203", "9999.3.501", "9999.4.205-preview3", "10000.0.100", "10000.1.100-preview1" }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", "9999.2.101"), ("major", "9999.2.101"), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", "9999.3.501"), ("latestMajor", "10000.0.100"), ("disable", (string)null), ("invalid", "10000.1.100-preview1"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // don't allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "10000.0.100", "10000.0.105-preview1", "10000.0.105", "10000.0.106-preview1", "10000.1.102", "10000.1.107", "10000.3.100", "10000.3.102-preview3", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", (string)null), ("major", "10000.0.106-preview1"), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", (string)null), ("latestMajor", "10000.3.102-preview3"), ("disable", (string)null), ("invalid", "10000.3.102-preview3"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "10000.0.100", "10000.0.105-preview1", "10000.0.105", "10000.0.106-preview1", "10000.1.102", "10000.1.107", "10000.3.100", "10000.3.102-preview3", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", (string)null), ("major", "10000.0.105"), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", (string)null), ("latestMajor", "10000.3.100"), ("disable", (string)null), ("invalid", "10000.3.102-preview3"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // don't allow prerelease policy.Item2, // expected installed // installed }; } } } // This method adds a list of new sdk version folders in the specified directory. // The actual contents are 'fake' and the mininum required for SDK discovery. // The dotnet.runtimeconfig.json created uses a dummy framework version (9999.0.0) private void AddAvailableSdkVersions(string sdkBaseDir, params string[] availableVersions) { string dummyRuntimeConfig = Path.Combine(RepoDirectories.TestAssetsFolder, "TestUtils", "SDKLookup", "dotnet.runtimeconfig.json"); foreach (string version in availableVersions) { string newSdkDir = Path.Combine(sdkBaseDir, version); Directory.CreateDirectory(newSdkDir); // ./dotnet.dll File.WriteAllText(Path.Combine(newSdkDir, "dotnet.dll"), string.Empty); // ./dotnet.runtimeconfig.json string runtimeConfig = Path.Combine(newSdkDir, "dotnet.runtimeconfig.json"); File.Copy(dummyRuntimeConfig, runtimeConfig, true); } } // Put a global.json file in the cwd in order to specify a CLI private void CopyGlobalJson(string globalJsonFileName) { string destFile = Path.Combine(_currentWorkingDir, "global.json"); string srcFile = Path.Combine(RepoDirectories.TestAssetsFolder, "TestUtils", "SDKLookup", globalJsonFileName); File.Copy(srcFile, destFile, true); } private static string FormatGlobalJson(string version = null, string policy = null, bool? allowPrerelease = null) { version = version == null ? "null" : string.Format("\"{0}\"", version); policy = policy == null ? "null" : string.Format("\"{0}\"", policy); string allow = allowPrerelease.HasValue ? (allowPrerelease.Value ? "true" : "false") : "null"; return $@"{{ ""sdk"": {{ ""version"": {version}, ""rollForward"": {policy}, ""allowPrerelease"": {allow} }} }}"; } private void WriteGlobalJson(string contents) { File.WriteAllText(Path.Combine(_currentWorkingDir, "global.json"), contents); } private void WriteEmptyGlobalJson() => WriteGlobalJson("{}"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using Microsoft.DotNet.Cli.Build; using Microsoft.DotNet.Cli.Build.Framework; using Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation { public class SDKLookup : IClassFixture<SDKLookup.SharedTestState> { private SharedTestState SharedState { get; } readonly DotNetCli ExecutableDotNet; readonly DotNetBuilder ExecutableDotNetBuilder; string ExecutableSelectedMessage { get; } public SDKLookup(SharedTestState sharedState) { SharedState = sharedState; string exeDotNetPath = SharedFramework.CalculateUniqueTestDirectory(sharedState.BaseDir); ExecutableDotNetBuilder = new DotNetBuilder(exeDotNetPath, sharedState.BuiltDotNet.BinPath, "exe"); ExecutableDotNet = ExecutableDotNetBuilder .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("9999.0.0") .Build(); // Trace messages used to identify from which folder the SDK was picked ExecutableSelectedMessage = $"Using .NET SDK dll=[{Path.Combine(ExecutableDotNet.BinPath, "sdk")}"; // Note: no need to delete the directory, it will be removed once the entire class is done // since everything is under the BaseDir from the shared state } [Fact] public void SdkLookup_Global_Json_Single_Digit_Patch_Rollup() { // Set specified SDK version = 9999.3.4-global-dummy CopyGlobalJson("SingleDigit-global.json"); // Specified SDK version: 9999.3.4-global-dummy // Exe: empty // Expected: no compatible version and a specific error messages RunTest() .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version") .And.HaveStdErrContaining("It was not possible to find any installed .NET SDKs") .And.HaveStdErrContaining("aka.ms/dotnet-download") .And.NotHaveStdErrContaining("Checking if resolved SDK dir"); // Add SDK versions AddAvailableSdkVersions("9999.4.1", "9999.3.4-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy // Expected: no compatible version and a specific error message RunTest() .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version") .And.NotHaveStdErrContaining("It was not possible to find any installed .NET SDKs"); // Add SDK versions AddAvailableSdkVersions("9999.3.3"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3 // Expected: no compatible version and a specific error message RunTest() .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version") .And.NotHaveStdErrContaining("It was not possible to find any installed .NET SDKs"); // Add SDK versions AddAvailableSdkVersions("9999.3.4"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4 // Expected: 9999.3.4 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput("9999.3.4")); // Add SDK versions AddAvailableSdkVersions("9999.3.5-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4, 9999.3.5-dummy // Expected: 9999.3.5-dummy from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput("9999.3.5-dummy")); // Add SDK versions AddAvailableSdkVersions("9999.3.600"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4, 9999.3.5-dummy, 9999.3.600 // Expected: 9999.3.5-dummy from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput("9999.3.5-dummy")); // Add SDK versions AddAvailableSdkVersions("9999.3.4-global-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4, 9999.3.5-dummy, 9999.3.600, 9999.3.4-global-dummy // Expected: 9999.3.4-global-dummy from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput("9999.3.4-global-dummy")); // Verify we have the expected SDK versions RunTest("--list-sdks") .Should().Pass() .And.HaveStdOutContaining("9999.3.4-dummy") .And.HaveStdOutContaining("9999.3.4-global-dummy") .And.HaveStdOutContaining("9999.4.1") .And.HaveStdOutContaining("9999.3.3") .And.HaveStdOutContaining("9999.3.4") .And.HaveStdOutContaining("9999.3.600") .And.HaveStdOutContaining("9999.3.5-dummy"); } [Fact] public void SdkLookup_Global_Json_Two_Part_Patch_Rollup() { // Set specified SDK version = 9999.3.304-global-dummy CopyGlobalJson("TwoPart-global.json"); // Specified SDK version: 9999.3.304-global-dummy // Exe: empty // Expected: no compatible version and a specific error messages RunTest() .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version") .And.HaveStdErrContaining("It was not possible to find any installed .NET SDKs"); // Add SDK versions AddAvailableSdkVersions("9999.3.57", "9999.3.4-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 9999.3.57, 9999.3.4-dummy // Expected: no compatible version and a specific error message RunTest() .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version") .And.NotHaveStdErrContaining("It was not possible to find any installed .NET SDKs"); // Add SDK versions AddAvailableSdkVersions("9999.3.300", "9999.7.304-global-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy // Expected: no compatible version and a specific error message RunTest() .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET SDK for global.json version") .And.NotHaveStdErrContaining("It was not possible to find any installed .NET SDKs"); // Add SDK versions AddAvailableSdkVersions("9999.3.304"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 99999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304 // Expected: 9999.3.304 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput("9999.3.304")); // Add SDK versions AddAvailableSdkVersions("9999.3.399", "9999.3.399-dummy", "9999.3.400"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304, 9999.3.399, 9999.3.399-dummy, 9999.3.400 // Expected: 9999.3.399 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput("9999.3.399")); // Add SDK versions AddAvailableSdkVersions("9999.3.2400", "9999.3.3004"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304, 9999.3.399, 9999.3.399-dummy, 9999.3.400, 9999.3.2400, 9999.3.3004 // Expected: 9999.3.399 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput("9999.3.399")); // Add SDK versions AddAvailableSdkVersions("9999.3.304-global-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304, 9999.3.399, 9999.3.399-dummy, 9999.3.400, 9999.3.2400, 9999.3.3004, 9999.3.304-global-dummy // Expected: 9999.3.304-global-dummy from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput("9999.3.304-global-dummy")); // Verify we have the expected SDK versions RunTest("--list-sdks") .Should().Pass() .And.HaveStdOutContaining("9999.3.57") .And.HaveStdOutContaining("9999.3.4-dummy") .And.HaveStdOutContaining("9999.3.300") .And.HaveStdOutContaining("9999.7.304-global-dummy") .And.HaveStdOutContaining("9999.3.399") .And.HaveStdOutContaining("9999.3.399-dummy") .And.HaveStdOutContaining("9999.3.400") .And.HaveStdOutContaining("9999.3.2400") .And.HaveStdOutContaining("9999.3.3004") .And.HaveStdOutContaining("9999.3.304") .And.HaveStdOutContaining("9999.3.304-global-dummy"); } [Fact] public void SdkLookup_Negative_Version() { WriteEmptyGlobalJson(); // Add a negative SDK version AddAvailableSdkVersions("-1.-1.-1"); // Specified SDK version: none // Exe: -1.-1.-1 // Expected: no compatible version and a specific error messages RunTest() .Should().Fail() .And.HaveStdErrContaining("It was not possible to find any installed .NET SDKs") .And.HaveStdErrContaining("Install a .NET SDK from"); // Add SDK versions AddAvailableSdkVersions("9999.0.4"); // Specified SDK version: none // Exe: -1.-1.-1, 9999.0.4 // Expected: 9999.0.4 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput("9999.0.4")); // Verify we have the expected SDK versions RunTest("--list-sdks") .Should().Pass() .And.HaveStdOutContaining("9999.0.4"); } [Fact] public void SdkLookup_Must_Pick_The_Highest_Semantic_Version() { WriteEmptyGlobalJson(); // Add SDK versions AddAvailableSdkVersions("9999.0.0", "9999.0.3-dummy.9", "9999.0.3-dummy.10"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10 // Expected: 9999.0.3-dummy.10 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput("9999.0.3-dummy.10")); // Add SDK versions AddAvailableSdkVersions("9999.0.3"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10, 9999.0.3 // Expected: 9999.0.3 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput("9999.0.3")); // Add SDK versions AddAvailableSdkVersions("9999.0.100"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10, 9999.0.3, 9999.0.100 // Expected: 9999.0.100 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput("9999.0.100")); // Add SDK versions AddAvailableSdkVersions("9999.0.80"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10, 9999.0.3, 9999.0.100, 9999.0.80 // Expected: 9999.0.100 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput("9999.0.100")); // Add SDK versions AddAvailableSdkVersions("9999.0.5500000"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10, 9999.0.3, 9999.0.100, 9999.0.80, 9999.0.5500000 // Expected: 9999.0.5500000 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput("9999.0.5500000")); // Add SDK versions AddAvailableSdkVersions("9999.0.52000000"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10, 9999.0.3, 9999.0.100, 9999.0.80, 9999.0.5500000, 9999.0.52000000 // Expected: 9999.0.52000000 from exe dir RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput("9999.0.52000000")); // Verify we have the expected SDK versions RunTest("--list-sdks") .Should().Pass() .And.HaveStdOutContaining("9999.0.0") .And.HaveStdOutContaining("9999.0.3-dummy.9") .And.HaveStdOutContaining("9999.0.3-dummy.10") .And.HaveStdOutContaining("9999.0.3") .And.HaveStdOutContaining("9999.0.100") .And.HaveStdOutContaining("9999.0.80") .And.HaveStdOutContaining("9999.0.5500000") .And.HaveStdOutContaining("9999.0.52000000"); } [Theory] [InlineData("diSABle")] [InlineData("PaTCh")] [InlineData("FeaturE")] [InlineData("MINOR")] [InlineData("maJor")] [InlineData("LatestPatch")] [InlineData("Latestfeature")] [InlineData("latestMINOR")] [InlineData("latESTMajor")] public void It_allows_case_insensitive_roll_forward_policy_names(string rollForward) { const string Requested = "9999.0.100"; WriteEmptyGlobalJson(); AddAvailableSdkVersions(Requested); WriteGlobalJson(FormatGlobalJson(policy: rollForward, version: Requested)); RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput(Requested)); } [Theory] [MemberData(nameof(InvalidGlobalJsonData))] public void It_falls_back_to_latest_sdk_for_invalid_global_json(string globalJsonContents, string[] messages) { AddAvailableSdkVersions("9999.0.100", "9999.0.300-dummy.9", "9999.1.402"); WriteGlobalJson(globalJsonContents); var expectation = RunTest() .Should().Pass() .And.HaveStdErrContaining(ExpectedResolvedSdkOutput("9999.1.402")); foreach (var message in messages) { expectation = expectation.And.HaveStdErrContaining(message); } } [Theory] [MemberData(nameof(SdkRollForwardData))] public void It_rolls_forward_as_expected(string policy, string requested, bool allowPrerelease, string expected, string[] installed) { AddAvailableSdkVersions(installed); WriteGlobalJson(FormatGlobalJson(policy: policy, version: requested, allowPrerelease: allowPrerelease)); var result = RunTest(); var globalJson = Path.Combine(SharedState.CurrentWorkingDir, "global.json"); if (expected == null) { result .Should() .Fail() .And.HaveStdErrContaining($"A compatible installed .NET SDK for global.json version [{requested}] from [{globalJson}] was not found") .And.HaveStdErrContaining($"Install the [{requested}] .NET SDK or update [{globalJson}] with an installed .NET SDK:"); } else { result .Should() .Pass() .And.HaveStdErrContaining($"SDK path resolved to [{Path.Combine(ExecutableDotNet.BinPath, "sdk", expected)}]"); } } [Fact] public void It_uses_latest_stable_sdk_if_allow_prerelease_is_false() { var installed = new string[] { "9999.1.702", "9999.2.101", "9999.2.203", "9999.2.204-preview1", "10000.0.100-preview3", "10000.0.100-preview7", "10000.0.100", "10000.1.102", "10000.1.106", "10000.0.200-preview5", "10000.1.100-preview3", "10001.0.100-preview3", }; const string ExpectedVersion = "10000.1.106"; AddAvailableSdkVersions(installed); WriteGlobalJson(FormatGlobalJson(allowPrerelease: false)); var result = RunTest() .Should().Pass() .And.HaveStdErrContaining($"SDK path resolved to [{Path.Combine(ExecutableDotNet.BinPath, "sdk", ExpectedVersion)}]"); } public static IEnumerable<object[]> InvalidGlobalJsonData { get { const string IgnoringSDKSettings = "Ignoring SDK settings in global.json: the latest installed .NET SDK (including prereleases) will be used"; // Use invalid JSON yield return new object[] { "{ sdk: { \"version\": \"9999.0.100\" } }", new[] { "A JSON parsing exception occurred", IgnoringSDKSettings } }; // Use something other than a JSON object yield return new object[] { "true", new[] { "Expected a JSON object", IgnoringSDKSettings } }; // Use a non-string version yield return new object[] { "{ \"sdk\": { \"version\": 1 } }", new[] { "Expected a string for the 'sdk/version' value", IgnoringSDKSettings } }; // Use an invalid version value yield return new object[] { FormatGlobalJson(version: "invalid"), new[] { "Version 'invalid' is not valid for the 'sdk/version' value", IgnoringSDKSettings } }; // Use a non-string policy yield return new object[] { "{ \"sdk\": { \"rollForward\": true } }", new[] { "Expected a string for the 'sdk/rollForward' value", IgnoringSDKSettings } }; // Use a policy but no version yield return new object[] { FormatGlobalJson(policy: "latestPatch"), new[] { "The roll-forward policy 'latestPatch' requires a 'sdk/version' value", IgnoringSDKSettings } }; // Use an invalid policy value yield return new object[] { FormatGlobalJson(policy: "invalid"), new[] { "The roll-forward policy 'invalid' is not supported for the 'sdk/rollForward' value", IgnoringSDKSettings } }; // Use a non-boolean allow prerelease yield return new object[] { "{ \"sdk\": { \"allowPrerelease\": \"true\" } }", new[] { "Expected a boolean for the 'sdk/allowPrerelease' value", IgnoringSDKSettings } }; // Use a prerelease version and allowPrerelease = false yield return new object[] { FormatGlobalJson(version: "9999.1.402-preview1", allowPrerelease: false), new[] { "Ignoring the 'sdk/allowPrerelease' value" } }; } } public static IEnumerable<object[]> SdkRollForwardData { get { const string Requested = "9999.1.501"; var installed = new string[] { "9999.1.500", }; // Array of (policy, expected) tuples var policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", (string)null), ("major", (string)null), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", (string)null), ("latestMajor", (string)null), ("disable", (string)null), ("invalid", "9999.1.500"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9999.1.500", "9999.2.100-preview1", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", (string)null), ("major", (string)null), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", (string)null), ("latestMajor", (string)null), ("disable", (string)null), ("invalid", "9999.2.100-preview1"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // do not allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.501", "9999.1.503-preview5", "9999.1.503", "9999.1.504-preview1", "9999.1.504-preview2", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, "9999.1.501"), ("patch", "9999.1.501"), ("feature", "9999.1.504-preview2"), ("minor", "9999.1.504-preview2"), ("major", "9999.1.504-preview2"), ("latestPatch", "9999.1.504-preview2"), ("latestFeature", "9999.1.504-preview2"), ("latestMinor", "9999.1.504-preview2"), ("latestMajor", "9999.1.504-preview2"), ("disable", "9999.1.501"), ("invalid", "9999.1.504-preview2"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.501", "9999.1.503-preview5", "9999.1.503", "9999.1.504-preview1", "9999.1.504-preview2", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, "9999.1.501"), ("patch", "9999.1.501"), ("feature", "9999.1.503"), ("minor", "9999.1.503"), ("major", "9999.1.503"), ("latestPatch", "9999.1.503"), ("latestFeature", "9999.1.503"), ("latestMinor", "9999.1.503"), ("latestMajor", "9999.1.503"), ("disable", "9999.1.501"), ("invalid", "9999.1.504-preview2"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // don't allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.503", "9999.1.505-preview2", "9999.1.505", "9999.1.506-preview1", "9999.1.601", "9999.1.608-preview3", "9999.1.609", "9999.2.101", "9999.2.203-preview1", "9999.2.203", "10000.0.100", "10000.1.100-preview1" }; // Array of (policy, expected) tuples policies = new[] { (null, "9999.1.506-preview1"), ("patch", "9999.1.506-preview1"), ("feature", "9999.1.506-preview1"), ("minor", "9999.1.506-preview1"), ("major", "9999.1.506-preview1"), ("latestPatch", "9999.1.506-preview1"), ("latestFeature", "9999.1.609"), ("latestMinor", "9999.2.203"), ("latestMajor", "10000.1.100-preview1"), ("disable", (string)null), ("invalid", "10000.1.100-preview1"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.503", "9999.1.505-preview2", "9999.1.505", "9999.1.506-preview1", "9999.1.601", "9999.1.608-preview3", "9999.1.609", "9999.2.101", "9999.2.203-preview1", "9999.2.203", "10000.0.100", "10000.1.100-preview1" }; // Array of (policy, expected) tuples policies = new[] { (null, "9999.1.505"), ("patch", "9999.1.505"), ("feature", "9999.1.505"), ("minor", "9999.1.505"), ("major", "9999.1.505"), ("latestPatch", "9999.1.505"), ("latestFeature", "9999.1.609"), ("latestMinor", "9999.2.203"), ("latestMajor", "10000.0.100"), ("disable", (string)null), ("invalid", "10000.1.100-preview1"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // don't allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.601", "9999.1.604-preview3", "9999.1.604", "9999.1.605-preview4", "9999.1.701", "9999.1.702-preview1", "9999.1.702", "9999.2.101", "9999.2.203", "9999.2.204-preview1", "10000.0.100-preview7", "10000.0.100", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", "9999.1.605-preview4"), ("minor", "9999.1.605-preview4"), ("major", "9999.1.605-preview4"), ("latestPatch", (string)null), ("latestFeature", "9999.1.702"), ("latestMinor", "9999.2.204-preview1"), ("latestMajor", "10000.0.100"), ("disable", (string)null), ("invalid", "10000.0.100"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.601", "9999.1.604-preview3", "9999.1.604", "9999.1.605-preview4", "9999.1.701", "9999.1.702-preview1", "9999.1.702", "9999.2.101", "9999.2.203", "9999.2.204-preview1", "10000.0.100-preview7", "10000.0.100", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", "9999.1.604"), ("minor", "9999.1.604"), ("major", "9999.1.604"), ("latestPatch", (string)null), ("latestFeature", "9999.1.702"), ("latestMinor", "9999.2.203"), ("latestMajor", "10000.0.100"), ("disable", (string)null), ("invalid", "10000.0.100"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // don't allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.2.101-preview4", "9999.2.101", "9999.2.102-preview1", "9999.2.203", "9999.3.501", "9999.4.205-preview3", "10000.0.100", "10000.1.100-preview1" }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", "9999.2.102-preview1"), ("major", "9999.2.102-preview1"), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", "9999.4.205-preview3"), ("latestMajor", "10000.1.100-preview1"), ("disable", (string)null), ("invalid", "10000.1.100-preview1"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.2.101-preview4", "9999.2.101", "9999.2.102-preview1", "9999.2.203", "9999.3.501", "9999.4.205-preview3", "10000.0.100", "10000.1.100-preview1" }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", "9999.2.101"), ("major", "9999.2.101"), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", "9999.3.501"), ("latestMajor", "10000.0.100"), ("disable", (string)null), ("invalid", "10000.1.100-preview1"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // don't allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "10000.0.100", "10000.0.105-preview1", "10000.0.105", "10000.0.106-preview1", "10000.1.102", "10000.1.107", "10000.3.100", "10000.3.102-preview3", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", (string)null), ("major", "10000.0.106-preview1"), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", (string)null), ("latestMajor", "10000.3.102-preview3"), ("disable", (string)null), ("invalid", "10000.3.102-preview3"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "10000.0.100", "10000.0.105-preview1", "10000.0.105", "10000.0.106-preview1", "10000.1.102", "10000.1.107", "10000.3.100", "10000.3.102-preview3", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", (string)null), ("major", "10000.0.105"), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", (string)null), ("latestMajor", "10000.3.100"), ("disable", (string)null), ("invalid", "10000.3.102-preview3"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // don't allow prerelease policy.Item2, // expected installed // installed }; } } } // This method adds a list of new sdk version folders in the specified directory. // The actual contents are 'fake' and the mininum required for SDK discovery. // The dotnet.runtimeconfig.json created uses a dummy framework version (9999.0.0) private void AddAvailableSdkVersions(params string[] availableVersions) { foreach (string version in availableVersions) { ExecutableDotNetBuilder.AddMockSDK(version, "9999.0.0"); } } // Put a global.json file in the cwd in order to specify a CLI private void CopyGlobalJson(string globalJsonFileName) { string destFile = Path.Combine(SharedState.CurrentWorkingDir, "global.json"); string srcFile = Path.Combine(SharedState.TestAssetsPath, globalJsonFileName); File.Copy(srcFile, destFile, true); } private static string FormatGlobalJson(string version = null, string policy = null, bool? allowPrerelease = null) { version = version == null ? "null" : string.Format("\"{0}\"", version); policy = policy == null ? "null" : string.Format("\"{0}\"", policy); string allow = allowPrerelease.HasValue ? (allowPrerelease.Value ? "true" : "false") : "null"; return $@"{{ ""sdk"": {{ ""version"": {version}, ""rollForward"": {policy}, ""allowPrerelease"": {allow} }} }}"; } private void WriteGlobalJson(string contents) { File.WriteAllText(Path.Combine(SharedState.CurrentWorkingDir, "global.json"), contents); } private void WriteEmptyGlobalJson() => WriteGlobalJson("{}"); private string ExpectedResolvedSdkOutput(string expectedVersion) => Path.Combine("Using .NET SDK dll=[", ExecutableDotNet.BinPath, "sdk", expectedVersion, "dotnet.dll]"); private CommandResult RunTest() => RunTest("help"); private CommandResult RunTest(string command) { return ExecutableDotNet.Exec(command) .WorkingDirectory(SharedState.CurrentWorkingDir) .EnableTracingAndCaptureOutputs() .MultilevelLookup(false) .Execute(); } public class SharedTestState : IDisposable { private readonly RepoDirectoriesProvider RepoDirectories; public DotNetCli BuiltDotNet { get; } public string BaseDir { get; } public string CurrentWorkingDir { get; } public string TestAssetsPath { get; } public SharedTestState() { // The dotnetSDKLookup dir will contain some folders and files that will be // necessary to perform the tests string baseDir = Path.Combine(TestArtifact.TestArtifactsPath, "dotnetSDKLookup"); BaseDir = SharedFramework.CalculateUniqueTestDirectory(baseDir); // The three tested locations will be the cwd and the exe dir. cwd is no longer supported. // All dirs will be placed inside the base folder BuiltDotNet = new DotNetCli(Path.Combine(TestArtifact.TestArtifactsPath, "sharedFrameworkPublish")); RepoDirectories = new RepoDirectoriesProvider(); // Executable location is created per test as each test adds a different set of SDK versions var currentWorkingSdk = new DotNetBuilder(BaseDir, BuiltDotNet.BinPath, "current") .AddMockSDK("10000.0.0", "9999.0.0") .Build(); CurrentWorkingDir = currentWorkingSdk.BinPath; TestAssetsPath = Path.Combine(RepoDirectories.TestAssetsFolder, "TestUtils", "SDKLookup"); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (!TestArtifact.PreserveTestRuns() && Directory.Exists(BaseDir)) { Directory.Delete(BaseDir, true); } } } } } }
1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/installer/tests/HostActivation.Tests/StartupHooks.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.Linq; using Xunit; using Microsoft.Extensions.DependencyModel; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation { public class StartupHooks : IClassFixture<StartupHooks.SharedTestState> { private SharedTestState sharedTestState; private string startupHookVarName = "DOTNET_STARTUP_HOOKS"; private string startupHookRuntimeConfigName = "STARTUP_HOOKS"; private string startupHookSupport = "System.StartupHookProvider.IsSupported"; public StartupHooks(StartupHooks.SharedTestState fixture) { sharedTestState = fixture; } // Run the app with a startup hook [Fact] public void Muxer_activation_of_StartupHook_Succeeds() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookWithNonPublicMethodFixture = sharedTestState.StartupHookWithNonPublicMethodFixture.Copy(); var startupHookWithNonPublicMethodDll = startupHookWithNonPublicMethodFixture.TestProject.AppDll; // Simple startup hook dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello World"); // Non-public Initialize method dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookWithNonPublicMethodDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook with non-public method"); // Ensure startup hook tracing works dotnet.Exec(appDll) .EnvironmentVariable("COREHOST_TRACE", "1") .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining("Property STARTUP_HOOKS = " + startupHookDll) .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello World"); // Startup hook in type that has an additional overload of Initialize with a different signature startupHookFixture = sharedTestState.StartupHookWithOverloadFixture.Copy(); startupHookDll = startupHookFixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook with overload! Input: 123") .And.HaveStdOutContaining("Hello World"); } // Run the app with multiple startup hooks [Fact] public void Muxer_activation_of_Multiple_StartupHooks_Succeeds() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHook2Fixture = sharedTestState.StartupHookWithDependencyFixture.Copy(); var startupHook2Dll = startupHook2Fixture.TestProject.AppDll; // Multiple startup hooks var startupHookVar = startupHookDll + Path.PathSeparator + startupHook2Dll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello from startup hook with dependency!") .And.HaveStdOutContaining("Hello World"); } [Fact] public void Muxer_activation_of_RuntimeConfig_StartupHook_Succeeds() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; RuntimeConfig.FromFile(fixture.TestProject.RuntimeConfigJson) .WithProperty(startupHookRuntimeConfigName, startupHookDll) .Save(); // RuntimeConfig defined startup hook dotnet.Exec(appDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello World"); } [Fact] public void Muxer_activation_of_RuntimeConfig_And_Environment_StartupHooks_SucceedsInExpectedOrder() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; RuntimeConfig.FromFile(fixture.TestProject.RuntimeConfigJson) .WithProperty(startupHookRuntimeConfigName, startupHookDll) .Save(); var startupHook2Fixture = sharedTestState.StartupHookWithDependencyFixture.Copy(); var startupHook2Dll = startupHook2Fixture.TestProject.AppDll; // include any char to counter output from other threads such as in #57243 const string wildcardPattern = @"[\r\n\s.]*"; // RuntimeConfig and Environment startup hooks in expected order dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHook2Dll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutMatching("Hello from startup hook with dependency!" + wildcardPattern + "Hello from startup hook!" + wildcardPattern + "Hello World"); } // Empty startup hook variable [Fact] public void Muxer_activation_of_Empty_StartupHook_Variable_Succeeds() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookVar = ""; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello World"); } // Run the app with a startup hook assembly that depends on assemblies not on the TPA list [Fact] public void Muxer_activation_of_StartupHook_With_Missing_Dependencies_Fails() { var fixture = sharedTestState.PortableAppWithExceptionFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookWithDependencyFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; // Startup hook has a dependency not on the TPA list dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("System.IO.FileNotFoundException: Could not load file or assembly 'Newtonsoft.Json"); } // Different variants of the startup hook variable format [Fact] public void Muxer_activation_of_StartupHook_VariableVariants() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHook2Fixture = sharedTestState.StartupHookWithDependencyFixture.Copy(); var startupHook2Dll = startupHook2Fixture.TestProject.AppDll; // Missing entries in the hook var startupHookVar = startupHookDll + Path.PathSeparator + Path.PathSeparator + startupHook2Dll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello from startup hook with dependency!") .And.HaveStdOutContaining("Hello World"); // Whitespace is invalid startupHookVar = startupHookDll + Path.PathSeparator + " " + Path.PathSeparator + startupHook2Dll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("System.ArgumentException: The startup hook simple assembly name ' ' is invalid."); // Leading separator startupHookVar = Path.PathSeparator + startupHookDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello World"); // Trailing separator startupHookVar = startupHookDll + Path.PathSeparator + startupHook2Dll + Path.PathSeparator; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello from startup hook with dependency!") .And.HaveStdOutContaining("Hello World"); } [Fact] public void Muxer_activation_of_StartupHook_With_Invalid_Simple_Name_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var relativeAssemblyPath = $".{Path.DirectorySeparatorChar}Assembly"; var expectedError = "System.ArgumentException: The startup hook simple assembly name '{0}' is invalid."; // With directory separator var startupHookVar = relativeAssemblyPath; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.NotHaveStdErrContaining("--->"); // With alternative directory separator startupHookVar = $".{Path.AltDirectorySeparatorChar}Assembly"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.NotHaveStdErrContaining("--->"); // With comma startupHookVar = $"Assembly,version=1.0.0.0"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.NotHaveStdErrContaining("--->"); // With space startupHookVar = $"Assembly version"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.NotHaveStdErrContaining("--->"); // With .dll suffix startupHookVar = $".{Path.AltDirectorySeparatorChar}Assembly.DLl"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.NotHaveStdErrContaining("--->"); // With invalid name startupHookVar = $"Assembly=Name"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.HaveStdErrContaining("---> System.IO.FileLoadException: The given assembly name or codebase was invalid."); // Relative path error is caught before any hooks run startupHookVar = startupHookDll + Path.PathSeparator + relativeAssemblyPath; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, relativeAssemblyPath)) .And.NotHaveStdOutContaining("Hello from startup hook!"); } [Fact] public void Muxer_activation_of_StartupHook_With_Missing_Assembly_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var expectedError = "System.ArgumentException: Startup hook assembly '{0}' failed to load."; // With file path which doesn't exist var startupHookVar = startupHookDll + ".missing.dll"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.HaveStdErrContaining($"---> System.IO.FileNotFoundException: Could not load file or assembly '{startupHookVar}'. The system cannot find the file specified."); // With simple name which won't resolve startupHookVar = "MissingAssembly"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.HaveStdErrContaining($"---> System.IO.FileNotFoundException: Could not load file or assembly '{startupHookVar}"); } [Fact] public void Muxer_activation_of_StartupHook_WithSimpleAssemblyName_Succeeds() { var fixture = sharedTestState.PortableAppFixture.Copy(); var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookAssemblyName = Path.GetFileNameWithoutExtension(startupHookDll); File.Copy(startupHookDll, Path.Combine(fixture.TestProject.BuiltApp.Location, Path.GetFileName(startupHookDll))); SharedFramework.AddReferenceToDepsJson( fixture.TestProject.DepsJson, $"{fixture.TestProject.AssemblyName}/1.0.0", startupHookAssemblyName, "1.0.0"); fixture.BuiltDotnet.Exec(fixture.TestProject.AppDll) .EnvironmentVariable(startupHookVarName, startupHookAssemblyName) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello World"); } // Run the app with missing startup hook assembly [Fact] public void Muxer_activation_of_Missing_StartupHook_Assembly_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookMissingDll = Path.Combine(Path.GetDirectoryName(startupHookDll), "StartupHookMissing.dll"); var expectedError = "System.IO.FileNotFoundException: Could not load file or assembly '{0}'."; // Missing dll is detected with appropriate error var startupHookVar = startupHookMissingDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(String.Format(expectedError, Path.GetFullPath(startupHookMissingDll))); // Missing dll is detected after previous hooks run startupHookVar = startupHookDll + Path.PathSeparator + startupHookMissingDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdErrContaining(String.Format(expectedError, Path.GetFullPath((startupHookMissingDll)))); } // Run the app with an invalid startup hook assembly [Fact] public void Muxer_activation_of_Invalid_StartupHook_Assembly_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookInvalidAssembly = sharedTestState.StartupHookStartupHookInvalidAssemblyFixture.Copy(); var startupHookInvalidAssemblyDll = Path.Combine(Path.GetDirectoryName(startupHookInvalidAssembly.TestProject.AppDll), "StartupHookInvalidAssembly.dll"); var expectedError = "System.BadImageFormatException"; // Dll load gives meaningful error message dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookInvalidAssemblyDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(expectedError); // Dll load error happens after previous hooks run var startupHookVar = startupHookDll + Path.PathSeparator + startupHookInvalidAssemblyDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(expectedError); } // Run the app with the startup hook type missing [Fact] public void Muxer_activation_of_Missing_StartupHook_Type_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookMissingTypeFixture = sharedTestState.StartupHookWithoutStartupHookTypeFixture.Copy(); var startupHookMissingTypeDll = startupHookMissingTypeFixture.TestProject.AppDll; // Missing type is detected dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookMissingTypeDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("System.TypeLoadException: Could not load type 'StartupHook' from assembly 'StartupHook"); // Missing type is detected after previous hooks have run var startupHookVar = startupHookDll + Path.PathSeparator + startupHookMissingTypeDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdErrContaining("System.TypeLoadException: Could not load type 'StartupHook' from assembly 'StartupHookWithoutStartupHookType"); } // Run the app with a startup hook that doesn't have any Initialize method [Fact] public void Muxer_activation_of_StartupHook_With_Missing_Method_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookMissingMethodFixture = sharedTestState.StartupHookWithoutInitializeMethodFixture.Copy(); var startupHookMissingMethodDll = startupHookMissingMethodFixture.TestProject.AppDll; var expectedError = "System.MissingMethodException: Method 'StartupHook.Initialize' not found."; // No Initialize method dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookMissingMethodDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(expectedError); // Missing Initialize method is caught after previous hooks have run var startupHookVar = startupHookDll + Path.PathSeparator + startupHookMissingMethodDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdErrContaining(expectedError); } // Run the app with startup hook that has no static void Initialize() method [Fact] public void Muxer_activation_of_StartupHook_With_Incorrect_Method_Signature_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var expectedError = "System.ArgumentException: The signature of the startup hook 'StartupHook.Initialize' in assembly '{0}' was invalid. It must be 'public static void Initialize()'."; // Initialize is an instance method var startupHookWithInstanceMethodFixture = sharedTestState.StartupHookWithInstanceMethodFixture.Copy(); var startupHookWithInstanceMethodDll = startupHookWithInstanceMethodFixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookWithInstanceMethodDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(String.Format(expectedError, startupHookWithInstanceMethodDll)); // Initialize method takes parameters var startupHookWithParameterFixture = sharedTestState.StartupHookWithParameterFixture.Copy(); var startupHookWithParameterDll = startupHookWithParameterFixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookWithParameterDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(String.Format(expectedError, startupHookWithParameterDll)); // Initialize method has non-void return type var startupHookWithReturnTypeFixture = sharedTestState.StartupHookWithReturnTypeFixture.Copy(); var startupHookWithReturnTypeDll = startupHookWithReturnTypeFixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookWithReturnTypeDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(String.Format(expectedError, startupHookWithReturnTypeDll)); // Initialize method that has multiple methods with an incorrect signature var startupHookWithMultipleIncorrectSignaturesFixture = sharedTestState.StartupHookWithMultipleIncorrectSignaturesFixture.Copy(); var startupHookWithMultipleIncorrectSignaturesDll = startupHookWithMultipleIncorrectSignaturesFixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookWithMultipleIncorrectSignaturesDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(String.Format(expectedError, startupHookWithMultipleIncorrectSignaturesDll)); // Signature problem is caught after previous hooks have run var startupHookVar = startupHookDll + Path.PathSeparator + startupHookWithMultipleIncorrectSignaturesDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdErrContaining(String.Format(expectedError, startupHookWithMultipleIncorrectSignaturesDll)); } private static void RemoveLibraryFromDepsJson(string depsJsonPath, string libraryName) { DependencyContext context; using (FileStream fileStream = File.Open(depsJsonPath, FileMode.Open)) { using (DependencyContextJsonReader reader = new DependencyContextJsonReader()) { context = reader.Read(fileStream); } } context = new DependencyContext(context.Target, context.CompilationOptions, context.CompileLibraries, context.RuntimeLibraries.Select(lib => new RuntimeLibrary( lib.Type, lib.Name, lib.Version, lib.Hash, lib.RuntimeAssemblyGroups.Select(assemblyGroup => new RuntimeAssetGroup( assemblyGroup.Runtime, assemblyGroup.RuntimeFiles.Where(f => !f.Path.EndsWith("SharedLibrary.dll")))).ToList().AsReadOnly(), lib.NativeLibraryGroups, lib.ResourceAssemblies, lib.Dependencies, lib.Serviceable, lib.Path, lib.HashPath, lib.RuntimeStoreManifestName)), context.RuntimeGraph); using (FileStream fileStream = File.Open(depsJsonPath, FileMode.Truncate, FileAccess.Write)) { DependencyContextWriter writer = new DependencyContextWriter(); writer.Write(context, fileStream); } } // Run startup hook that adds an assembly resolver [Fact] public void Muxer_activation_of_StartupHook_With_Assembly_Resolver() { var fixture = sharedTestState.PortableAppWithMissingRefFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var appDepsJson = Path.Combine(Path.GetDirectoryName(appDll), Path.GetFileNameWithoutExtension(appDll) + ".deps.json"); RemoveLibraryFromDepsJson(appDepsJson, "SharedLibrary.dll"); var startupHookFixture = sharedTestState.StartupHookWithAssemblyResolver.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; // No startup hook results in failure due to missing app dependency dotnet.Exec(appDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("FileNotFoundException: Could not load file or assembly 'SharedLibrary"); // Startup hook with assembly resolver results in use of injected dependency (which has value 2) dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.ExitWith(2); } [Fact] public void Muxer_activation_of_StartupHook_With_IsSupported_False() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; RuntimeConfig.FromFile(fixture.TestProject.RuntimeConfigJson) .WithProperty(startupHookSupport, "false") .Save(); // Startup hooks are not executed when the StartupHookSupport // feature switch is set to false. dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.NotHaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello World"); } public class SharedTestState : IDisposable { // Entry point projects public TestProjectFixture PortableAppFixture { get; } public TestProjectFixture PortableAppWithExceptionFixture { get; } // Entry point with missing reference assembly public TestProjectFixture PortableAppWithMissingRefFixture { get; } // Correct startup hooks public TestProjectFixture StartupHookFixture { get; } public TestProjectFixture StartupHookWithOverloadFixture { get; } // Missing startup hook type (no StartupHook type defined) public TestProjectFixture StartupHookWithoutStartupHookTypeFixture { get; } // Missing startup hook method (no Initialize method defined) public TestProjectFixture StartupHookWithoutInitializeMethodFixture { get; } // Invalid startup hook assembly public TestProjectFixture StartupHookStartupHookInvalidAssemblyFixture { get; } // Invalid startup hooks (incorrect signatures) public TestProjectFixture StartupHookWithNonPublicMethodFixture { get; } public TestProjectFixture StartupHookWithInstanceMethodFixture { get; } public TestProjectFixture StartupHookWithParameterFixture { get; } public TestProjectFixture StartupHookWithReturnTypeFixture { get; } public TestProjectFixture StartupHookWithMultipleIncorrectSignaturesFixture { get; } // Valid startup hooks with incorrect behavior public TestProjectFixture StartupHookWithDependencyFixture { get; } // Startup hook with an assembly resolver public TestProjectFixture StartupHookWithAssemblyResolver { get; } public RepoDirectoriesProvider RepoDirectories { get; } public SharedTestState() { RepoDirectories = new RepoDirectoriesProvider(); // Entry point projects PortableAppFixture = new TestProjectFixture("PortableApp", RepoDirectories) .EnsureRestored() .PublishProject(); PortableAppWithExceptionFixture = new TestProjectFixture("PortableAppWithException", RepoDirectories) .EnsureRestored() .PublishProject(); // Entry point with missing reference assembly PortableAppWithMissingRefFixture = new TestProjectFixture("PortableAppWithMissingRef", RepoDirectories) .EnsureRestored() .PublishProject(); // Correct startup hooks StartupHookFixture = new TestProjectFixture("StartupHook", RepoDirectories) .EnsureRestored() .PublishProject(); StartupHookWithOverloadFixture = new TestProjectFixture("StartupHookWithOverload", RepoDirectories) .EnsureRestored() .PublishProject(); // Missing startup hook type (no StartupHook type defined) StartupHookWithoutStartupHookTypeFixture = new TestProjectFixture("StartupHookWithoutStartupHookType", RepoDirectories) .EnsureRestored() .PublishProject(); // Missing startup hook method (no Initialize method defined) StartupHookWithoutInitializeMethodFixture = new TestProjectFixture("StartupHookWithoutInitializeMethod", RepoDirectories) .EnsureRestored() .PublishProject(); // Invalid startup hook assembly StartupHookStartupHookInvalidAssemblyFixture = new TestProjectFixture("StartupHookFake", RepoDirectories) .EnsureRestored() .PublishProject(); // Invalid startup hooks (incorrect signatures) StartupHookWithNonPublicMethodFixture = new TestProjectFixture("StartupHookWithNonPublicMethod", RepoDirectories) .EnsureRestored() .PublishProject(); StartupHookWithInstanceMethodFixture = new TestProjectFixture("StartupHookWithInstanceMethod", RepoDirectories) .EnsureRestored() .PublishProject(); StartupHookWithParameterFixture = new TestProjectFixture("StartupHookWithParameter", RepoDirectories) .EnsureRestored() .PublishProject(); StartupHookWithReturnTypeFixture = new TestProjectFixture("StartupHookWithReturnType", RepoDirectories) .EnsureRestored() .PublishProject(); StartupHookWithMultipleIncorrectSignaturesFixture = new TestProjectFixture("StartupHookWithMultipleIncorrectSignatures", RepoDirectories) .EnsureRestored() .PublishProject(); // Valid startup hooks with incorrect behavior StartupHookWithDependencyFixture = new TestProjectFixture("StartupHookWithDependency", RepoDirectories) .EnsureRestored() .PublishProject(); // Startup hook with an assembly resolver StartupHookWithAssemblyResolver = new TestProjectFixture("StartupHookWithAssemblyResolver", RepoDirectories) .EnsureRestored() .PublishProject(); } public void Dispose() { // Entry point projects PortableAppFixture.Dispose(); PortableAppWithExceptionFixture.Dispose(); // Entry point with missing reference assembly PortableAppWithMissingRefFixture.Dispose(); // Correct startup hooks StartupHookFixture.Dispose(); StartupHookWithOverloadFixture.Dispose(); // Missing startup hook type (no StartupHook type defined) StartupHookWithoutStartupHookTypeFixture.Dispose(); // Missing startup hook method (no Initialize method defined) StartupHookWithoutInitializeMethodFixture.Dispose(); // Invalid startup hook assembly StartupHookStartupHookInvalidAssemblyFixture.Dispose(); // Invalid startup hooks (incorrect signatures) StartupHookWithNonPublicMethodFixture.Dispose(); StartupHookWithInstanceMethodFixture.Dispose(); StartupHookWithParameterFixture.Dispose(); StartupHookWithReturnTypeFixture.Dispose(); StartupHookWithMultipleIncorrectSignaturesFixture.Dispose(); // Valid startup hooks with incorrect behavior StartupHookWithDependencyFixture.Dispose(); // Startup hook with an assembly resolver StartupHookWithAssemblyResolver.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; using System.IO; using System.Linq; using Xunit; using Microsoft.Extensions.DependencyModel; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation { public class StartupHooks : IClassFixture<StartupHooks.SharedTestState> { private SharedTestState sharedTestState; private string startupHookVarName = "DOTNET_STARTUP_HOOKS"; private string startupHookRuntimeConfigName = "STARTUP_HOOKS"; private string startupHookSupport = "System.StartupHookProvider.IsSupported"; public StartupHooks(StartupHooks.SharedTestState fixture) { sharedTestState = fixture; } // Run the app with a startup hook [Fact] public void Muxer_activation_of_StartupHook_Succeeds() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookWithNonPublicMethodFixture = sharedTestState.StartupHookWithNonPublicMethodFixture.Copy(); var startupHookWithNonPublicMethodDll = startupHookWithNonPublicMethodFixture.TestProject.AppDll; // Simple startup hook dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello World"); // Non-public Initialize method dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookWithNonPublicMethodDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook with non-public method"); // Ensure startup hook tracing works dotnet.Exec(appDll) .EnvironmentVariable("COREHOST_TRACE", "1") .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining("Property STARTUP_HOOKS = " + startupHookDll) .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello World"); // Startup hook in type that has an additional overload of Initialize with a different signature startupHookFixture = sharedTestState.StartupHookWithOverloadFixture.Copy(); startupHookDll = startupHookFixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook with overload! Input: 123") .And.HaveStdOutContaining("Hello World"); } // Run the app with multiple startup hooks [Fact] public void Muxer_activation_of_Multiple_StartupHooks_Succeeds() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHook2Fixture = sharedTestState.StartupHookWithDependencyFixture.Copy(); var startupHook2Dll = startupHook2Fixture.TestProject.AppDll; // Multiple startup hooks var startupHookVar = startupHookDll + Path.PathSeparator + startupHook2Dll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello from startup hook with dependency!") .And.HaveStdOutContaining("Hello World"); } [Fact] public void Muxer_activation_of_RuntimeConfig_StartupHook_Succeeds() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; RuntimeConfig.FromFile(fixture.TestProject.RuntimeConfigJson) .WithProperty(startupHookRuntimeConfigName, startupHookDll) .Save(); // RuntimeConfig defined startup hook dotnet.Exec(appDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello World"); } [Fact] public void Muxer_activation_of_RuntimeConfig_And_Environment_StartupHooks_SucceedsInExpectedOrder() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; RuntimeConfig.FromFile(fixture.TestProject.RuntimeConfigJson) .WithProperty(startupHookRuntimeConfigName, startupHookDll) .Save(); var startupHook2Fixture = sharedTestState.StartupHookWithDependencyFixture.Copy(); var startupHook2Dll = startupHook2Fixture.TestProject.AppDll; // include any char to counter output from other threads such as in #57243 const string wildcardPattern = @"[\r\n\s.]*"; // RuntimeConfig and Environment startup hooks in expected order dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHook2Dll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutMatching("Hello from startup hook with dependency!" + wildcardPattern + "Hello from startup hook!" + wildcardPattern + "Hello World"); } // Empty startup hook variable [Fact] public void Muxer_activation_of_Empty_StartupHook_Variable_Succeeds() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookVar = ""; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello World"); } // Run the app with a startup hook assembly that depends on assemblies not on the TPA list [Fact] public void Muxer_activation_of_StartupHook_With_Missing_Dependencies_Fails() { var fixture = sharedTestState.PortableAppWithExceptionFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookWithDependencyFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; // Startup hook has a dependency not on the TPA list dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("System.IO.FileNotFoundException: Could not load file or assembly 'Newtonsoft.Json"); } // Different variants of the startup hook variable format [Fact] public void Muxer_activation_of_StartupHook_VariableVariants() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHook2Fixture = sharedTestState.StartupHookWithDependencyFixture.Copy(); var startupHook2Dll = startupHook2Fixture.TestProject.AppDll; // Missing entries in the hook var startupHookVar = startupHookDll + Path.PathSeparator + Path.PathSeparator + startupHook2Dll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello from startup hook with dependency!") .And.HaveStdOutContaining("Hello World"); // Whitespace is invalid startupHookVar = startupHookDll + Path.PathSeparator + " " + Path.PathSeparator + startupHook2Dll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("System.ArgumentException: The startup hook simple assembly name ' ' is invalid."); // Leading separator startupHookVar = Path.PathSeparator + startupHookDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello World"); // Trailing separator startupHookVar = startupHookDll + Path.PathSeparator + startupHook2Dll + Path.PathSeparator; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello from startup hook with dependency!") .And.HaveStdOutContaining("Hello World"); } [Fact] public void Muxer_activation_of_StartupHook_With_Invalid_Simple_Name_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var relativeAssemblyPath = $".{Path.DirectorySeparatorChar}Assembly"; var expectedError = "System.ArgumentException: The startup hook simple assembly name '{0}' is invalid."; // With directory separator var startupHookVar = relativeAssemblyPath; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.NotHaveStdErrContaining("--->"); // With alternative directory separator startupHookVar = $".{Path.AltDirectorySeparatorChar}Assembly"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.NotHaveStdErrContaining("--->"); // With comma startupHookVar = $"Assembly,version=1.0.0.0"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.NotHaveStdErrContaining("--->"); // With space startupHookVar = $"Assembly version"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.NotHaveStdErrContaining("--->"); // With .dll suffix startupHookVar = $".{Path.AltDirectorySeparatorChar}Assembly.DLl"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.NotHaveStdErrContaining("--->"); // With invalid name startupHookVar = $"Assembly=Name"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.HaveStdErrContaining("---> System.IO.FileLoadException: The given assembly name or codebase was invalid."); // Relative path error is caught before any hooks run startupHookVar = startupHookDll + Path.PathSeparator + relativeAssemblyPath; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, relativeAssemblyPath)) .And.NotHaveStdOutContaining("Hello from startup hook!"); } [Fact] public void Muxer_activation_of_StartupHook_With_Missing_Assembly_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var expectedError = "System.ArgumentException: Startup hook assembly '{0}' failed to load."; // With file path which doesn't exist var startupHookVar = startupHookDll + ".missing.dll"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.HaveStdErrContaining($"---> System.IO.FileNotFoundException: Could not load file or assembly '{startupHookVar}'. The system cannot find the file specified."); // With simple name which won't resolve startupHookVar = "MissingAssembly"; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookVar)) .And.HaveStdErrContaining($"---> System.IO.FileNotFoundException: Could not load file or assembly '{startupHookVar}"); } [Fact] public void Muxer_activation_of_StartupHook_WithSimpleAssemblyName_Succeeds() { var fixture = sharedTestState.PortableAppFixture.Copy(); var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookAssemblyName = Path.GetFileNameWithoutExtension(startupHookDll); File.Copy(startupHookDll, Path.Combine(fixture.TestProject.BuiltApp.Location, Path.GetFileName(startupHookDll))); SharedFramework.AddReferenceToDepsJson( fixture.TestProject.DepsJson, $"{fixture.TestProject.AssemblyName}/1.0.0", startupHookAssemblyName, "1.0.0"); fixture.BuiltDotnet.Exec(fixture.TestProject.AppDll) .EnvironmentVariable(startupHookVarName, startupHookAssemblyName) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello World"); } // Run the app with missing startup hook assembly [Fact] public void Muxer_activation_of_Missing_StartupHook_Assembly_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookMissingDll = Path.Combine(Path.GetDirectoryName(startupHookDll), "StartupHookMissing.dll"); var expectedError = "System.IO.FileNotFoundException: Could not load file or assembly '{0}'."; // Missing dll is detected with appropriate error var startupHookVar = startupHookMissingDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, Path.GetFullPath(startupHookMissingDll))); // Missing dll is detected after previous hooks run startupHookVar = startupHookDll + Path.PathSeparator + startupHookMissingDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdErrContaining(string.Format(expectedError, Path.GetFullPath((startupHookMissingDll)))); } // Run the app with an invalid startup hook assembly [Fact] public void Muxer_activation_of_Invalid_StartupHook_Assembly_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookInvalidAssembly = sharedTestState.StartupHookStartupHookInvalidAssemblyFixture.Copy(); var startupHookInvalidAssemblyDll = Path.Combine(Path.GetDirectoryName(startupHookInvalidAssembly.TestProject.AppDll), "StartupHookInvalidAssembly.dll"); var expectedError = "System.BadImageFormatException"; // Dll load gives meaningful error message dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookInvalidAssemblyDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(expectedError); // Dll load error happens after previous hooks run var startupHookVar = startupHookDll + Path.PathSeparator + startupHookInvalidAssemblyDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(expectedError); } // Run the app with the startup hook type missing [Fact] public void Muxer_activation_of_Missing_StartupHook_Type_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookMissingTypeFixture = sharedTestState.StartupHookWithoutStartupHookTypeFixture.Copy(); var startupHookMissingTypeDll = startupHookMissingTypeFixture.TestProject.AppDll; // Missing type is detected dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookMissingTypeDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("System.TypeLoadException: Could not load type 'StartupHook' from assembly 'StartupHook"); // Missing type is detected after previous hooks have run var startupHookVar = startupHookDll + Path.PathSeparator + startupHookMissingTypeDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdErrContaining("System.TypeLoadException: Could not load type 'StartupHook' from assembly 'StartupHookWithoutStartupHookType"); } // Run the app with a startup hook that doesn't have any Initialize method [Fact] public void Muxer_activation_of_StartupHook_With_Missing_Method_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var startupHookMissingMethodFixture = sharedTestState.StartupHookWithoutInitializeMethodFixture.Copy(); var startupHookMissingMethodDll = startupHookMissingMethodFixture.TestProject.AppDll; var expectedError = "System.MissingMethodException: Method 'StartupHook.Initialize' not found."; // No Initialize method dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookMissingMethodDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(expectedError); // Missing Initialize method is caught after previous hooks have run var startupHookVar = startupHookDll + Path.PathSeparator + startupHookMissingMethodDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdErrContaining(expectedError); } // Run the app with startup hook that has no static void Initialize() method [Fact] public void Muxer_activation_of_StartupHook_With_Incorrect_Method_Signature_Fails() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; var expectedError = "System.ArgumentException: The signature of the startup hook 'StartupHook.Initialize' in assembly '{0}' was invalid. It must be 'public static void Initialize()'."; // Initialize is an instance method var startupHookWithInstanceMethodFixture = sharedTestState.StartupHookWithInstanceMethodFixture.Copy(); var startupHookWithInstanceMethodDll = startupHookWithInstanceMethodFixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookWithInstanceMethodDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookWithInstanceMethodDll)); // Initialize method takes parameters var startupHookWithParameterFixture = sharedTestState.StartupHookWithParameterFixture.Copy(); var startupHookWithParameterDll = startupHookWithParameterFixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookWithParameterDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookWithParameterDll)); // Initialize method has non-void return type var startupHookWithReturnTypeFixture = sharedTestState.StartupHookWithReturnTypeFixture.Copy(); var startupHookWithReturnTypeDll = startupHookWithReturnTypeFixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookWithReturnTypeDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookWithReturnTypeDll)); // Initialize method that has multiple methods with an incorrect signature var startupHookWithMultipleIncorrectSignaturesFixture = sharedTestState.StartupHookWithMultipleIncorrectSignaturesFixture.Copy(); var startupHookWithMultipleIncorrectSignaturesDll = startupHookWithMultipleIncorrectSignaturesFixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookWithMultipleIncorrectSignaturesDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining(string.Format(expectedError, startupHookWithMultipleIncorrectSignaturesDll)); // Signature problem is caught after previous hooks have run var startupHookVar = startupHookDll + Path.PathSeparator + startupHookWithMultipleIncorrectSignaturesDll; dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookVar) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdOutContaining("Hello from startup hook!") .And.HaveStdErrContaining(string.Format(expectedError, startupHookWithMultipleIncorrectSignaturesDll)); } private static void RemoveLibraryFromDepsJson(string depsJsonPath, string libraryName) { DependencyContext context; using (FileStream fileStream = File.Open(depsJsonPath, FileMode.Open)) { using (DependencyContextJsonReader reader = new DependencyContextJsonReader()) { context = reader.Read(fileStream); } } context = new DependencyContext(context.Target, context.CompilationOptions, context.CompileLibraries, context.RuntimeLibraries.Select(lib => new RuntimeLibrary( lib.Type, lib.Name, lib.Version, lib.Hash, lib.RuntimeAssemblyGroups.Select(assemblyGroup => new RuntimeAssetGroup( assemblyGroup.Runtime, assemblyGroup.RuntimeFiles.Where(f => !f.Path.EndsWith("SharedLibrary.dll")))).ToList().AsReadOnly(), lib.NativeLibraryGroups, lib.ResourceAssemblies, lib.Dependencies, lib.Serviceable, lib.Path, lib.HashPath, lib.RuntimeStoreManifestName)), context.RuntimeGraph); using (FileStream fileStream = File.Open(depsJsonPath, FileMode.Truncate, FileAccess.Write)) { DependencyContextWriter writer = new DependencyContextWriter(); writer.Write(context, fileStream); } } // Run startup hook that adds an assembly resolver [Fact] public void Muxer_activation_of_StartupHook_With_Assembly_Resolver() { var fixture = sharedTestState.PortableAppWithMissingRefFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var appDepsJson = Path.Combine(Path.GetDirectoryName(appDll), Path.GetFileNameWithoutExtension(appDll) + ".deps.json"); RemoveLibraryFromDepsJson(appDepsJson, "SharedLibrary.dll"); var startupHookFixture = sharedTestState.StartupHookWithAssemblyResolver.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; // No startup hook results in failure due to missing app dependency dotnet.Exec(appDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("FileNotFoundException: Could not load file or assembly 'SharedLibrary"); // Startup hook with assembly resolver results in use of injected dependency (which has value 2) dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.ExitWith(2); } [Fact] public void Muxer_activation_of_StartupHook_With_IsSupported_False() { var fixture = sharedTestState.PortableAppFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var startupHookFixture = sharedTestState.StartupHookFixture.Copy(); var startupHookDll = startupHookFixture.TestProject.AppDll; RuntimeConfig.FromFile(fixture.TestProject.RuntimeConfigJson) .WithProperty(startupHookSupport, "false") .Save(); // Startup hooks are not executed when the StartupHookSupport // feature switch is set to false. dotnet.Exec(appDll) .EnvironmentVariable(startupHookVarName, startupHookDll) .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.NotHaveStdOutContaining("Hello from startup hook!") .And.HaveStdOutContaining("Hello World"); } public class SharedTestState : IDisposable { // Entry point projects public TestProjectFixture PortableAppFixture { get; } public TestProjectFixture PortableAppWithExceptionFixture { get; } // Entry point with missing reference assembly public TestProjectFixture PortableAppWithMissingRefFixture { get; } // Correct startup hooks public TestProjectFixture StartupHookFixture { get; } public TestProjectFixture StartupHookWithOverloadFixture { get; } // Missing startup hook type (no StartupHook type defined) public TestProjectFixture StartupHookWithoutStartupHookTypeFixture { get; } // Missing startup hook method (no Initialize method defined) public TestProjectFixture StartupHookWithoutInitializeMethodFixture { get; } // Invalid startup hook assembly public TestProjectFixture StartupHookStartupHookInvalidAssemblyFixture { get; } // Invalid startup hooks (incorrect signatures) public TestProjectFixture StartupHookWithNonPublicMethodFixture { get; } public TestProjectFixture StartupHookWithInstanceMethodFixture { get; } public TestProjectFixture StartupHookWithParameterFixture { get; } public TestProjectFixture StartupHookWithReturnTypeFixture { get; } public TestProjectFixture StartupHookWithMultipleIncorrectSignaturesFixture { get; } // Valid startup hooks with incorrect behavior public TestProjectFixture StartupHookWithDependencyFixture { get; } // Startup hook with an assembly resolver public TestProjectFixture StartupHookWithAssemblyResolver { get; } public RepoDirectoriesProvider RepoDirectories { get; } public SharedTestState() { RepoDirectories = new RepoDirectoriesProvider(); // Entry point projects PortableAppFixture = new TestProjectFixture("PortableApp", RepoDirectories) .EnsureRestored() .PublishProject(); PortableAppWithExceptionFixture = new TestProjectFixture("PortableAppWithException", RepoDirectories) .EnsureRestored() .PublishProject(); // Entry point with missing reference assembly PortableAppWithMissingRefFixture = new TestProjectFixture("PortableAppWithMissingRef", RepoDirectories) .EnsureRestored() .PublishProject(); // Correct startup hooks StartupHookFixture = new TestProjectFixture("StartupHook", RepoDirectories) .EnsureRestored() .PublishProject(); StartupHookWithOverloadFixture = new TestProjectFixture("StartupHookWithOverload", RepoDirectories) .EnsureRestored() .PublishProject(); // Missing startup hook type (no StartupHook type defined) StartupHookWithoutStartupHookTypeFixture = new TestProjectFixture("StartupHookWithoutStartupHookType", RepoDirectories) .EnsureRestored() .PublishProject(); // Missing startup hook method (no Initialize method defined) StartupHookWithoutInitializeMethodFixture = new TestProjectFixture("StartupHookWithoutInitializeMethod", RepoDirectories) .EnsureRestored() .PublishProject(); // Invalid startup hook assembly StartupHookStartupHookInvalidAssemblyFixture = new TestProjectFixture("StartupHookFake", RepoDirectories) .EnsureRestored() .PublishProject(); // Invalid startup hooks (incorrect signatures) StartupHookWithNonPublicMethodFixture = new TestProjectFixture("StartupHookWithNonPublicMethod", RepoDirectories) .EnsureRestored() .PublishProject(); StartupHookWithInstanceMethodFixture = new TestProjectFixture("StartupHookWithInstanceMethod", RepoDirectories) .EnsureRestored() .PublishProject(); StartupHookWithParameterFixture = new TestProjectFixture("StartupHookWithParameter", RepoDirectories) .EnsureRestored() .PublishProject(); StartupHookWithReturnTypeFixture = new TestProjectFixture("StartupHookWithReturnType", RepoDirectories) .EnsureRestored() .PublishProject(); StartupHookWithMultipleIncorrectSignaturesFixture = new TestProjectFixture("StartupHookWithMultipleIncorrectSignatures", RepoDirectories) .EnsureRestored() .PublishProject(); // Valid startup hooks with incorrect behavior StartupHookWithDependencyFixture = new TestProjectFixture("StartupHookWithDependency", RepoDirectories) .EnsureRestored() .PublishProject(); // Startup hook with an assembly resolver StartupHookWithAssemblyResolver = new TestProjectFixture("StartupHookWithAssemblyResolver", RepoDirectories) .EnsureRestored() .PublishProject(); } public void Dispose() { // Entry point projects PortableAppFixture.Dispose(); PortableAppWithExceptionFixture.Dispose(); // Entry point with missing reference assembly PortableAppWithMissingRefFixture.Dispose(); // Correct startup hooks StartupHookFixture.Dispose(); StartupHookWithOverloadFixture.Dispose(); // Missing startup hook type (no StartupHook type defined) StartupHookWithoutStartupHookTypeFixture.Dispose(); // Missing startup hook method (no Initialize method defined) StartupHookWithoutInitializeMethodFixture.Dispose(); // Invalid startup hook assembly StartupHookStartupHookInvalidAssemblyFixture.Dispose(); // Invalid startup hooks (incorrect signatures) StartupHookWithNonPublicMethodFixture.Dispose(); StartupHookWithInstanceMethodFixture.Dispose(); StartupHookWithParameterFixture.Dispose(); StartupHookWithReturnTypeFixture.Dispose(); StartupHookWithMultipleIncorrectSignaturesFixture.Dispose(); // Valid startup hooks with incorrect behavior StartupHookWithDependencyFixture.Dispose(); // Startup hook with an assembly resolver StartupHookWithAssemblyResolver.Dispose(); } } } }
1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/installer/tests/TestUtils/Command.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.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; namespace Microsoft.DotNet.Cli.Build.Framework { public class Command { private StringWriter _stdOutCapture; private StringWriter _stdErrCapture; private Action<string> _stdOutForward; private Action<string> _stdErrForward; private Action<string> _stdOutHandler; private Action<string> _stdErrHandler; private bool _running = false; private bool _quietBuildReporter = false; public Process Process { get; } // Priority order of runnable suffixes to look for and run private static readonly string[] RunnableSuffixes = OperatingSystem.IsWindows() ? new string[] { ".exe", ".cmd", ".bat" } : new string[] { string.Empty }; private Command(string executable, string args) { // Set the things we need var psi = new ProcessStartInfo() { FileName = executable, Arguments = args }; Process = new Process() { StartInfo = psi }; } public static Command Create(string executable, params string[] args) { return Create(executable, ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(args)); } public static Command Create(string executable, IEnumerable<string> args) { return Create(executable, ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(args)); } public static Command Create(string executable, string args) { ResolveExecutablePath(ref executable, ref args); return new Command(executable, args); } private static void ResolveExecutablePath(ref string executable, ref string args) { foreach (string suffix in RunnableSuffixes) { var fullExecutable = Path.GetFullPath(Path.Combine( AppContext.BaseDirectory, executable + suffix)); if (File.Exists(fullExecutable)) { executable = fullExecutable; // In priority order we've found the best runnable extension, so break. break; } } // On Windows, we want to avoid using "cmd" if possible (it mangles the colors, and a bunch of other things) // So, do a quick path search to see if we can just directly invoke it var useCmd = ShouldUseCmd(executable); if (useCmd) { var comSpec = System.Environment.GetEnvironmentVariable("ComSpec"); // cmd doesn't like "foo.exe ", so we need to ensure that if // args is empty, we just run "foo.exe" if (!string.IsNullOrEmpty(args)) { executable = (executable + " " + args).Replace("\"", "\\\""); } args = $"/C \"{executable}\""; executable = comSpec; } } private static bool ShouldUseCmd(string executable) { if (OperatingSystem.IsWindows()) { var extension = Path.GetExtension(executable); if (!string.IsNullOrEmpty(extension)) { return !string.Equals(extension, ".exe", StringComparison.Ordinal); } else if (executable.Contains(Path.DirectorySeparatorChar)) { // It's a relative path without an extension if (File.Exists(executable + ".exe")) { // It refers to an exe! return false; } } else { // Search the path to see if we can find it foreach (var path in System.Environment.GetEnvironmentVariable("PATH").Split(Path.PathSeparator)) { var candidate = Path.Combine(path, executable + ".exe"); if (File.Exists(candidate)) { // We found an exe! return false; } } } // It's a non-exe :( return true; } // Non-windows never uses cmd return false; } public Command Environment(IDictionary<string, string> env) { if (env == null) { return this; } foreach (var item in env) { Process.StartInfo.Environment[item.Key] = item.Value; } return this; } public Command Environment(string key, string value) { Process.StartInfo.Environment[key] = value; return this; } public Command QuietBuildReporter() { _quietBuildReporter = true; return this; } public CommandResult Execute() { return Execute(false); } public Command Start() { ThrowIfRunning(); _running = true; if (Process.StartInfo.RedirectStandardOutput) { Process.OutputDataReceived += (sender, args) => { ProcessData(args.Data, _stdOutCapture, _stdOutForward, _stdOutHandler); }; } if (Process.StartInfo.RedirectStandardError) { Process.ErrorDataReceived += (sender, args) => { ProcessData(args.Data, _stdErrCapture, _stdErrForward, _stdErrHandler); }; } Process.EnableRaisingEvents = true; ReportExecBegin(); // Retry if we hit ETXTBSY due to Linux race // https://github.com/dotnet/runtime/issues/58964 for (int i = 0; ; i++) { try { Process.Start(); break; } catch (Win32Exception e) when (i < 4 && e.Message.Contains("Text file busy")) { Thread.Sleep(i * 20); } } if (Process.StartInfo.RedirectStandardOutput) { Process.BeginOutputReadLine(); } if (Process.StartInfo.RedirectStandardError) { Process.BeginErrorReadLine(); } return this; } public CommandResult WaitForExit(bool fExpectedToFail, int timeoutMilliseconds = Timeout.Infinite) { ReportExecWaitOnExit(); int exitCode; if (!Process.WaitForExit(timeoutMilliseconds)) { exitCode = -1; } else { exitCode = Process.ExitCode; } ReportExecEnd(exitCode, fExpectedToFail); return new CommandResult( Process.StartInfo, exitCode, _stdOutCapture?.GetStringBuilder()?.ToString(), _stdErrCapture?.GetStringBuilder()?.ToString()); } public CommandResult Execute(bool fExpectedToFail) { Start(); return WaitForExit(fExpectedToFail); } public Command WorkingDirectory(string projectDirectory) { Process.StartInfo.WorkingDirectory = projectDirectory; return this; } public Command WithUserProfile(string userprofile) { string userDir; if (OperatingSystem.IsWindows()) { userDir = "USERPROFILE"; } else { userDir = "HOME"; } Process.StartInfo.Environment[userDir] = userprofile; return this; } public Command EnvironmentVariable(string name, string value) { if (value == null) { value = ""; } Process.StartInfo.Environment[name] = value; return this; } public Command CaptureStdOut() { ThrowIfRunning(); Process.StartInfo.RedirectStandardOutput = true; _stdOutCapture = new StringWriter(); return this; } public Command CaptureStdErr() { ThrowIfRunning(); Process.StartInfo.RedirectStandardError = true; _stdErrCapture = new StringWriter(); return this; } public Command ForwardStdOut(TextWriter to = null) { ThrowIfRunning(); Process.StartInfo.RedirectStandardOutput = true; if (to == null) { _stdOutForward = Reporter.Output.WriteLine; } else { _stdOutForward = to.WriteLine; } return this; } public Command ForwardStdErr(TextWriter to = null) { ThrowIfRunning(); Process.StartInfo.RedirectStandardError = true; if (to == null) { _stdErrForward = Reporter.Error.WriteLine; } else { _stdErrForward = to.WriteLine; } return this; } public Command OnOutputLine(Action<string> handler) { ThrowIfRunning(); Process.StartInfo.RedirectStandardOutput = true; if (_stdOutHandler != null) { throw new InvalidOperationException("Already handling stdout!"); } _stdOutHandler = handler; return this; } public Command OnErrorLine(Action<string> handler) { ThrowIfRunning(); Process.StartInfo.RedirectStandardError = true; if (_stdErrHandler != null) { throw new InvalidOperationException("Already handling stderr!"); } _stdErrHandler = handler; return this; } private string FormatProcessInfo(ProcessStartInfo info, bool includeWorkingDirectory) { string prefix = includeWorkingDirectory ? $"{info.WorkingDirectory}> {info.FileName}" : info.FileName; if (string.IsNullOrWhiteSpace(info.Arguments)) { return prefix; } return prefix + " " + info.Arguments; } private void ReportExecBegin() { if (!_quietBuildReporter) { BuildReporter.BeginSection("EXEC", FormatProcessInfo(Process.StartInfo, includeWorkingDirectory: false)); } } private void ReportExecWaitOnExit() { if (!_quietBuildReporter) { BuildReporter.SectionComment("EXEC", $"Waiting for process {Process.Id} to exit..."); } } private void ReportExecEnd(int exitCode, bool fExpectedToFail) { if (!_quietBuildReporter) { bool success = exitCode == 0; string msgExpectedToFail = ""; if (fExpectedToFail) { success = !success; msgExpectedToFail = "failed as expected and "; } var message = $"{FormatProcessInfo(Process.StartInfo, includeWorkingDirectory: !success)} {msgExpectedToFail}exited with {exitCode}"; BuildReporter.EndSection( "EXEC", success ? message.Green() : message.Red().Bold(), success); } } private void ThrowIfRunning([CallerMemberName] string memberName = null) { if (_running) { throw new InvalidOperationException($"Unable to invoke {memberName} after the command has been run"); } } private void ProcessData(string data, StringWriter capture, Action<string> forward, Action<string> handler) { if (data == null) { return; } if (capture != null) { capture.WriteLine(data); } forward?.Invoke(data); handler?.Invoke(data); } } }
// 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.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; namespace Microsoft.DotNet.Cli.Build.Framework { public class Command { private StringWriter _stdOutCapture; private StringWriter _stdErrCapture; private Action<string> _stdOutForward; private Action<string> _stdErrForward; private Action<string> _stdOutHandler; private Action<string> _stdErrHandler; private bool _running = false; private bool _quietBuildReporter = false; public Process Process { get; } // Priority order of runnable suffixes to look for and run private static readonly string[] RunnableSuffixes = OperatingSystem.IsWindows() ? new string[] { ".exe", ".cmd", ".bat" } : new string[] { string.Empty }; private Command(string executable, string args) { // Set the things we need var psi = new ProcessStartInfo() { FileName = executable, Arguments = args }; Process = new Process() { StartInfo = psi }; } public static Command Create(string executable, params string[] args) { return Create(executable, ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(args)); } public static Command Create(string executable, IEnumerable<string> args) { return Create(executable, ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(args)); } public static Command Create(string executable, string args) { ResolveExecutablePath(ref executable, ref args); return new Command(executable, args); } private static void ResolveExecutablePath(ref string executable, ref string args) { foreach (string suffix in RunnableSuffixes) { var fullExecutable = Path.GetFullPath(Path.Combine( AppContext.BaseDirectory, executable + suffix)); if (File.Exists(fullExecutable)) { executable = fullExecutable; // In priority order we've found the best runnable extension, so break. break; } } // On Windows, we want to avoid using "cmd" if possible (it mangles the colors, and a bunch of other things) // So, do a quick path search to see if we can just directly invoke it var useCmd = ShouldUseCmd(executable); if (useCmd) { var comSpec = System.Environment.GetEnvironmentVariable("ComSpec"); // cmd doesn't like "foo.exe ", so we need to ensure that if // args is empty, we just run "foo.exe" if (!string.IsNullOrEmpty(args)) { executable = (executable + " " + args).Replace("\"", "\\\""); } args = $"/C \"{executable}\""; executable = comSpec; } } private static bool ShouldUseCmd(string executable) { if (OperatingSystem.IsWindows()) { var extension = Path.GetExtension(executable); if (!string.IsNullOrEmpty(extension)) { return !string.Equals(extension, ".exe", StringComparison.Ordinal); } else if (executable.Contains(Path.DirectorySeparatorChar)) { // It's a relative path without an extension if (File.Exists(executable + ".exe")) { // It refers to an exe! return false; } } else { // Search the path to see if we can find it foreach (var path in System.Environment.GetEnvironmentVariable("PATH").Split(Path.PathSeparator)) { var candidate = Path.Combine(path, executable + ".exe"); if (File.Exists(candidate)) { // We found an exe! return false; } } } // It's a non-exe :( return true; } // Non-windows never uses cmd return false; } public Command Environment(IDictionary<string, string> env) { if (env == null) { return this; } foreach (var item in env) { Process.StartInfo.Environment[item.Key] = item.Value; } return this; } public Command Environment(string key, string value) { Process.StartInfo.Environment[key] = value; return this; } public Command QuietBuildReporter() { _quietBuildReporter = true; return this; } public CommandResult Execute() { return Execute(false); } public Command Start() { ThrowIfRunning(); _running = true; if (Process.StartInfo.RedirectStandardOutput) { Process.OutputDataReceived += (sender, args) => { ProcessData(args.Data, _stdOutCapture, _stdOutForward, _stdOutHandler); }; } if (Process.StartInfo.RedirectStandardError) { Process.ErrorDataReceived += (sender, args) => { ProcessData(args.Data, _stdErrCapture, _stdErrForward, _stdErrHandler); }; } Process.EnableRaisingEvents = true; ReportExecBegin(); // Retry if we hit ETXTBSY due to Linux race // https://github.com/dotnet/runtime/issues/58964 for (int i = 0; ; i++) { try { Process.Start(); break; } catch (Win32Exception e) when (i < 4 && e.Message.Contains("Text file busy")) { Thread.Sleep(i * 20); } } if (Process.StartInfo.RedirectStandardOutput) { Process.BeginOutputReadLine(); } if (Process.StartInfo.RedirectStandardError) { Process.BeginErrorReadLine(); } return this; } public CommandResult WaitForExit(bool fExpectedToFail, int timeoutMilliseconds = Timeout.Infinite) { ReportExecWaitOnExit(); int exitCode; if (!Process.WaitForExit(timeoutMilliseconds)) { exitCode = -1; } else { exitCode = Process.ExitCode; } ReportExecEnd(exitCode, fExpectedToFail); return new CommandResult( Process.StartInfo, exitCode, _stdOutCapture?.GetStringBuilder()?.ToString(), _stdErrCapture?.GetStringBuilder()?.ToString()); } public CommandResult Execute(bool fExpectedToFail) { Start(); return WaitForExit(fExpectedToFail); } public Command WorkingDirectory(string projectDirectory) { Process.StartInfo.WorkingDirectory = projectDirectory; return this; } public Command EnvironmentVariable(string name, string value) { if (value == null) { value = ""; } Process.StartInfo.Environment[name] = value; return this; } public Command RemoveEnvironmentVariable(string name) { Process.StartInfo.Environment.Remove(name); return this; } public Command CaptureStdOut() { ThrowIfRunning(); Process.StartInfo.RedirectStandardOutput = true; _stdOutCapture = new StringWriter(); return this; } public Command CaptureStdErr() { ThrowIfRunning(); Process.StartInfo.RedirectStandardError = true; _stdErrCapture = new StringWriter(); return this; } public Command ForwardStdOut(TextWriter to = null) { ThrowIfRunning(); Process.StartInfo.RedirectStandardOutput = true; if (to == null) { _stdOutForward = Reporter.Output.WriteLine; } else { _stdOutForward = to.WriteLine; } return this; } public Command ForwardStdErr(TextWriter to = null) { ThrowIfRunning(); Process.StartInfo.RedirectStandardError = true; if (to == null) { _stdErrForward = Reporter.Error.WriteLine; } else { _stdErrForward = to.WriteLine; } return this; } public Command OnOutputLine(Action<string> handler) { ThrowIfRunning(); Process.StartInfo.RedirectStandardOutput = true; if (_stdOutHandler != null) { throw new InvalidOperationException("Already handling stdout!"); } _stdOutHandler = handler; return this; } public Command OnErrorLine(Action<string> handler) { ThrowIfRunning(); Process.StartInfo.RedirectStandardError = true; if (_stdErrHandler != null) { throw new InvalidOperationException("Already handling stderr!"); } _stdErrHandler = handler; return this; } private string FormatProcessInfo(ProcessStartInfo info, bool includeWorkingDirectory) { string prefix = includeWorkingDirectory ? $"{info.WorkingDirectory}> {info.FileName}" : info.FileName; if (string.IsNullOrWhiteSpace(info.Arguments)) { return prefix; } return prefix + " " + info.Arguments; } private void ReportExecBegin() { if (!_quietBuildReporter) { BuildReporter.BeginSection("EXEC", FormatProcessInfo(Process.StartInfo, includeWorkingDirectory: false)); } } private void ReportExecWaitOnExit() { if (!_quietBuildReporter) { BuildReporter.SectionComment("EXEC", $"Waiting for process {Process.Id} to exit..."); } } private void ReportExecEnd(int exitCode, bool fExpectedToFail) { if (!_quietBuildReporter) { bool success = exitCode == 0; string msgExpectedToFail = ""; if (fExpectedToFail) { success = !success; msgExpectedToFail = "failed as expected and "; } var message = $"{FormatProcessInfo(Process.StartInfo, includeWorkingDirectory: !success)} {msgExpectedToFail}exited with {exitCode}"; BuildReporter.EndSection( "EXEC", success ? message.Green() : message.Red().Bold(), success); } } private void ThrowIfRunning([CallerMemberName] string memberName = null) { if (_running) { throw new InvalidOperationException($"Unable to invoke {memberName} after the command has been run"); } } private void ProcessData(string data, StringWriter capture, Action<string> forward, Action<string> handler) { if (data == null) { return; } if (capture != null) { capture.WriteLine(data); } forward?.Invoke(data); handler?.Invoke(data); } } }
1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/installer/tests/TestUtils/CommandExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.DotNet.Cli.Build.Framework; using Microsoft.DotNet.CoreSetup.Test; using System; using System.IO; namespace Microsoft.DotNet.CoreSetup.Test { public static class CommandExtensions { public static Command EnableHostTracing(this Command command) { return command.EnvironmentVariable(Constants.HostTracing.TraceLevelEnvironmentVariable, "1"); } public static Command EnableHostTracingToFile(this Command command, out string filePath) { filePath = Path.Combine(TestArtifact.TestArtifactsPath, "trace" + Guid.NewGuid().ToString() + ".log"); if (File.Exists(filePath)) { File.Delete(filePath); } return command .EnableHostTracing() .EnvironmentVariable(Constants.HostTracing.TraceFileEnvironmentVariable, filePath); } public static Command EnableTracingAndCaptureOutputs(this Command command) { return command .EnableHostTracing() .CaptureStdOut() .CaptureStdErr(); } public static Command DotNetRoot(this Command command, string dotNetRoot, string architecture = null) { if (!string.IsNullOrEmpty(architecture)) return command.EnvironmentVariable(Constants.DotnetRoot.ArchitectureEnvironmentVariablePrefix + architecture.ToUpper(), dotNetRoot); return command .EnvironmentVariable(Constants.DotnetRoot.EnvironmentVariable, dotNetRoot) .EnvironmentVariable(Constants.DotnetRoot.WindowsX86EnvironmentVariable, dotNetRoot); } public static Command MultilevelLookup(this Command command, bool enable) { return command.EnvironmentVariable(Constants.MultilevelLookup.EnvironmentVariable, enable ? "1" : "0"); } public static Command RuntimeId(this Command command, string rid) { return command.EnvironmentVariable(Constants.RuntimeId.EnvironmentVariable, rid); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.DotNet.Cli.Build.Framework; using Microsoft.DotNet.CoreSetup.Test; using System; using System.IO; namespace Microsoft.DotNet.CoreSetup.Test { public static class CommandExtensions { public static Command EnableHostTracing(this Command command) { return command.EnvironmentVariable(Constants.HostTracing.TraceLevelEnvironmentVariable, "1"); } public static Command EnableHostTracingToFile(this Command command, out string filePath) { filePath = Path.Combine(TestArtifact.TestArtifactsPath, "trace" + Guid.NewGuid().ToString() + ".log"); if (File.Exists(filePath)) { File.Delete(filePath); } return command .EnableHostTracing() .EnvironmentVariable(Constants.HostTracing.TraceFileEnvironmentVariable, filePath); } public static Command EnableTracingAndCaptureOutputs(this Command command) { return command .EnableHostTracing() .CaptureStdOut() .CaptureStdErr(); } public static Command DotNetRoot(this Command command, string dotNetRoot, string architecture = null) { if (!string.IsNullOrEmpty(architecture)) return command.EnvironmentVariable(Constants.DotnetRoot.ArchitectureEnvironmentVariablePrefix + architecture.ToUpper(), dotNetRoot); return command .EnvironmentVariable(Constants.DotnetRoot.EnvironmentVariable, dotNetRoot) .EnvironmentVariable(Constants.DotnetRoot.WindowsX86EnvironmentVariable, dotNetRoot); } public static Command MultilevelLookup(this Command command, bool? enable) { if (enable.HasValue) return command.EnvironmentVariable(Constants.MultilevelLookup.EnvironmentVariable, enable.Value ? "1" : "0"); return command.RemoveEnvironmentVariable(Constants.MultilevelLookup.EnvironmentVariable); } public static Command RuntimeId(this Command command, string rid) { return command.EnvironmentVariable(Constants.RuntimeId.EnvironmentVariable, rid); } } }
1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/installer/tests/TestUtils/Constants.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.DotNet.CoreSetup.Test { public static class Constants { public const string MicrosoftNETCoreApp = "Microsoft.NETCore.App"; public static class ApplyPatchesSetting { public const string RuntimeConfigPropertyName = "applyPatches"; } public static class RollForwardOnNoCandidateFxSetting { public const string RuntimeConfigPropertyName = "rollForwardOnNoCandidateFx"; public const string CommandLineArgument = "--roll-forward-on-no-candidate-fx"; public const string EnvironmentVariable = "DOTNET_ROLL_FORWARD_ON_NO_CANDIDATE_FX"; } public static class RollForwardSetting { public const string RuntimeConfigPropertyName = "rollForward"; public const string CommandLineArgument = "--roll-forward"; public const string EnvironmentVariable = "DOTNET_ROLL_FORWARD"; public const string LatestPatch = "LatestPatch"; public const string Minor = "Minor"; public const string Major = "Major"; public const string LatestMinor = "LatestMinor"; public const string LatestMajor = "LatestMajor"; public const string Disable = "Disable"; } public static class FxVersion { public const string CommandLineArgument = "--fx-version"; } public static class RollForwardToPreRelease { public const string EnvironmentVariable = "DOTNET_ROLL_FORWARD_TO_PRERELEASE"; } public static class DisableGuiErrors { public const string EnvironmentVariable = "DOTNET_DISABLE_GUI_ERRORS"; } public static class TestOnlyEnvironmentVariables { public const string DefaultInstallPath = "_DOTNET_TEST_DEFAULT_INSTALL_PATH"; public const string RegistryPath = "_DOTNET_TEST_REGISTRY_PATH"; public const string GloballyRegisteredPath = "_DOTNET_TEST_GLOBALLY_REGISTERED_PATH"; public const string InstallLocationPath = "_DOTNET_TEST_INSTALL_LOCATION_PATH"; } public static class RuntimeId { public const string EnvironmentVariable = "DOTNET_RUNTIME_ID"; } public static class MultilevelLookup { public const string EnvironmentVariable = "DOTNET_MULTILEVEL_LOOKUP"; } public static class HostTracing { public const string TraceLevelEnvironmentVariable = "COREHOST_TRACE"; public const string TraceFileEnvironmentVariable = "COREHOST_TRACEFILE"; } public static class DotnetRoot { public const string EnvironmentVariable = "DOTNET_ROOT"; public const string WindowsX86EnvironmentVariable = "DOTNET_ROOT(x86)"; public const string ArchitectureEnvironmentVariablePrefix = "DOTNET_ROOT_"; } public static class ErrorCode { public const int InvalidArgFailure = unchecked((int)0x80008081); public const int CoreHostLibMissingFailure = unchecked((int)0x80008083); public const int ResolverInitFailure = unchecked((int)0x8000808b); public const int ResolverResolveFailure = unchecked((int)0x8000808c); public const int LibHostInvalidArgs = unchecked((int)0x80008092); public const int AppArgNotRunnable = unchecked((int)0x80008094); public const int FrameworkMissingFailure = unchecked((int)0x80008096); public const int BundleExtractionFailure = unchecked((int)0x8000809f); public const int COMPlusException = unchecked((int)0xe0434352); public const int SIGABRT = 134; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.DotNet.CoreSetup.Test { public static class Constants { public const string MicrosoftNETCoreApp = "Microsoft.NETCore.App"; public static class ApplyPatchesSetting { public const string RuntimeConfigPropertyName = "applyPatches"; } public static class RollForwardOnNoCandidateFxSetting { public const string RuntimeConfigPropertyName = "rollForwardOnNoCandidateFx"; public const string CommandLineArgument = "--roll-forward-on-no-candidate-fx"; public const string EnvironmentVariable = "DOTNET_ROLL_FORWARD_ON_NO_CANDIDATE_FX"; } public static class RollForwardSetting { public const string RuntimeConfigPropertyName = "rollForward"; public const string CommandLineArgument = "--roll-forward"; public const string EnvironmentVariable = "DOTNET_ROLL_FORWARD"; public const string LatestPatch = "LatestPatch"; public const string Minor = "Minor"; public const string Major = "Major"; public const string LatestMinor = "LatestMinor"; public const string LatestMajor = "LatestMajor"; public const string Disable = "Disable"; } public static class Tfm { public const string RuntimeConfigPropertyName = "tfm"; public const string NetCoreApp30 = "netcoreapp3.0"; public const string NetCoreApp31 = "netcoreapp3.1"; public const string Net5 = "net5.0"; public const string Net6 = "net6.0"; public const string Net7 = "net7.0"; } public static class FxVersion { public const string CommandLineArgument = "--fx-version"; } public static class RollForwardToPreRelease { public const string EnvironmentVariable = "DOTNET_ROLL_FORWARD_TO_PRERELEASE"; } public static class DisableGuiErrors { public const string EnvironmentVariable = "DOTNET_DISABLE_GUI_ERRORS"; } public static class TestOnlyEnvironmentVariables { public const string DefaultInstallPath = "_DOTNET_TEST_DEFAULT_INSTALL_PATH"; public const string RegistryPath = "_DOTNET_TEST_REGISTRY_PATH"; public const string GloballyRegisteredPath = "_DOTNET_TEST_GLOBALLY_REGISTERED_PATH"; public const string InstallLocationPath = "_DOTNET_TEST_INSTALL_LOCATION_PATH"; } public static class RuntimeId { public const string EnvironmentVariable = "DOTNET_RUNTIME_ID"; } public static class MultilevelLookup { public const string EnvironmentVariable = "DOTNET_MULTILEVEL_LOOKUP"; } public static class HostTracing { public const string TraceLevelEnvironmentVariable = "COREHOST_TRACE"; public const string TraceFileEnvironmentVariable = "COREHOST_TRACEFILE"; } public static class DotnetRoot { public const string EnvironmentVariable = "DOTNET_ROOT"; public const string WindowsX86EnvironmentVariable = "DOTNET_ROOT(x86)"; public const string ArchitectureEnvironmentVariablePrefix = "DOTNET_ROOT_"; } public static class ErrorCode { public const int InvalidArgFailure = unchecked((int)0x80008081); public const int CoreHostLibMissingFailure = unchecked((int)0x80008083); public const int ResolverInitFailure = unchecked((int)0x8000808b); public const int ResolverResolveFailure = unchecked((int)0x8000808c); public const int LibHostInvalidArgs = unchecked((int)0x80008092); public const int AppArgNotRunnable = unchecked((int)0x80008094); public const int FrameworkMissingFailure = unchecked((int)0x80008096); public const int BundleExtractionFailure = unchecked((int)0x8000809f); public const int COMPlusException = unchecked((int)0xe0434352); public const int SIGABRT = 134; } } }
1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/installer/tests/TestUtils/DotNetBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.DotNet.Cli.Build; using System; using System.IO; namespace Microsoft.DotNet.CoreSetup.Test { /// <summary> /// Helper class for creating a mock version of a dotnet installation /// </summary> /// <remarks> /// This class uses a mock version of hostpolicy and does not use the product coreclr runtime, /// so the mock installation cannot be used to actually run apps. /// </remarks> public class DotNetBuilder { private readonly string _path; private readonly RepoDirectoriesProvider _repoDirectories; public DotNetBuilder(string basePath, string builtDotnet, string name) { _path = Path.Combine(basePath, name); Directory.CreateDirectory(_path); _repoDirectories = new RepoDirectoriesProvider(builtDotnet: _path); // Prepare the dotnet installation mock // ./dotnet.exe - used as a convenient way to load and invoke hostfxr. May change in the future to use test-specific executable var builtDotNetCli = new DotNetCli(builtDotnet); File.Copy( builtDotNetCli.DotnetExecutablePath, Path.Combine(_path, RuntimeInformationExtensions.GetExeFileNameForCurrentPlatform("dotnet")), true); // ./host/fxr/<version>/hostfxr.dll - this is the component being tested SharedFramework.CopyDirectory( builtDotNetCli.GreatestVersionHostFxrPath, Path.Combine(_path, "host", "fxr", Path.GetFileName(builtDotNetCli.GreatestVersionHostFxrPath))); } /// <summary> /// Add a mock of the Microsoft.NETCore.App framework with the specified version /// </summary> /// <param name="version">Version to add</param> /// <remarks> /// Product runtime binaries are not added. All the added mock framework will contain is a mock version of host policy. /// </remarks> public DotNetBuilder AddMicrosoftNETCoreAppFrameworkMockHostPolicy(string version) { // ./shared/Microsoft.NETCore.App/<version> - create a mock of the root framework string netCoreAppPath = Path.Combine(_path, "shared", "Microsoft.NETCore.App", version); Directory.CreateDirectory(netCoreAppPath); // ./shared/Microsoft.NETCore.App/<version>/hostpolicy.dll - this is a mock, will not actually load CoreCLR string mockHostPolicyFileName = RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("mockhostpolicy"); File.Copy( Path.Combine(_repoDirectories.Artifacts, "corehost_test", mockHostPolicyFileName), Path.Combine(netCoreAppPath, RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostpolicy")), true); return this; } /// <summary> /// Use a mock version of HostFxr. /// </summary> /// <param name="version">Version to add</param> public DotNetBuilder AddMockHostFxr(Version version) { string hostfxrPath = Path.Combine(_path, "host", "fxr", version.ToString()); Directory.CreateDirectory(hostfxrPath); string mockHostFxrFileNameBase = version switch { { Major: 2, Minor: 2 } => "mockhostfxr_2_2", { Major: 5, Minor: 0 } => "mockhostfxr_5_0", _ => throw new InvalidOperationException($"Unsupported version {version} of mockhostfxr.") }; string mockHostFxrFileName = RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform(mockHostFxrFileNameBase); File.Copy( Path.Combine(_repoDirectories.Artifacts, "corehost_test", mockHostFxrFileName), Path.Combine(hostfxrPath, RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostfxr")), true); return this; } /// <summary> /// Removes the specified HostFxr version. If no version is set, it'll delete all versions found. /// </summary> /// <param name="version">Version to remove</param> public DotNetBuilder RemoveHostFxr(Version version = null) { if (version != null) { new DirectoryInfo(Path.Combine(_path, "host", "fxr", version.ToString())).Delete(recursive: true); } else { foreach (var dir in new DirectoryInfo(Path.Combine(_path, "host", "fxr")).GetDirectories()) { dir.Delete(recursive: true); } } return this; } /// <summary> /// Add a mock of the Microsoft.NETCore.App framework with the specified version /// </summary> /// <param name="version">Version to add</param> /// <param name="customizer">Customizer to customize the framework before it is built</param> /// <remarks> /// Product runtime binaries are not added. All the added mock framework will contain is hostpolicy, /// a mock version of coreclr, and a minimal Microsoft.NETCore.App.deps.json. /// </remarks> public DotNetBuilder AddMicrosoftNETCoreAppFrameworkMockCoreClr(string version, Action<NetCoreAppBuilder> customizer = null) { // ./shared/Microsoft.NETCore.App/<version> - create a mock of the root framework string netCoreAppPath = Path.Combine(_path, "shared", "Microsoft.NETCore.App", version); Directory.CreateDirectory(netCoreAppPath); string hostPolicyFileName = RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostpolicy"); string coreclrFileName = RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("coreclr"); string mockCoreclrFileName = RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("mockcoreclr"); string currentRid = _repoDirectories.TargetRID; NetCoreAppBuilder.ForNETCoreApp("Microsoft.NETCore.App", currentRid) .WithStandardRuntimeFallbacks() .WithProject("Microsoft.NETCore.App", version, p => p .WithNativeLibraryGroup(null, g => g // ./shared/Microsoft.NETCore.App/<version>/coreclr.dll - this is a mock, will not actually run CoreClr .WithAsset((new NetCoreAppBuilder.RuntimeFileBuilder($"runtimes/{currentRid}/native/{coreclrFileName}")) .CopyFromFile(Path.Combine(_repoDirectories.Artifacts, "corehost_test", mockCoreclrFileName)) .WithFileOnDiskPath(coreclrFileName)))) .WithPackage($"runtime.{currentRid}.Microsoft.NETCore.DotNetHostPolicy", version, p => p .WithNativeLibraryGroup(null, g => g // ./shared/Microsoft.NETCore.App/<version>/hostpolicy.dll - this is the real component and will load CoreClr library .WithAsset((new NetCoreAppBuilder.RuntimeFileBuilder($"runtimes/{currentRid}/native/{hostPolicyFileName}")) .CopyFromFile(Path.Combine(_repoDirectories.Artifacts, "corehost", hostPolicyFileName)) .WithFileOnDiskPath(hostPolicyFileName)))) .WithCustomizer(customizer) .Build(new TestApp(netCoreAppPath, "Microsoft.NETCore.App")); return this; } /// <summary> /// Add a mock framework with the specified framework name and version /// </summary> /// <param name="name">Framework name</param> /// <param name="version">Framework version</param> /// <param name="runtimeConfigCustomizer">Customization function for the runtime config</param> /// <remarks> /// The added mock framework will only contain a runtime.config.json file. /// </remarks> public DotNetBuilder AddFramework( string name, string version, Action<RuntimeConfig> runtimeConfigCustomizer) { // ./shared/<name>/<version> - create a mock of effectively empty non-root framework string path = Path.Combine(_path, "shared", name, version); Directory.CreateDirectory(path); // ./shared/<name>/<version>/<name>.runtimeconfig.json - runtime config which can be customized RuntimeConfig runtimeConfig = new RuntimeConfig(Path.Combine(path, name + ".runtimeconfig.json")); runtimeConfigCustomizer(runtimeConfig); runtimeConfig.Save(); return this; } public DotNetBuilder AddMockSDK( string version, string MNAVersion) { string path = Path.Combine(_path, "sdk", version); Directory.CreateDirectory(path); using var _ = File.Create(Path.Combine(path, "dotnet.dll")); RuntimeConfig dotnetRuntimeConfig = new RuntimeConfig(Path.Combine(path, "dotnet.runtimeconfig.json")); dotnetRuntimeConfig.WithFramework(new RuntimeConfig.Framework("Microsoft.NETCore.App", MNAVersion)); dotnetRuntimeConfig.Save(); return this; } public DotNetCli Build() { return new DotNetCli(_path); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.DotNet.Cli.Build; using System; using System.IO; namespace Microsoft.DotNet.CoreSetup.Test { /// <summary> /// Helper class for creating a mock version of a dotnet installation /// </summary> /// <remarks> /// This class uses a mock version of hostpolicy and does not use the product coreclr runtime, /// so the mock installation cannot be used to actually run apps. /// </remarks> public class DotNetBuilder { private readonly string _path; private readonly RepoDirectoriesProvider _repoDirectories; public DotNetBuilder(string basePath, string builtDotnet, string name) { _path = name == null ? basePath : Path.Combine(basePath, name); Directory.CreateDirectory(_path); _repoDirectories = new RepoDirectoriesProvider(builtDotnet: _path); // Prepare the dotnet installation mock // ./dotnet.exe - used as a convenient way to load and invoke hostfxr. May change in the future to use test-specific executable var builtDotNetCli = new DotNetCli(builtDotnet); File.Copy( builtDotNetCli.DotnetExecutablePath, Path.Combine(_path, RuntimeInformationExtensions.GetExeFileNameForCurrentPlatform("dotnet")), true); // ./host/fxr/<version>/hostfxr.dll - this is the component being tested SharedFramework.CopyDirectory( builtDotNetCli.GreatestVersionHostFxrPath, Path.Combine(_path, "host", "fxr", Path.GetFileName(builtDotNetCli.GreatestVersionHostFxrPath))); } /// <summary> /// Add a mock of the Microsoft.NETCore.App framework with the specified version /// </summary> /// <param name="version">Version to add</param> /// <remarks> /// Product runtime binaries are not added. All the added mock framework will contain is a mock version of host policy. /// </remarks> public DotNetBuilder AddMicrosoftNETCoreAppFrameworkMockHostPolicy(string version) { // ./shared/Microsoft.NETCore.App/<version> - create a mock of the root framework string netCoreAppPath = Path.Combine(_path, "shared", "Microsoft.NETCore.App", version); Directory.CreateDirectory(netCoreAppPath); // ./shared/Microsoft.NETCore.App/<version>/hostpolicy.dll - this is a mock, will not actually load CoreCLR string mockHostPolicyFileName = RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("mockhostpolicy"); File.Copy( Path.Combine(_repoDirectories.Artifacts, "corehost_test", mockHostPolicyFileName), Path.Combine(netCoreAppPath, RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostpolicy")), true); return this; } /// <summary> /// Use a mock version of HostFxr. /// </summary> /// <param name="version">Version to add</param> public DotNetBuilder AddMockHostFxr(Version version) { string hostfxrPath = Path.Combine(_path, "host", "fxr", version.ToString()); Directory.CreateDirectory(hostfxrPath); string mockHostFxrFileNameBase = version switch { { Major: 2, Minor: 2 } => "mockhostfxr_2_2", { Major: 5, Minor: 0 } => "mockhostfxr_5_0", _ => throw new InvalidOperationException($"Unsupported version {version} of mockhostfxr.") }; string mockHostFxrFileName = RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform(mockHostFxrFileNameBase); File.Copy( Path.Combine(_repoDirectories.Artifacts, "corehost_test", mockHostFxrFileName), Path.Combine(hostfxrPath, RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostfxr")), true); return this; } /// <summary> /// Removes the specified HostFxr version. If no version is set, it'll delete all versions found. /// </summary> /// <param name="version">Version to remove</param> public DotNetBuilder RemoveHostFxr(Version version = null) { if (version != null) { new DirectoryInfo(Path.Combine(_path, "host", "fxr", version.ToString())).Delete(recursive: true); } else { foreach (var dir in new DirectoryInfo(Path.Combine(_path, "host", "fxr")).GetDirectories()) { dir.Delete(recursive: true); } } return this; } /// <summary> /// Add a mock of the Microsoft.NETCore.App framework with the specified version /// </summary> /// <param name="version">Version to add</param> /// <param name="customizer">Customizer to customize the framework before it is built</param> /// <remarks> /// Product runtime binaries are not added. All the added mock framework will contain is hostpolicy, /// a mock version of coreclr, and a minimal Microsoft.NETCore.App.deps.json. /// </remarks> public DotNetBuilder AddMicrosoftNETCoreAppFrameworkMockCoreClr(string version, Action<NetCoreAppBuilder> customizer = null) { // ./shared/Microsoft.NETCore.App/<version> - create a mock of the root framework string netCoreAppPath = Path.Combine(_path, "shared", "Microsoft.NETCore.App", version); Directory.CreateDirectory(netCoreAppPath); string hostPolicyFileName = RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostpolicy"); string coreclrFileName = RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("coreclr"); string mockCoreclrFileName = RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("mockcoreclr"); string currentRid = _repoDirectories.TargetRID; NetCoreAppBuilder.ForNETCoreApp("Microsoft.NETCore.App", currentRid) .WithStandardRuntimeFallbacks() .WithProject("Microsoft.NETCore.App", version, p => p .WithNativeLibraryGroup(null, g => g // ./shared/Microsoft.NETCore.App/<version>/coreclr.dll - this is a mock, will not actually run CoreClr .WithAsset((new NetCoreAppBuilder.RuntimeFileBuilder($"runtimes/{currentRid}/native/{coreclrFileName}")) .CopyFromFile(Path.Combine(_repoDirectories.Artifacts, "corehost_test", mockCoreclrFileName)) .WithFileOnDiskPath(coreclrFileName)))) .WithPackage($"runtime.{currentRid}.Microsoft.NETCore.DotNetHostPolicy", version, p => p .WithNativeLibraryGroup(null, g => g // ./shared/Microsoft.NETCore.App/<version>/hostpolicy.dll - this is the real component and will load CoreClr library .WithAsset((new NetCoreAppBuilder.RuntimeFileBuilder($"runtimes/{currentRid}/native/{hostPolicyFileName}")) .CopyFromFile(Path.Combine(_repoDirectories.Artifacts, "corehost", hostPolicyFileName)) .WithFileOnDiskPath(hostPolicyFileName)))) .WithCustomizer(customizer) .Build(new TestApp(netCoreAppPath, "Microsoft.NETCore.App")); return this; } /// <summary> /// Add a mock framework with the specified framework name and version /// </summary> /// <param name="name">Framework name</param> /// <param name="version">Framework version</param> /// <param name="runtimeConfigCustomizer">Customization function for the runtime config</param> /// <remarks> /// The added mock framework will only contain a runtime.config.json file. /// </remarks> public DotNetBuilder AddFramework( string name, string version, Action<RuntimeConfig> runtimeConfigCustomizer, Action<string> frameworkCustomizer = null) { // ./shared/<name>/<version> - create a mock of effectively empty non-root framework string path = Path.Combine(_path, "shared", name, version); Directory.CreateDirectory(path); // ./shared/<name>/<version>/<name>.runtimeconfig.json - runtime config which can be customized RuntimeConfig runtimeConfig = new RuntimeConfig(Path.Combine(path, name + ".runtimeconfig.json")); runtimeConfigCustomizer(runtimeConfig); runtimeConfig.Save(); if (frameworkCustomizer is not null) frameworkCustomizer(path); return this; } public DotNetBuilder AddMockSDK( string sdkVersion, string runtimeVersion) { string path = Path.Combine(_path, "sdk", sdkVersion); Directory.CreateDirectory(path); using var _ = File.Create(Path.Combine(path, "dotnet.dll")); RuntimeConfig dotnetRuntimeConfig = new RuntimeConfig(Path.Combine(path, "dotnet.runtimeconfig.json")); dotnetRuntimeConfig.WithFramework(new RuntimeConfig.Framework("Microsoft.NETCore.App", runtimeVersion)); dotnetRuntimeConfig.Save(); return this; } public DotNetCli Build() { return new DotNetCli(_path); } } }
1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/installer/tests/TestUtils/RuntimeConfig.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Microsoft.DotNet.CoreSetup.Test { public class RuntimeConfig { public class Framework { public string Name { get; } public string Version { get; set; } public string RollForward { get; set; } public int? RollForwardOnNoCandidateFx { get; set; } public bool? ApplyPatches { get; set; } public Framework(string name, string version) { Name = name; Version = version; } public Framework WithRollForward(string value) { RollForward = value; return this; } public Framework WithRollForwardOnNoCandidateFx(int? value) { RollForwardOnNoCandidateFx = value; return this; } public Framework WithApplyPatches(bool? value) { ApplyPatches = value; return this; } internal JObject ToJson() { JObject frameworkReference = new JObject(); if (Name != null) { frameworkReference.Add("name", Name); } if (Version != null) { frameworkReference.Add("version", Version); } if (RollForward != null) { frameworkReference.Add( Constants.RollForwardSetting.RuntimeConfigPropertyName, RollForward); } if (RollForwardOnNoCandidateFx.HasValue) { frameworkReference.Add( Constants.RollForwardOnNoCandidateFxSetting.RuntimeConfigPropertyName, RollForwardOnNoCandidateFx.Value); } if (ApplyPatches.HasValue) { frameworkReference.Add( Constants.ApplyPatchesSetting.RuntimeConfigPropertyName, ApplyPatches.Value); } return frameworkReference; } internal static Framework FromJson(JObject jobject) { return new Framework((string)jobject["name"], (string)jobject["version"]) { RollForward = (string)jobject[Constants.RollForwardSetting.RuntimeConfigPropertyName], RollForwardOnNoCandidateFx = (int?)jobject[Constants.RollForwardOnNoCandidateFxSetting.RuntimeConfigPropertyName], ApplyPatches = (bool?)jobject[Constants.ApplyPatchesSetting.RuntimeConfigPropertyName] }; } } private string _rollForward; private int? _rollForwardOnNoCandidateFx; private bool? _applyPatches; private readonly string _path; private readonly List<Framework> _frameworks = new List<Framework>(); private readonly List<Framework> _includedFrameworks = new List<Framework>(); private readonly List<Tuple<string, string>> _properties = new List<Tuple<string, string>>(); /// <summary> /// Creates new runtime config - overwrites existing file on Save if any. /// </summary> public RuntimeConfig(string path) { _path = path; } /// <summary> /// Creates the object over existing file - reading its content. Save should recreate the file /// assuming we can store all the values in it in this class. /// </summary> public static RuntimeConfig FromFile(string path) { RuntimeConfig runtimeConfig = new RuntimeConfig(path); if (File.Exists(path)) { using (TextReader textReader = File.OpenText(path)) using (JsonTextReader reader = new JsonTextReader(textReader)) { JObject root = (JObject)JToken.ReadFrom(reader); JObject runtimeOptions = (JObject)root["runtimeOptions"]; var singleFramework = runtimeOptions["framework"] as JObject; if (singleFramework != null) { runtimeConfig.WithFramework(Framework.FromJson(singleFramework)); } var frameworks = runtimeOptions["frameworks"]; if (frameworks != null) { foreach (JObject framework in frameworks) { runtimeConfig.WithFramework(Framework.FromJson(framework)); } } var includedFrameworks = runtimeOptions["includedFrameworks"]; if (includedFrameworks != null) { foreach (JObject includedFramework in includedFrameworks) { runtimeConfig.WithFramework(Framework.FromJson(includedFramework)); } } var configProperties = runtimeOptions["configProperties"] as JObject; if (configProperties != null) { foreach (KeyValuePair<string, JToken> property in configProperties) { runtimeConfig.WithProperty(property.Key, (string)property.Value); } } runtimeConfig._rollForward = (string)runtimeOptions[Constants.RollForwardSetting.RuntimeConfigPropertyName]; runtimeConfig._rollForwardOnNoCandidateFx = (int?)runtimeOptions[Constants.RollForwardOnNoCandidateFxSetting.RuntimeConfigPropertyName]; runtimeConfig._applyPatches = (bool?)runtimeOptions[Constants.ApplyPatchesSetting.RuntimeConfigPropertyName]; } } return runtimeConfig; } public static RuntimeConfig Path(string path) { return new RuntimeConfig(path); } public Framework GetFramework(string name) { return _frameworks.FirstOrDefault(f => f.Name == name); } public RuntimeConfig WithFramework(Framework framework) { _frameworks.Add(framework); return this; } public RuntimeConfig WithFramework(string name, string version) { return WithFramework(new Framework(name, version)); } public RuntimeConfig RemoveFramework(string name) { Framework framework = GetFramework(name); if (framework != null) { _frameworks.Remove(framework); } return this; } public RuntimeConfig WithIncludedFramework(Framework framework) { _includedFrameworks.Add(framework); return this; } public RuntimeConfig WithIncludedFramework(string name, string version) { return WithIncludedFramework(new Framework(name, version)); } public RuntimeConfig WithRollForward(string value) { _rollForward = value; return this; } public RuntimeConfig WithRollForwardOnNoCandidateFx(int? value) { _rollForwardOnNoCandidateFx = value; return this; } public RuntimeConfig WithApplyPatches(bool? value) { _applyPatches = value; return this; } public RuntimeConfig WithProperty(string name, string value) { _properties.Add(new Tuple<string, string>(name, value)); return this; } public void Save() { JObject runtimeOptions = new JObject(); if (_frameworks.Any()) { runtimeOptions.Add( "frameworks", new JArray(_frameworks.Select(f => f.ToJson()).ToArray())); } if (_includedFrameworks.Any()) { runtimeOptions.Add( "includedFrameworks", new JArray(_includedFrameworks.Select(f => f.ToJson()).ToArray())); } if (_rollForward != null) { runtimeOptions.Add( Constants.RollForwardSetting.RuntimeConfigPropertyName, _rollForward); } if (_rollForwardOnNoCandidateFx.HasValue) { runtimeOptions.Add( Constants.RollForwardOnNoCandidateFxSetting.RuntimeConfigPropertyName, _rollForwardOnNoCandidateFx.Value); } if (_applyPatches.HasValue) { runtimeOptions.Add( Constants.ApplyPatchesSetting.RuntimeConfigPropertyName, _applyPatches.Value); } if (_properties.Count > 0) { JObject configProperties = new JObject(); foreach (var property in _properties) { var tokenValue = (property.Item2 == "false" || property.Item2 == "true") ? JToken.Parse(property.Item2) : property.Item2; configProperties.Add(property.Item1, tokenValue); } runtimeOptions.Add("configProperties", configProperties); } JObject json = new JObject() { { "runtimeOptions", runtimeOptions } }; File.WriteAllText(_path, json.ToString()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Microsoft.DotNet.CoreSetup.Test { public class RuntimeConfig { public class Framework { public string Name { get; } public string Version { get; set; } public string RollForward { get; set; } public int? RollForwardOnNoCandidateFx { get; set; } public bool? ApplyPatches { get; set; } public Framework(string name, string version) { Name = name; Version = version; } public Framework WithRollForward(string value) { RollForward = value; return this; } public Framework WithRollForwardOnNoCandidateFx(int? value) { RollForwardOnNoCandidateFx = value; return this; } public Framework WithApplyPatches(bool? value) { ApplyPatches = value; return this; } internal JObject ToJson() { JObject frameworkReference = new JObject(); if (Name != null) { frameworkReference.Add("name", Name); } if (Version != null) { frameworkReference.Add("version", Version); } if (RollForward != null) { frameworkReference.Add( Constants.RollForwardSetting.RuntimeConfigPropertyName, RollForward); } if (RollForwardOnNoCandidateFx.HasValue) { frameworkReference.Add( Constants.RollForwardOnNoCandidateFxSetting.RuntimeConfigPropertyName, RollForwardOnNoCandidateFx.Value); } if (ApplyPatches.HasValue) { frameworkReference.Add( Constants.ApplyPatchesSetting.RuntimeConfigPropertyName, ApplyPatches.Value); } return frameworkReference; } internal static Framework FromJson(JObject jobject) { return new Framework((string)jobject["name"], (string)jobject["version"]) { RollForward = (string)jobject[Constants.RollForwardSetting.RuntimeConfigPropertyName], RollForwardOnNoCandidateFx = (int?)jobject[Constants.RollForwardOnNoCandidateFxSetting.RuntimeConfigPropertyName], ApplyPatches = (bool?)jobject[Constants.ApplyPatchesSetting.RuntimeConfigPropertyName] }; } } private string _rollForward; private int? _rollForwardOnNoCandidateFx; private bool? _applyPatches; private string _tfm; private readonly string _path; private readonly List<Framework> _frameworks = new List<Framework>(); private readonly List<Framework> _includedFrameworks = new List<Framework>(); private readonly List<Tuple<string, string>> _properties = new List<Tuple<string, string>>(); /// <summary> /// Creates new runtime config - overwrites existing file on Save if any. /// </summary> public RuntimeConfig(string path) { _path = path; } /// <summary> /// Creates the object over existing file - reading its content. Save should recreate the file /// assuming we can store all the values in it in this class. /// </summary> public static RuntimeConfig FromFile(string path) { RuntimeConfig runtimeConfig = new RuntimeConfig(path); if (File.Exists(path)) { using (TextReader textReader = File.OpenText(path)) using (JsonTextReader reader = new JsonTextReader(textReader)) { JObject root = (JObject)JToken.ReadFrom(reader); JObject runtimeOptions = (JObject)root["runtimeOptions"]; var singleFramework = runtimeOptions["framework"] as JObject; if (singleFramework != null) { runtimeConfig.WithFramework(Framework.FromJson(singleFramework)); } var frameworks = runtimeOptions["frameworks"]; if (frameworks != null) { foreach (JObject framework in frameworks) { runtimeConfig.WithFramework(Framework.FromJson(framework)); } } var includedFrameworks = runtimeOptions["includedFrameworks"]; if (includedFrameworks != null) { foreach (JObject includedFramework in includedFrameworks) { runtimeConfig.WithFramework(Framework.FromJson(includedFramework)); } } var configProperties = runtimeOptions["configProperties"] as JObject; if (configProperties != null) { foreach (KeyValuePair<string, JToken> property in configProperties) { runtimeConfig.WithProperty(property.Key, (string)property.Value); } } runtimeConfig._rollForward = (string)runtimeOptions[Constants.RollForwardSetting.RuntimeConfigPropertyName]; runtimeConfig._rollForwardOnNoCandidateFx = (int?)runtimeOptions[Constants.RollForwardOnNoCandidateFxSetting.RuntimeConfigPropertyName]; runtimeConfig._applyPatches = (bool?)runtimeOptions[Constants.ApplyPatchesSetting.RuntimeConfigPropertyName]; } } return runtimeConfig; } public static RuntimeConfig Path(string path) { return new RuntimeConfig(path); } public Framework GetFramework(string name) { return _frameworks.FirstOrDefault(f => f.Name == name); } public RuntimeConfig WithFramework(Framework framework) { _frameworks.Add(framework); return this; } public RuntimeConfig WithFramework(string name, string version) { return WithFramework(new Framework(name, version)); } public RuntimeConfig RemoveFramework(string name) { Framework framework = GetFramework(name); if (framework != null) { _frameworks.Remove(framework); } return this; } public RuntimeConfig WithIncludedFramework(Framework framework) { _includedFrameworks.Add(framework); return this; } public RuntimeConfig WithIncludedFramework(string name, string version) { return WithIncludedFramework(new Framework(name, version)); } public RuntimeConfig WithRollForward(string value) { _rollForward = value; return this; } public RuntimeConfig WithRollForwardOnNoCandidateFx(int? value) { _rollForwardOnNoCandidateFx = value; return this; } public RuntimeConfig WithApplyPatches(bool? value) { _applyPatches = value; return this; } public RuntimeConfig WithTfm(string tfm) { _tfm = tfm; return this; } public RuntimeConfig WithProperty(string name, string value) { _properties.Add(new Tuple<string, string>(name, value)); return this; } public void Save() { JObject runtimeOptions = new JObject(); if (_frameworks.Any()) { runtimeOptions.Add( "frameworks", new JArray(_frameworks.Select(f => f.ToJson()).ToArray())); } if (_includedFrameworks.Any()) { runtimeOptions.Add( "includedFrameworks", new JArray(_includedFrameworks.Select(f => f.ToJson()).ToArray())); } if (_rollForward != null) { runtimeOptions.Add( Constants.RollForwardSetting.RuntimeConfigPropertyName, _rollForward); } if (_rollForwardOnNoCandidateFx.HasValue) { runtimeOptions.Add( Constants.RollForwardOnNoCandidateFxSetting.RuntimeConfigPropertyName, _rollForwardOnNoCandidateFx.Value); } if (_applyPatches.HasValue) { runtimeOptions.Add( Constants.ApplyPatchesSetting.RuntimeConfigPropertyName, _applyPatches.Value); } if (_tfm is not null) { runtimeOptions.Add( Constants.Tfm.RuntimeConfigPropertyName, _tfm); } if (_properties.Count > 0) { JObject configProperties = new JObject(); foreach (var property in _properties) { var tokenValue = (property.Item2 == "false" || property.Item2 == "true") ? JToken.Parse(property.Item2) : property.Item2; configProperties.Add(property.Item1, tokenValue); } runtimeOptions.Add("configProperties", configProperties); } JObject json = new JObject() { { "runtimeOptions", runtimeOptions } }; File.WriteAllText(_path, json.ToString()); } } }
1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/native/corehost/test/mockhostpolicy/mockhostpolicy.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <iostream> #include "pal.h" #include "trace.h" #include "error_codes.h" #include "host_interface.h" #include <hostpolicy.h> std::vector<char> tostr(const pal::char_t* value) { std::vector<char> vect; pal::pal_utf8string(pal::string_t(value), &vect); return vect; } void print_strarr(const char* prefix, const strarr_t& arr) { if (arr.len == 0) { std::cout << prefix << "<empty>" << std::endl; return; } for (size_t i = 0; i < arr.len; i++) { std::cout << prefix << tostr(arr.arr[i]).data() << std::endl; } } SHARED_API int HOSTPOLICY_CALLTYPE corehost_load(host_interface_t* init) { trace::setup(); trace::verbose(_X("--- Invoked hostpolicy mock - corehost_load")); std::cout << "--- Invoked hostpolicy mock - corehost_load" << std::endl; std::cout << "mock version: " << init->version_hi << " " << init->version_lo << std::endl; if (init->config_keys.len == 0) { std::cout << "mock config: <empty>" << std::endl; } else { for (size_t i = 0; i < init->config_keys.len; i++) { std::cout << "mock config: " << tostr(init->config_keys.arr[i]).data() << "=" << tostr(init->config_values.arr[i]).data() << std::endl; } } std::cout << "mock fx_dir: " << tostr(init->fx_dir).data() << std::endl; std::cout << "mock fx_name: " << tostr(init->fx_name).data() << std::endl; std::cout << "mock deps_file: " << tostr(init->deps_file).data() << std::endl; std::cout << "mock is_framework_dependent: " << init->is_framework_dependent << std::endl; print_strarr("mock probe_paths: ", init->probe_paths); std::cout << "mock host_mode: " << init->host_mode << std::endl; std::cout << "mock tfm: " << tostr(init->tfm).data() << std::endl; std::cout << "mock additional_deps_serialized: " << tostr(init->additional_deps_serialized).data() << std::endl; std::cout << "mock fx_ver: " << tostr(init->fx_ver).data() << std::endl; print_strarr("mock fx_names: ", init->fx_names); print_strarr("mock fx_dirs: ", init->fx_dirs); print_strarr("mock fx_requested_versions: ", init->fx_requested_versions); print_strarr("mock fx_found_versions: ", init->fx_found_versions); std::cout << "mock host_command:" << tostr(init->host_command).data() << std::endl; std::cout << "mock host_info_host_path:" << tostr(init->host_info_host_path).data() << std::endl; std::cout << "mock host_info_dotnet_root:" << tostr(init->host_info_dotnet_root).data() << std::endl; std::cout << "mock host_info_app_path:" << tostr(init->host_info_app_path).data() << std::endl; std::cout << "mock single_file_bundle_header_offset:" << std::hex << init->single_file_bundle_header_offset << std::endl; if (init->fx_names.len == 0) { std::cout << "mock frameworks: <empty>" << std::endl; } else { for (size_t i = 0; i < init->fx_names.len; i++) { std::cout << "mock frameworks: " << tostr(init->fx_names.arr[i]).data() << " " << tostr(init->fx_found_versions.arr[i]).data() << " [requested: " << tostr(init->fx_requested_versions.arr[i]).data() << "] [path: " << tostr(init->fx_dirs.arr[i]).data() << "]" << std::endl; } } return StatusCode::Success; } SHARED_API int HOSTPOLICY_CALLTYPE corehost_main(const int argc, const pal::char_t* argv[]) { trace::verbose(_X("--- Invoked hostpolicy mock - corehost_main")); return StatusCode::Success; } SHARED_API int HOSTPOLICY_CALLTYPE corehost_unload() { trace::verbose(_X("--- Invoked hostpolicy mock - corehost_unload")); return StatusCode::Success; } SHARED_API corehost_error_writer_fn HOSTPOLICY_CALLTYPE corehost_set_error_writer(corehost_error_writer_fn error_writer) { trace::verbose(_X("--- Invoked hostpolicy mock - corehost_set_error_writer")); return nullptr; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <iostream> #include "pal.h" #include "trace.h" #include "error_codes.h" #include "host_interface.h" #include <hostpolicy.h> std::vector<char> tostr(const pal::char_t* value) { std::vector<char> vect; pal::pal_utf8string(pal::string_t(value), &vect); return vect; } void print_strarr(const char* prefix, const strarr_t& arr) { if (arr.len == 0) { std::cout << prefix << "<empty>" << std::endl; return; } for (size_t i = 0; i < arr.len; i++) { std::cout << prefix << tostr(arr.arr[i]).data() << std::endl; } } SHARED_API int HOSTPOLICY_CALLTYPE corehost_load(host_interface_t* init) { trace::setup(); trace::verbose(_X("--- Invoked hostpolicy mock - corehost_load")); std::cout << "--- Invoked hostpolicy mock - corehost_load" << std::endl; std::cout << "mock version: " << init->version_hi << " " << init->version_lo << std::endl; if (init->config_keys.len == 0) { std::cout << "mock config: <empty>" << std::endl; } else { for (size_t i = 0; i < init->config_keys.len; i++) { std::cout << "mock config: " << tostr(init->config_keys.arr[i]).data() << "=" << tostr(init->config_values.arr[i]).data() << std::endl; } } std::cout << "mock fx_dir: " << tostr(init->fx_dir).data() << std::endl; std::cout << "mock fx_name: " << tostr(init->fx_name).data() << std::endl; std::cout << "mock deps_file: " << tostr(init->deps_file).data() << std::endl; std::cout << "mock is_framework_dependent: " << init->is_framework_dependent << std::endl; print_strarr("mock probe_paths: ", init->probe_paths); std::cout << "mock host_mode: " << init->host_mode << std::endl; std::cout << "mock tfm: " << tostr(init->tfm).data() << std::endl; std::cout << "mock additional_deps_serialized: " << tostr(init->additional_deps_serialized).data() << std::endl; std::cout << "mock fx_ver: " << tostr(init->fx_ver).data() << std::endl; print_strarr("mock fx_names: ", init->fx_names); print_strarr("mock fx_dirs: ", init->fx_dirs); print_strarr("mock fx_requested_versions: ", init->fx_requested_versions); print_strarr("mock fx_found_versions: ", init->fx_found_versions); std::cout << "mock host_command:" << tostr(init->host_command).data() << std::endl; std::cout << "mock host_info_host_path:" << tostr(init->host_info_host_path).data() << std::endl; std::cout << "mock host_info_dotnet_root:" << tostr(init->host_info_dotnet_root).data() << std::endl; std::cout << "mock host_info_app_path:" << tostr(init->host_info_app_path).data() << std::endl; std::cout << "mock single_file_bundle_header_offset:" << std::hex << init->single_file_bundle_header_offset << std::endl; if (init->fx_names.len == 0) { std::cout << "mock frameworks: <empty>" << std::endl; } else { for (size_t i = 0; i < init->fx_names.len; i++) { std::cout << "mock frameworks: " << tostr(init->fx_names.arr[i]).data() << " " << tostr(init->fx_found_versions.arr[i]).data() << " [path: " << tostr(init->fx_dirs.arr[i]).data() << "] [requested: " << tostr(init->fx_requested_versions.arr[i]).data() << "]" << std::endl; } } return StatusCode::Success; } SHARED_API int HOSTPOLICY_CALLTYPE corehost_main(const int argc, const pal::char_t* argv[]) { trace::verbose(_X("--- Invoked hostpolicy mock - corehost_main")); return StatusCode::Success; } SHARED_API int HOSTPOLICY_CALLTYPE corehost_unload() { trace::verbose(_X("--- Invoked hostpolicy mock - corehost_unload")); return StatusCode::Success; } SHARED_API corehost_error_writer_fn HOSTPOLICY_CALLTYPE corehost_set_error_writer(corehost_error_writer_fn error_writer) { trace::verbose(_X("--- Invoked hostpolicy mock - corehost_set_error_writer")); return nullptr; }
1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/tests/JIT/HardwareIntrinsics/General/Vector256/Dot.Int32.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 DotInt32() { var test = new VectorBinaryOpTest__DotInt32(); // 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__DotInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, 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>(inArray2Ptr), ref Unsafe.As<Int32, 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 Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int32> _fld1; public Vector256<Int32> _fld2; 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<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__DotInt32 testClass) { var result = Vector256.Dot(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__DotInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public VectorBinaryOpTest__DotInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Dot( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.Dot), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Dot), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int32)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (Int32)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Dot( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Vector256.Dot(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__DotInt32(); var result = Vector256.Dot(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.Dot(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.Dot(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Int32> op1, Vector256<Int32> op2, Int32 result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, Int32 result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32 result, [CallerMemberName] string method = "") { bool succeeded = true; Int32 actualResult = default; Int32 intermResult = default; for (var i = 0; i < Op1ElementCount; i++) { if ((i % Vector128<Int32>.Count) == 0) { actualResult += intermResult; intermResult = default; } intermResult += (Int32)(left[i] * right[i]); } actualResult += intermResult; if (actualResult != result) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Dot)}<Int32>(Vector256<Int32>, Vector256<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: {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 DotInt32() { var test = new VectorBinaryOpTest__DotInt32(); // 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__DotInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, 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>(inArray2Ptr), ref Unsafe.As<Int32, 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 Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int32> _fld1; public Vector256<Int32> _fld2; 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<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__DotInt32 testClass) { var result = Vector256.Dot(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__DotInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public VectorBinaryOpTest__DotInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Dot( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.Dot), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Dot), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int32)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (Int32)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Dot( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Vector256.Dot(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__DotInt32(); var result = Vector256.Dot(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.Dot(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.Dot(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Int32> op1, Vector256<Int32> op2, Int32 result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, Int32 result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32 result, [CallerMemberName] string method = "") { bool succeeded = true; Int32 actualResult = default; Int32 intermResult = default; for (var i = 0; i < Op1ElementCount; i++) { if ((i % Vector128<Int32>.Count) == 0) { actualResult += intermResult; intermResult = default; } intermResult += (Int32)(left[i] * right[i]); } actualResult += intermResult; if (actualResult != result) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Dot)}<Int32>(Vector256<Int32>, Vector256<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: {result}"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/tests/Interop/PInvoke/Miscellaneous/HandleRef/HandleRefNative.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <stdio.h> #include <xplatform.h> #include <platformdefines.h> const int intManaged = 1000; const int intNative = 2000; const int intReturn = 3000; const int intErrReturn = 4000; const int expectedStackGuard = 5000; extern "C" DLL_EXPORT int STDMETHODCALLTYPE MarshalPointer_In(/*[in]*/int *pintValue, int stackGuard) { if (*pintValue != intManaged) { printf("Error in Function MarshalPointer_In(Native Client)\n"); printf("Expected:%u\n", intManaged); printf("Actual:%u\n",*pintValue); // Return the error value instead if verification failed return intErrReturn; } if (stackGuard != expectedStackGuard) { printf("Stack error in Function MarshalPointer_In(Native Client)\n"); return intErrReturn; } return intReturn; } extern "C" DLL_EXPORT int STDMETHODCALLTYPE MarshalPointer_InOut(/*[in,out]*/int *pintValue, int stackGuard) { if(*pintValue != intManaged) { printf("Error in Function MarshalPointer_InOut(Native Client)\n"); printf("Expected:%u\n", intManaged); printf("Actual:%u\n",*pintValue); // Return the error value instead if verification failed return intErrReturn; } if (stackGuard != expectedStackGuard) { printf("Stack error in Function MarshalPointer_In(Native Client)\n"); return intErrReturn; } // In-Place Change *pintValue = intNative; return intReturn; } extern "C" DLL_EXPORT int STDMETHODCALLTYPE MarshalPointer_Out(/*[out]*/ int *pintValue, int stackGuard) { *pintValue = intNative; if (stackGuard != expectedStackGuard) { printf("Stack error in Function MarshalPointer_In(Native Client)\n"); return intErrReturn; } return intReturn; } typedef void (*GCCallback)(void); extern "C" DLL_EXPORT int STDMETHODCALLTYPE TestNoGC(int *pintValue, GCCallback gcCallback) { int origValue = *pintValue; gcCallback(); int afterGCValue = *pintValue; if (origValue != afterGCValue) { printf("Error in Function TestNoGC(Native Client)\n"); printf("Expected:%u\n", origValue); printf("Actual:%u\n", afterGCValue); return intErrReturn; } return intReturn; } extern "C" DLL_EXPORT void* STDMETHODCALLTYPE InvalidMarshalPointer_Return() { return nullptr; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <stdio.h> #include <xplatform.h> #include <platformdefines.h> const int intManaged = 1000; const int intNative = 2000; const int intReturn = 3000; const int intErrReturn = 4000; const int expectedStackGuard = 5000; extern "C" DLL_EXPORT int STDMETHODCALLTYPE MarshalPointer_In(/*[in]*/int *pintValue, int stackGuard) { if (*pintValue != intManaged) { printf("Error in Function MarshalPointer_In(Native Client)\n"); printf("Expected:%u\n", intManaged); printf("Actual:%u\n",*pintValue); // Return the error value instead if verification failed return intErrReturn; } if (stackGuard != expectedStackGuard) { printf("Stack error in Function MarshalPointer_In(Native Client)\n"); return intErrReturn; } return intReturn; } extern "C" DLL_EXPORT int STDMETHODCALLTYPE MarshalPointer_InOut(/*[in,out]*/int *pintValue, int stackGuard) { if(*pintValue != intManaged) { printf("Error in Function MarshalPointer_InOut(Native Client)\n"); printf("Expected:%u\n", intManaged); printf("Actual:%u\n",*pintValue); // Return the error value instead if verification failed return intErrReturn; } if (stackGuard != expectedStackGuard) { printf("Stack error in Function MarshalPointer_In(Native Client)\n"); return intErrReturn; } // In-Place Change *pintValue = intNative; return intReturn; } extern "C" DLL_EXPORT int STDMETHODCALLTYPE MarshalPointer_Out(/*[out]*/ int *pintValue, int stackGuard) { *pintValue = intNative; if (stackGuard != expectedStackGuard) { printf("Stack error in Function MarshalPointer_In(Native Client)\n"); return intErrReturn; } return intReturn; } typedef void (*GCCallback)(void); extern "C" DLL_EXPORT int STDMETHODCALLTYPE TestNoGC(int *pintValue, GCCallback gcCallback) { int origValue = *pintValue; gcCallback(); int afterGCValue = *pintValue; if (origValue != afterGCValue) { printf("Error in Function TestNoGC(Native Client)\n"); printf("Expected:%u\n", origValue); printf("Actual:%u\n", afterGCValue); return intErrReturn; } return intReturn; } extern "C" DLL_EXPORT void* STDMETHODCALLTYPE InvalidMarshalPointer_Return() { return nullptr; }
-1
dotnet/runtime
66,332
Refactor and improve MLL tests
* Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
vitek-karas
2022-03-08T13:26:28Z
2022-03-11T08:34:45Z
5ce2b9f860f7a84c3059650bb67817d59d8f4953
f82fe1d83f1a0e22025e186fdc6f4d86de0a83a1
Refactor and improve MLL tests. * Remove duplicated code - I know that tests should be descriptive, but repeating 100 times that we want to capture output doesn't feel necessary. * For some of them move more stuff into the shared test state - this improves perf as we avoid repeating the setup (copying files around) for each test case, we do it once for the entire class I also changed some of the tests to "Theory" as it's easier to read that way. * `SDKLookup.cs` - moved most of the state in to the shared state to speed up the tests. * Adding more cases into the "theory" tests * Most notably for the framework resolution I added variations on the TFM (which will be needed when we implement disable of MLL) * Adding new tests mostly around "list runtimes" (various forms), "list sdks" (various forms) and errors (which also list runtimes or sdks) * Ported all of the `MultiLevelLookupFramework` tests over to the `FrameworkResolution` and `DependencyResolutions` suites which have a more robust test infra and can run the same tests much faster. Along the way I added lot more variations on top of the existing tests: * `PerAssemblyVersionResolutionMultipleFrameworks.cs` - this is actually not an MLL test, but I moved it to the new infra to make it much faster * `MultipleHives.cs` - MLL framework resolution tests For SDK resolution I kept the `MultiLevelSDKLookup.cs` just removed code duplication and added new variants. For the core reviewers: I promise I didn't remove any single test case in spirit with these exceptions: * We had tests which validated that framework resolution is not affected by frameworks in current directory and also by frameworks in the user's directory. I left some basic test for the current directory check, but I completely removed the user's directory variant as the product simply doesn't have any code around that anymore.
./src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.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.Linq; namespace Microsoft.Extensions.DependencyModel { public class RuntimeFallbacks { public string Runtime { get; set; } public IReadOnlyList<string?> Fallbacks { get; set; } public RuntimeFallbacks(string runtime, params string?[] fallbacks) : this(runtime, (IEnumerable<string?>)fallbacks) { } public RuntimeFallbacks(string runtime, IEnumerable<string?> fallbacks) { if (string.IsNullOrEmpty(runtime)) { throw new ArgumentException(null, nameof(runtime)); } if (fallbacks == null) { throw new ArgumentNullException(nameof(fallbacks)); } Runtime = runtime; Fallbacks = fallbacks.ToArray(); } } }
// 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.Linq; namespace Microsoft.Extensions.DependencyModel { public class RuntimeFallbacks { public string Runtime { get; set; } public IReadOnlyList<string?> Fallbacks { get; set; } public RuntimeFallbacks(string runtime, params string?[] fallbacks) : this(runtime, (IEnumerable<string?>)fallbacks) { } public RuntimeFallbacks(string runtime, IEnumerable<string?> fallbacks) { if (string.IsNullOrEmpty(runtime)) { throw new ArgumentException(null, nameof(runtime)); } if (fallbacks == null) { throw new ArgumentNullException(nameof(fallbacks)); } Runtime = runtime; Fallbacks = fallbacks.ToArray(); } } }
-1