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,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/HardwareIntrinsics/General/Vector128/EqualsAny.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 EqualsAnyInt32() { var test = new VectorBooleanBinaryOpTest__EqualsAnyInt32(); // 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 VectorBooleanBinaryOpTest__EqualsAnyInt32 { 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 Vector128<Int32> _fld1; public Vector128<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<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__EqualsAnyInt32 testClass) { var result = Vector128.EqualsAny(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__EqualsAnyInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public VectorBooleanBinaryOpTest__EqualsAnyInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<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 = Vector128.EqualsAny( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.EqualsAny), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.EqualsAny), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int32)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.EqualsAny( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Vector128.EqualsAny(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__EqualsAnyInt32(); var result = Vector128.EqualsAny(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.EqualsAny(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.EqualsAny(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(Vector128<Int32> op1, Vector128<Int32> op2, bool 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, bool 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<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int32[] left, Int32[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = false; for (var i = 0; i < Op1ElementCount; i++) { expectedResult |= (left[i] == right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.EqualsAny)}<Int32>(Vector128<Int32>, Vector128<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 EqualsAnyInt32() { var test = new VectorBooleanBinaryOpTest__EqualsAnyInt32(); // 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 VectorBooleanBinaryOpTest__EqualsAnyInt32 { 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 Vector128<Int32> _fld1; public Vector128<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<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__EqualsAnyInt32 testClass) { var result = Vector128.EqualsAny(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__EqualsAnyInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public VectorBooleanBinaryOpTest__EqualsAnyInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<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 = Vector128.EqualsAny( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.EqualsAny), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.EqualsAny), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int32)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.EqualsAny( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Vector128.EqualsAny(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__EqualsAnyInt32(); var result = Vector128.EqualsAny(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.EqualsAny(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.EqualsAny(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(Vector128<Int32> op1, Vector128<Int32> op2, bool 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, bool 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<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int32[] left, Int32[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = false; for (var i = 0; i < Op1ElementCount; i++) { expectedResult |= (left[i] == right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.EqualsAny)}<Int32>(Vector128<Int32>, Vector128<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,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/coreclr/tools/Common/Compiler/DependencyAnalysis/AssemblyStubNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Internal.TypeSystem; using Internal.Text; namespace ILCompiler.DependencyAnalysis { public abstract class AssemblyStubNode : ObjectNode, ISymbolDefinitionNode { public AssemblyStubNode() { } /// <summary> /// Gets a value indicating whether the stub's address is visible from managed code /// and could be a target of a managed calli. /// </summary> protected virtual bool IsVisibleFromManagedCode => true; public override ObjectNodeSection Section => ObjectNodeSection.TextSection; public override bool StaticDependenciesAreComputed => true; public abstract void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb); public int Offset => 0; public override bool IsShareable => false; public override ObjectData GetData(NodeFactory factory, bool relocsOnly) { // If the address is expected to be visible from managed code, we need to align // at the managed code boundaries to prevent the stub from being confused with // a fat fuction pointer. Otherwise we can align tighter. int alignment = IsVisibleFromManagedCode ? factory.Target.MinimumFunctionAlignment : factory.Target.MinimumCodeAlignment; switch (factory.Target.Architecture) { case TargetArchitecture.X64: X64.X64Emitter x64Emitter = new X64.X64Emitter(factory, relocsOnly); EmitCode(factory, ref x64Emitter, relocsOnly); x64Emitter.Builder.RequireInitialAlignment(alignment); x64Emitter.Builder.AddSymbol(this); return x64Emitter.Builder.ToObjectData(); case TargetArchitecture.X86: X86.X86Emitter x86Emitter = new X86.X86Emitter(factory, relocsOnly); EmitCode(factory, ref x86Emitter, relocsOnly); x86Emitter.Builder.RequireInitialAlignment(alignment); x86Emitter.Builder.AddSymbol(this); return x86Emitter.Builder.ToObjectData(); case TargetArchitecture.ARM: ARM.ARMEmitter armEmitter = new ARM.ARMEmitter(factory, relocsOnly); EmitCode(factory, ref armEmitter, relocsOnly); armEmitter.Builder.RequireInitialAlignment(alignment); armEmitter.Builder.AddSymbol(this); return armEmitter.Builder.ToObjectData(); case TargetArchitecture.ARM64: ARM64.ARM64Emitter arm64Emitter = new ARM64.ARM64Emitter(factory, relocsOnly); EmitCode(factory, ref arm64Emitter, relocsOnly); arm64Emitter.Builder.RequireInitialAlignment(alignment); arm64Emitter.Builder.AddSymbol(this); return arm64Emitter.Builder.ToObjectData(); default: throw new NotImplementedException(); } } protected abstract void EmitCode(NodeFactory factory, ref X64.X64Emitter instructionEncoder, bool relocsOnly); protected abstract void EmitCode(NodeFactory factory, ref X86.X86Emitter instructionEncoder, bool relocsOnly); protected abstract void EmitCode(NodeFactory factory, ref ARM.ARMEmitter instructionEncoder, bool relocsOnly); protected abstract void EmitCode(NodeFactory factory, ref ARM64.ARM64Emitter instructionEncoder, bool relocsOnly); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Internal.TypeSystem; using Internal.Text; namespace ILCompiler.DependencyAnalysis { public abstract class AssemblyStubNode : ObjectNode, ISymbolDefinitionNode { public AssemblyStubNode() { } /// <summary> /// Gets a value indicating whether the stub's address is visible from managed code /// and could be a target of a managed calli. /// </summary> protected virtual bool IsVisibleFromManagedCode => true; public override ObjectNodeSection Section => ObjectNodeSection.TextSection; public override bool StaticDependenciesAreComputed => true; public abstract void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb); public int Offset => 0; public override bool IsShareable => false; public override ObjectData GetData(NodeFactory factory, bool relocsOnly) { // If the address is expected to be visible from managed code, we need to align // at the managed code boundaries to prevent the stub from being confused with // a fat fuction pointer. Otherwise we can align tighter. int alignment = IsVisibleFromManagedCode ? factory.Target.MinimumFunctionAlignment : factory.Target.MinimumCodeAlignment; switch (factory.Target.Architecture) { case TargetArchitecture.X64: X64.X64Emitter x64Emitter = new X64.X64Emitter(factory, relocsOnly); EmitCode(factory, ref x64Emitter, relocsOnly); x64Emitter.Builder.RequireInitialAlignment(alignment); x64Emitter.Builder.AddSymbol(this); return x64Emitter.Builder.ToObjectData(); case TargetArchitecture.X86: X86.X86Emitter x86Emitter = new X86.X86Emitter(factory, relocsOnly); EmitCode(factory, ref x86Emitter, relocsOnly); x86Emitter.Builder.RequireInitialAlignment(alignment); x86Emitter.Builder.AddSymbol(this); return x86Emitter.Builder.ToObjectData(); case TargetArchitecture.ARM: ARM.ARMEmitter armEmitter = new ARM.ARMEmitter(factory, relocsOnly); EmitCode(factory, ref armEmitter, relocsOnly); armEmitter.Builder.RequireInitialAlignment(alignment); armEmitter.Builder.AddSymbol(this); return armEmitter.Builder.ToObjectData(); case TargetArchitecture.ARM64: ARM64.ARM64Emitter arm64Emitter = new ARM64.ARM64Emitter(factory, relocsOnly); EmitCode(factory, ref arm64Emitter, relocsOnly); arm64Emitter.Builder.RequireInitialAlignment(alignment); arm64Emitter.Builder.AddSymbol(this); return arm64Emitter.Builder.ToObjectData(); default: throw new NotImplementedException(); } } protected abstract void EmitCode(NodeFactory factory, ref X64.X64Emitter instructionEncoder, bool relocsOnly); protected abstract void EmitCode(NodeFactory factory, ref X86.X86Emitter instructionEncoder, bool relocsOnly); protected abstract void EmitCode(NodeFactory factory, ref ARM.ARMEmitter instructionEncoder, bool relocsOnly); protected abstract void EmitCode(NodeFactory factory, ref ARM64.ARM64Emitter instructionEncoder, bool relocsOnly); } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Threading.Channels/ref/System.Threading.Channels.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.Threading.Channels { public enum BoundedChannelFullMode { Wait = 0, DropNewest = 1, DropOldest = 2, DropWrite = 3, } public sealed partial class BoundedChannelOptions : System.Threading.Channels.ChannelOptions { public BoundedChannelOptions(int capacity) { } public int Capacity { get { throw null; } set { } } public System.Threading.Channels.BoundedChannelFullMode FullMode { get { throw null; } set { } } } public static partial class Channel { public static System.Threading.Channels.Channel<T> CreateBounded<T>(int capacity) { throw null; } public static System.Threading.Channels.Channel<T> CreateBounded<T>(System.Threading.Channels.BoundedChannelOptions options) { throw null; } public static System.Threading.Channels.Channel<T> CreateBounded<T>(BoundedChannelOptions options, Action<T>? itemDropped) { throw null; } public static System.Threading.Channels.Channel<T> CreateUnbounded<T>() { throw null; } public static System.Threading.Channels.Channel<T> CreateUnbounded<T>(System.Threading.Channels.UnboundedChannelOptions options) { throw null; } } public partial class ChannelClosedException : System.InvalidOperationException { public ChannelClosedException() { } public ChannelClosedException(System.Exception? innerException) { } public ChannelClosedException(string? message) { } public ChannelClosedException(string? message, System.Exception? innerException) { } } public abstract partial class ChannelOptions { protected ChannelOptions() { } public bool AllowSynchronousContinuations { get { throw null; } set { } } public bool SingleReader { get { throw null; } set { } } public bool SingleWriter { get { throw null; } set { } } } public abstract partial class ChannelReader<T> { protected ChannelReader() { } public virtual bool CanCount { get { throw null; } } public virtual bool CanPeek { get { throw null; } } public virtual System.Threading.Tasks.Task Completion { get { throw null; } } public virtual int Count { get { throw null; } } public virtual System.Threading.Tasks.ValueTask<T> ReadAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual bool TryPeek([System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T item) { throw null; } public abstract bool TryRead([System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T item); public abstract System.Threading.Tasks.ValueTask<bool> WaitToReadAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } public abstract partial class ChannelWriter<T> { protected ChannelWriter() { } public void Complete(System.Exception? error = null) { } public virtual bool TryComplete(System.Exception? error = null) { throw null; } public abstract bool TryWrite(T item); public abstract System.Threading.Tasks.ValueTask<bool> WaitToWriteAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); public virtual System.Threading.Tasks.ValueTask WriteAsync(T item, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public abstract partial class Channel<T> : System.Threading.Channels.Channel<T, T> { protected Channel() { } } public abstract partial class Channel<TWrite, TRead> { protected Channel() { } public System.Threading.Channels.ChannelReader<TRead> Reader { get { throw null; } protected set { } } public System.Threading.Channels.ChannelWriter<TWrite> Writer { get { throw null; } protected set { } } public static implicit operator System.Threading.Channels.ChannelReader<TRead> (System.Threading.Channels.Channel<TWrite, TRead> channel) { throw null; } public static implicit operator System.Threading.Channels.ChannelWriter<TWrite> (System.Threading.Channels.Channel<TWrite, TRead> channel) { throw null; } } public sealed partial class UnboundedChannelOptions : System.Threading.Channels.ChannelOptions { public UnboundedChannelOptions() { } } }
// 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.Threading.Channels { public enum BoundedChannelFullMode { Wait = 0, DropNewest = 1, DropOldest = 2, DropWrite = 3, } public sealed partial class BoundedChannelOptions : System.Threading.Channels.ChannelOptions { public BoundedChannelOptions(int capacity) { } public int Capacity { get { throw null; } set { } } public System.Threading.Channels.BoundedChannelFullMode FullMode { get { throw null; } set { } } } public static partial class Channel { public static System.Threading.Channels.Channel<T> CreateBounded<T>(int capacity) { throw null; } public static System.Threading.Channels.Channel<T> CreateBounded<T>(System.Threading.Channels.BoundedChannelOptions options) { throw null; } public static System.Threading.Channels.Channel<T> CreateBounded<T>(BoundedChannelOptions options, Action<T>? itemDropped) { throw null; } public static System.Threading.Channels.Channel<T> CreateUnbounded<T>() { throw null; } public static System.Threading.Channels.Channel<T> CreateUnbounded<T>(System.Threading.Channels.UnboundedChannelOptions options) { throw null; } } public partial class ChannelClosedException : System.InvalidOperationException { public ChannelClosedException() { } public ChannelClosedException(System.Exception? innerException) { } public ChannelClosedException(string? message) { } public ChannelClosedException(string? message, System.Exception? innerException) { } } public abstract partial class ChannelOptions { protected ChannelOptions() { } public bool AllowSynchronousContinuations { get { throw null; } set { } } public bool SingleReader { get { throw null; } set { } } public bool SingleWriter { get { throw null; } set { } } } public abstract partial class ChannelReader<T> { protected ChannelReader() { } public virtual bool CanCount { get { throw null; } } public virtual bool CanPeek { get { throw null; } } public virtual System.Threading.Tasks.Task Completion { get { throw null; } } public virtual int Count { get { throw null; } } public virtual System.Threading.Tasks.ValueTask<T> ReadAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual bool TryPeek([System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T item) { throw null; } public abstract bool TryRead([System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T item); public abstract System.Threading.Tasks.ValueTask<bool> WaitToReadAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } public abstract partial class ChannelWriter<T> { protected ChannelWriter() { } public void Complete(System.Exception? error = null) { } public virtual bool TryComplete(System.Exception? error = null) { throw null; } public abstract bool TryWrite(T item); public abstract System.Threading.Tasks.ValueTask<bool> WaitToWriteAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); public virtual System.Threading.Tasks.ValueTask WriteAsync(T item, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public abstract partial class Channel<T> : System.Threading.Channels.Channel<T, T> { protected Channel() { } } public abstract partial class Channel<TWrite, TRead> { protected Channel() { } public System.Threading.Channels.ChannelReader<TRead> Reader { get { throw null; } protected set { } } public System.Threading.Channels.ChannelWriter<TWrite> Writer { get { throw null; } protected set { } } public static implicit operator System.Threading.Channels.ChannelReader<TRead> (System.Threading.Channels.Channel<TWrite, TRead> channel) { throw null; } public static implicit operator System.Threading.Channels.ChannelWriter<TWrite> (System.Threading.Channels.Channel<TWrite, TRead> channel) { throw null; } } public sealed partial class UnboundedChannelOptions : System.Threading.Channels.ChannelOptions { public UnboundedChannelOptions() { } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/HardwareIntrinsics/General/Vector256_1/op_BitwiseOr.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\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_BitwiseOrSByte() { var test = new VectorBinaryOpTest__op_BitwiseOrSByte(); // 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_BitwiseOrSByte { 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(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); 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<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<SByte> _fld1; public Vector256<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__op_BitwiseOrSByte testClass) { var result = _fld1 | _fld2; Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector256<SByte> _clsVar1; private static Vector256<SByte> _clsVar2; private Vector256<SByte> _fld1; private Vector256<SByte> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__op_BitwiseOrSByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); } public VectorBinaryOpTest__op_BitwiseOrSByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr) | Unsafe.Read<Vector256<SByte>>(_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(Vector256<SByte>).GetMethod("op_BitwiseOr", new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(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<Vector256<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<SByte>>(_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_BitwiseOrSByte(); 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(Vector256<SByte> op1, Vector256<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (sbyte)(left[0] | right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (sbyte)(left[i] | right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_BitwiseOr<SByte>(Vector256<SByte>, Vector256<SByte>): {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_BitwiseOrSByte() { var test = new VectorBinaryOpTest__op_BitwiseOrSByte(); // 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_BitwiseOrSByte { 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(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); 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<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<SByte> _fld1; public Vector256<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__op_BitwiseOrSByte testClass) { var result = _fld1 | _fld2; Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector256<SByte> _clsVar1; private static Vector256<SByte> _clsVar2; private Vector256<SByte> _fld1; private Vector256<SByte> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__op_BitwiseOrSByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); } public VectorBinaryOpTest__op_BitwiseOrSByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr) | Unsafe.Read<Vector256<SByte>>(_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(Vector256<SByte>).GetMethod("op_BitwiseOr", new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(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<Vector256<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<SByte>>(_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_BitwiseOrSByte(); 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(Vector256<SByte> op1, Vector256<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (sbyte)(left[0] | right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (sbyte)(left[i] | right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_BitwiseOr<SByte>(Vector256<SByte>, Vector256<SByte>): {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,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Private.Xml/src/System/Xml/IHasXmlNode.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 { public interface IHasXmlNode { XmlNode GetNode(); } }
// 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 { public interface IHasXmlNode { XmlNode GetNode(); } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/RuntimeNoMetadataNamedTypeInfo.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.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.CustomAttributes; using Internal.LowLevelLinq; using Internal.Reflection.Tracing; using Internal.Reflection.Core.Execution; using StructLayoutAttribute = System.Runtime.InteropServices.StructLayoutAttribute; namespace System.Reflection.Runtime.TypeInfos { // // TypeInfos that represent type definitions (i.e. Foo or Foo<>, but not Foo<int> or arrays/pointers/byrefs.) // that not opted into pay-for-play metadata. // internal sealed partial class RuntimeNoMetadataNamedTypeInfo : RuntimeTypeDefinitionTypeInfo { private RuntimeNoMetadataNamedTypeInfo(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition) { _typeHandle = typeHandle; _isGenericTypeDefinition = isGenericTypeDefinition; } public sealed override Assembly Assembly { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override bool ContainsGenericParameters { get { return _isGenericTypeDefinition; } } public sealed override IEnumerable<CustomAttributeData> CustomAttributes { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override string FullName { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_FullName(this); #endif throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override Guid GUID { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override bool IsGenericTypeDefinition { get { return _isGenericTypeDefinition; } } #if DEBUG public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => base.HasSameMetadataDefinitionAs(other); #endif public sealed override string Namespace { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_Namespace(this); #endif throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override StructLayoutAttribute StructLayoutAttribute { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override string ToString() { return _typeHandle.LastResortString(); } public sealed override int MetadataToken { get { throw new InvalidOperationException(SR.NoMetadataTokenAvailable); } } protected sealed override TypeAttributes GetAttributeFlagsImpl() { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } protected sealed override int InternalGetHashCode() { return _typeHandle.GetHashCode(); } // // Returns the anchoring typedef that declares the members that this type wants returned by the Declared*** properties. // The Declared*** properties will project the anchoring typedef's members by overriding their DeclaringType property with "this" // and substituting the value of this.TypeContext into any generic parameters. // // Default implementation returns null which causes the Declared*** properties to return no members. // // Note that this does not apply to DeclaredNestedTypes. Nested types and their containers have completely separate generic instantiation environments // (despite what C# might lead you to think.) Constructed generic types return the exact same same nested types that its generic type definition does // - i.e. their DeclaringTypes refer back to the generic type definition, not the constructed generic type.) // // Note also that we cannot use this anchoring concept for base types because of generic parameters. Generic parameters return // baseclass and interfaces based on its constraints. // internal sealed override RuntimeNamedTypeInfo AnchoringTypeDefinitionForDeclaredMembers { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } internal sealed override bool CanBrowseWithoutMissingMetadataExceptions => false; internal sealed override Type InternalDeclaringType { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override string InternalGetNameIfAvailable(ref Type rootCauseForFailure) { rootCauseForFailure = this; return null; } internal sealed override string InternalFullNameOfAssembly { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } internal sealed override RuntimeTypeHandle InternalTypeHandleIfAvailable { get { return _typeHandle; } } internal sealed override RuntimeTypeInfo[] RuntimeGenericTypeParameters { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } // // Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null. // internal sealed override QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } // // Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and // insertion of the TypeContext. // internal sealed override QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } // // Returns the generic parameter substitutions to use when enumerating declared members, base class and implemented interfaces. // internal sealed override TypeContext TypeContext { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } private readonly RuntimeTypeHandle _typeHandle; private readonly bool _isGenericTypeDefinition; } }
// 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.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.CustomAttributes; using Internal.LowLevelLinq; using Internal.Reflection.Tracing; using Internal.Reflection.Core.Execution; using StructLayoutAttribute = System.Runtime.InteropServices.StructLayoutAttribute; namespace System.Reflection.Runtime.TypeInfos { // // TypeInfos that represent type definitions (i.e. Foo or Foo<>, but not Foo<int> or arrays/pointers/byrefs.) // that not opted into pay-for-play metadata. // internal sealed partial class RuntimeNoMetadataNamedTypeInfo : RuntimeTypeDefinitionTypeInfo { private RuntimeNoMetadataNamedTypeInfo(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition) { _typeHandle = typeHandle; _isGenericTypeDefinition = isGenericTypeDefinition; } public sealed override Assembly Assembly { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override bool ContainsGenericParameters { get { return _isGenericTypeDefinition; } } public sealed override IEnumerable<CustomAttributeData> CustomAttributes { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override string FullName { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_FullName(this); #endif throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override Guid GUID { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override bool IsGenericTypeDefinition { get { return _isGenericTypeDefinition; } } #if DEBUG public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => base.HasSameMetadataDefinitionAs(other); #endif public sealed override string Namespace { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_Namespace(this); #endif throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override StructLayoutAttribute StructLayoutAttribute { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override string ToString() { return _typeHandle.LastResortString(); } public sealed override int MetadataToken { get { throw new InvalidOperationException(SR.NoMetadataTokenAvailable); } } protected sealed override TypeAttributes GetAttributeFlagsImpl() { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } protected sealed override int InternalGetHashCode() { return _typeHandle.GetHashCode(); } // // Returns the anchoring typedef that declares the members that this type wants returned by the Declared*** properties. // The Declared*** properties will project the anchoring typedef's members by overriding their DeclaringType property with "this" // and substituting the value of this.TypeContext into any generic parameters. // // Default implementation returns null which causes the Declared*** properties to return no members. // // Note that this does not apply to DeclaredNestedTypes. Nested types and their containers have completely separate generic instantiation environments // (despite what C# might lead you to think.) Constructed generic types return the exact same same nested types that its generic type definition does // - i.e. their DeclaringTypes refer back to the generic type definition, not the constructed generic type.) // // Note also that we cannot use this anchoring concept for base types because of generic parameters. Generic parameters return // baseclass and interfaces based on its constraints. // internal sealed override RuntimeNamedTypeInfo AnchoringTypeDefinitionForDeclaredMembers { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } internal sealed override bool CanBrowseWithoutMissingMetadataExceptions => false; internal sealed override Type InternalDeclaringType { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override string InternalGetNameIfAvailable(ref Type rootCauseForFailure) { rootCauseForFailure = this; return null; } internal sealed override string InternalFullNameOfAssembly { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } internal sealed override RuntimeTypeHandle InternalTypeHandleIfAvailable { get { return _typeHandle; } } internal sealed override RuntimeTypeInfo[] RuntimeGenericTypeParameters { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } // // Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null. // internal sealed override QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } // // Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and // insertion of the TypeContext. // internal sealed override QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } // // Returns the generic parameter substitutions to use when enumerating declared members, base class and implemented interfaces. // internal sealed override TypeContext TypeContext { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } private readonly RuntimeTypeHandle _typeHandle; private readonly bool _isGenericTypeDefinition; } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/jit64/gc/misc/structret4_1.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; struct Pad { #pragma warning disable 0414 public double d1; public double d2; public double d3; public double d4; public double d5; public double d6; public double d7; public double d8; public double d9; public double d10; public double d11; public double d12; public double d13; public double d14; public double d15; public double d16; public double d17; public double d18; public double d19; public double d20; public double d21; public double d22; public double d23; public double d24; public double d25; public double d26; public double d27; public double d28; public double d29; public double d30; } struct S { public String str2; #pragma warning restore 0414 public String str; public Pad pad; public S(String s) { str = s; str2 = s + str; pad.d1 = pad.d2 = pad.d3 = pad.d4 = pad.d5 = pad.d6 = pad.d7 = pad.d8 = pad.d9 = pad.d10 = pad.d11 = pad.d12 = pad.d13 = pad.d14 = pad.d15 = pad.d16 = pad.d17 = pad.d18 = pad.d19 = pad.d20 = pad.d21 = pad.d22 = pad.d23 = pad.d24 = pad.d25 = pad.d26 = pad.d27 = pad.d28 = pad.d29 = pad.d30 = 3.3; } } class Test_structret4_1 { public static S c(S s1, S s2, S s3) { s1.str = (s1.str + s2.str + s3.str); return s1; } public static int Main() { S sM = new S("test"); S sM2 = new S("test2"); S sM3 = new S("test3"); Console.WriteLine(c(sM, sM2, sM3)); 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; struct Pad { #pragma warning disable 0414 public double d1; public double d2; public double d3; public double d4; public double d5; public double d6; public double d7; public double d8; public double d9; public double d10; public double d11; public double d12; public double d13; public double d14; public double d15; public double d16; public double d17; public double d18; public double d19; public double d20; public double d21; public double d22; public double d23; public double d24; public double d25; public double d26; public double d27; public double d28; public double d29; public double d30; } struct S { public String str2; #pragma warning restore 0414 public String str; public Pad pad; public S(String s) { str = s; str2 = s + str; pad.d1 = pad.d2 = pad.d3 = pad.d4 = pad.d5 = pad.d6 = pad.d7 = pad.d8 = pad.d9 = pad.d10 = pad.d11 = pad.d12 = pad.d13 = pad.d14 = pad.d15 = pad.d16 = pad.d17 = pad.d18 = pad.d19 = pad.d20 = pad.d21 = pad.d22 = pad.d23 = pad.d24 = pad.d25 = pad.d26 = pad.d27 = pad.d28 = pad.d29 = pad.d30 = 3.3; } } class Test_structret4_1 { public static S c(S s1, S s2, S s3) { s1.str = (s1.str + s2.str + s3.str); return s1; } public static int Main() { S sM = new S("test"); S sM2 = new S("test2"); S sM3 = new S("test3"); Console.WriteLine(c(sM, sM2, sM3)); return 100; } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.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.Xml; using System.Xml.XPath; using System.Globalization; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Xml.Schema; using System.IO; using System.Text; using System.Runtime.InteropServices; using System.Reflection; namespace System.Xml.Schema { // // NOTE!!! LARGE PORTIONS OF THIS FILE ARE AUTOGENERATED BY GENERATECONVERTER.CS. DO NOT MANUALLY CHANGE ANY CODE // WITHIN #REGION. INSTEAD, MODIFY GENERATECONVERTER.CS. // // SUMMARY // ======= // For each Xml type, there is a set of Clr types that can represent it. Some of these mappings involve // loss of fidelity. For example, xsd:dateTime can be represented as System.DateTime, but only at the expense // of normalizing the time zone. And xs:duration can be represented as System.TimeSpan, but only at the expense // of discarding variations such as "P50H", "P1D26H", "P2D2H", all of which are normalized as "P2D2H". // // Implementations of this class convert between the various Clr representations of Xml types. Note that // in *no* case is the Xml type ever modified. Only the Clr type is changed. This means that in cases where // the Xml type is part of the representation (such as XmlAtomicValue), the destination value is guaranteed // to have the same Xml type. // // For all converters, converting to typeof(object) is identical to converting to XmlSchemaType.Datatype.ValueType. // // // ATOMIC MAPPINGS // =============== // // ----------------------------------------------------------------------------------------------------------- // Source/Destination System.String Other Clr Type // ----------------------------------------------------------------------------------------------------------- // System.String No-op conversion. Use Xsd rules to convert from the string // to primitive, full-fidelity Clr type (use // XmlConvert where possible). Use Clr rules // to convert to destination type. // ----------------------------------------------------------------------------------------------------------- // Other Clr Type Use Clr rules to convert from Use Clr rules to convert from source to // source type to primitive, full- destination type. // fidelity Clr type. Use Xsd rules // to convert to a string (use // XmlConvert where possible). // ----------------------------------------------------------------------------------------------------------- // // // LIST MAPPINGS // ============= // The following Clr types can be used to represent Xsd list types: IList, ICollection, IEnumerable, Type[], // String. // // ----------------------------------------------------------------------------------------------------------- // Source/Destination System.String Clr List Type // ----------------------------------------------------------------------------------------------------------- // System.String No-op conversion Tokenize the string by whitespace, create a // String[] from tokens, and follow List => List // rules. // ----------------------------------------------------------------------------------------------------------- // Clr List Type Follow List => String[] rules, Create destination list having the same length // then concatenate strings from array, as the source list. For each item in the // separating adjacent strings with a source list, call the atomic converter to // single space character. convert to the destination type. The destination // item type for IList, ICollection, IEnumerable // is typeof(object). The destination item type // for Type[] is Type. // ----------------------------------------------------------------------------------------------------------- // // // UNION MAPPINGS // ============== // Union types may only be represented using System.Xml.Schema.XmlAtomicValue or System.String. Either the // source type or the destination type must therefore always be either System.String or // System.Xml.Schema.XmlAtomicValue. // // ----------------------------------------------------------------------------------------------------------- // Source/Destination System.String XmlAtomicValue Other Clr Type // ----------------------------------------------------------------------------------------------------------- // System.String No-op conversion Follow System.String=> Call ParseValue in order to determine // Other Clr Type rules. the member type. Call ChangeType on // the member type's converter to convert // to desired Clr type. // ----------------------------------------------------------------------------------------------------------- // XmlAtomicValue Follow XmlAtomicValue No-op conversion. Call ReadValueAs, where destinationType // => Other Clr Type is the desired Clr type. // rules. // ----------------------------------------------------------------------------------------------------------- // Other Clr Type InvalidCastException InvalidCastException InvalidCastException // ----------------------------------------------------------------------------------------------------------- // // // EXAMPLES // ======== // // ----------------------------------------------------------------------------------------------------------- // Source Destination // Xml Type Value Type Conversion Steps Explanation // ----------------------------------------------------------------------------------------------------------- // xs:int "10" Byte "10" => 10M => (byte) 10 Primitive, full-fidelity for xs:int // is a truncated decimal // ----------------------------------------------------------------------------------------------------------- // xs:int "10.10" Byte FormatException xs:integer parsing rules do not // allow fractional parts // ----------------------------------------------------------------------------------------------------------- // xs:int 10.10M Byte 10.10M => (byte) 10 Default Clr rules truncate when // converting from Decimal to Byte // ----------------------------------------------------------------------------------------------------------- // xs:int 10.10M Decimal 10.10M => 10.10M Decimal => Decimal is no-op // ----------------------------------------------------------------------------------------------------------- // xs:int 10.10M String 10.10M => 10M => "10" // ----------------------------------------------------------------------------------------------------------- // xs:int "hello" String "hello" => "hello" String => String is no-op // ----------------------------------------------------------------------------------------------------------- // xs:byte "300" Int32 "300" => 300M => (int) 300 // ----------------------------------------------------------------------------------------------------------- // xs:byte 300 Byte 300 => 300M => OverflowException Clr overflows when converting from // Decimal to Byte // ----------------------------------------------------------------------------------------------------------- // xs:byte 300 XmlAtomicValue new XmlAtomicValue(xs:byte, 300) Invalid atomic value created // ----------------------------------------------------------------------------------------------------------- // xs:double 1.234f String 1.234f => 1.2339999675750732d => Converting a Single value to a Double // "1.2339999675750732" value zero-extends it in base-2, so // "garbage" digits appear when it's // converted to base-10. // ----------------------------------------------------------------------------------------------------------- // xs:int* {1, "2", String {1, "2", 3.1M} => Delegate to xs:int converter to // 3.1M} {"1", "2", "3"} => "1 2 3" convert each item to a string. // ----------------------------------------------------------------------------------------------------------- // xs:int* "1 2 3" Int32[] "1 2 3" => {"1", "2", "3"} => // {1, 2, 3} // ----------------------------------------------------------------------------------------------------------- // xs:int* {1, "2", Object[] {1, "2", 3.1M} => xs:int converter uses Int32 by default, // 3.1M} {(object)1, (object)2, (object)3} so returns boxed Int32 values. // ----------------------------------------------------------------------------------------------------------- // (xs:int | "1 2001" XmlAtomicValue[] "1 2001" => {(xs:int) 1, // xs:gYear)* (xs:gYear) 2001} // ----------------------------------------------------------------------------------------------------------- // (xs:int* | "1 2001" String "1 2001" No-op conversion even though // xs:gYear*) ParseValue would fail if it were called. // ----------------------------------------------------------------------------------------------------------- // (xs:int* | "1 2001" Int[] XmlSchemaException ParseValue fails. // xs:gYear*) // ----------------------------------------------------------------------------------------------------------- // internal abstract class XmlValueConverter { public abstract bool ToBoolean(long value); public abstract bool ToBoolean(int value); public abstract bool ToBoolean(double value); public abstract bool ToBoolean(DateTime value); public abstract bool ToBoolean(string value); public abstract bool ToBoolean(object value); public abstract int ToInt32(bool value); public abstract int ToInt32(long value); public abstract int ToInt32(double value); public abstract int ToInt32(DateTime value); public abstract int ToInt32(string value); public abstract int ToInt32(object value); public abstract long ToInt64(bool value); public abstract long ToInt64(int value); public abstract long ToInt64(double value); public abstract long ToInt64(DateTime value); public abstract long ToInt64(string value); public abstract long ToInt64(object value); public abstract decimal ToDecimal(string value); public abstract decimal ToDecimal(object value); public abstract double ToDouble(bool value); public abstract double ToDouble(int value); public abstract double ToDouble(long value); public abstract double ToDouble(DateTime value); public abstract double ToDouble(string value); public abstract double ToDouble(object value); public abstract float ToSingle(double value); public abstract float ToSingle(string value); public abstract float ToSingle(object value); public abstract DateTime ToDateTime(bool value); public abstract DateTime ToDateTime(int value); public abstract DateTime ToDateTime(long value); public abstract DateTime ToDateTime(double value); public abstract DateTime ToDateTime(DateTimeOffset value); public abstract DateTime ToDateTime(string value); public abstract DateTime ToDateTime(object value); public abstract DateTimeOffset ToDateTimeOffset(DateTime value); public abstract DateTimeOffset ToDateTimeOffset(string value); public abstract DateTimeOffset ToDateTimeOffset(object value); public abstract string ToString(bool value); public abstract string ToString(int value); public abstract string ToString(long value); public abstract string ToString(decimal value); public abstract string ToString(float value); public abstract string ToString(double value); public abstract string ToString(DateTime value); public abstract string ToString(DateTimeOffset value); public abstract string ToString(object value); public abstract string ToString(object value, IXmlNamespaceResolver? nsResolver); public abstract object ChangeType(bool value, Type destinationType); public abstract object ChangeType(int value, Type destinationType); public abstract object ChangeType(long value, Type destinationType); public abstract object ChangeType(decimal value, Type destinationType); public abstract object ChangeType(double value, Type destinationType); public abstract object ChangeType(DateTime value, Type destinationType); public abstract object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver); public abstract object ChangeType(object value, Type destinationType); public abstract object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver); } internal abstract class XmlBaseConverter : XmlValueConverter { private readonly XmlSchemaType? _schemaType; private readonly XmlTypeCode _typeCode; private readonly Type? _clrTypeDefault; protected XmlBaseConverter(XmlSchemaType schemaType) { // XmlValueConverter is defined only on types with simple content XmlSchemaDatatype? datatype = schemaType.Datatype; Debug.Assert(schemaType != null && datatype != null, "schemaType or schemaType.Datatype may not be null"); while (schemaType != null && !(schemaType is XmlSchemaSimpleType)) { schemaType = schemaType.BaseXmlSchemaType!; } if (schemaType == null) { //Did not find any simple type in the parent chain schemaType = XmlSchemaType.GetBuiltInSimpleType(datatype.TypeCode); } Debug.Assert(schemaType.Datatype!.Variety != XmlSchemaDatatypeVariety.List, "schemaType must be list's item type, not list itself"); _schemaType = schemaType; _typeCode = schemaType.TypeCode; _clrTypeDefault = schemaType.Datatype.ValueType; } protected XmlBaseConverter(XmlTypeCode typeCode) { switch (typeCode) { case XmlTypeCode.Item: _clrTypeDefault = XPathItemType; break; case XmlTypeCode.Node: _clrTypeDefault = XPathNavigatorType; break; case XmlTypeCode.AnyAtomicType: _clrTypeDefault = XmlAtomicValueType; break; default: Debug.Fail($"Type code {typeCode} is not supported."); break; } _typeCode = typeCode; } protected XmlBaseConverter(XmlBaseConverter converterAtomic) { _schemaType = converterAtomic._schemaType; _typeCode = converterAtomic._typeCode; _clrTypeDefault = Array.CreateInstance(converterAtomic.DefaultClrType!, 0).GetType(); } protected XmlBaseConverter(XmlBaseConverter converterAtomic, Type clrTypeDefault) { _schemaType = converterAtomic._schemaType; _typeCode = converterAtomic._typeCode; _clrTypeDefault = clrTypeDefault; } protected static readonly Type ICollectionType = typeof(ICollection); protected static readonly Type IEnumerableType = typeof(IEnumerable); protected static readonly Type IListType = typeof(IList); protected static readonly Type ObjectArrayType = typeof(object[]); protected static readonly Type StringArrayType = typeof(string[]); protected static readonly Type XmlAtomicValueArrayType = typeof(XmlAtomicValue[]); #region AUTOGENERATED_XMLBASECONVERTER protected static readonly Type DecimalType = typeof(decimal); protected static readonly Type Int32Type = typeof(int); protected static readonly Type Int64Type = typeof(long); protected static readonly Type StringType = typeof(string); protected static readonly Type XmlAtomicValueType = typeof(XmlAtomicValue); protected static readonly Type ObjectType = typeof(object); protected static readonly Type ByteType = typeof(byte); protected static readonly Type Int16Type = typeof(short); protected static readonly Type SByteType = typeof(sbyte); protected static readonly Type UInt16Type = typeof(ushort); protected static readonly Type UInt32Type = typeof(uint); protected static readonly Type UInt64Type = typeof(ulong); protected static readonly Type XPathItemType = typeof(XPathItem); protected static readonly Type DoubleType = typeof(double); protected static readonly Type SingleType = typeof(float); protected static readonly Type DateTimeType = typeof(DateTime); protected static readonly Type DateTimeOffsetType = typeof(DateTimeOffset); protected static readonly Type BooleanType = typeof(bool); protected static readonly Type ByteArrayType = typeof(byte[]); protected static readonly Type XmlQualifiedNameType = typeof(XmlQualifiedName); protected static readonly Type UriType = typeof(Uri); protected static readonly Type TimeSpanType = typeof(TimeSpan); protected static readonly Type XPathNavigatorType = typeof(XPathNavigator); public override bool ToBoolean(DateTime value) { return (bool)ChangeType((object)value, BooleanType, null); } public override bool ToBoolean(double value) { return (bool)ChangeType((object)value, BooleanType, null); } public override bool ToBoolean(int value) { return (bool)ChangeType((object)value, BooleanType, null); } public override bool ToBoolean(long value) { return (bool)ChangeType((object)value, BooleanType, null); } public override bool ToBoolean(string value) { return (bool)ChangeType((object)value, BooleanType, null); } public override bool ToBoolean(object value) { return (bool)ChangeType((object)value, BooleanType, null); } public override DateTime ToDateTime(bool value) { return (DateTime)ChangeType((object)value, DateTimeType, null); } public override DateTime ToDateTime(DateTimeOffset value) { return (DateTime)ChangeType((object)value, DateTimeType, null); } public override DateTime ToDateTime(double value) { return (DateTime)ChangeType((object)value, DateTimeType, null); } public override DateTime ToDateTime(int value) { return (DateTime)ChangeType((object)value, DateTimeType, null); } public override DateTime ToDateTime(long value) { return (DateTime)ChangeType((object)value, DateTimeType, null); } public override DateTime ToDateTime(string value) { return (DateTime)ChangeType((object)value, DateTimeType, null); } public override DateTime ToDateTime(object value) { return (DateTime)ChangeType((object)value, DateTimeType, null); } public override DateTimeOffset ToDateTimeOffset(DateTime value) { return (DateTimeOffset)ChangeType((object)value, DateTimeOffsetType, null); } public override DateTimeOffset ToDateTimeOffset(string value) { return (DateTimeOffset)ChangeType((object)value, DateTimeOffsetType, null); } public override DateTimeOffset ToDateTimeOffset(object value) { return (DateTimeOffset)ChangeType((object)value, DateTimeOffsetType, null); } public override decimal ToDecimal(string value) { return (decimal)ChangeType((object)value, DecimalType, null); } public override decimal ToDecimal(object value) { return (decimal)ChangeType((object)value, DecimalType, null); } public override double ToDouble(bool value) { return (double)ChangeType((object)value, DoubleType, null); } public override double ToDouble(DateTime value) { return (double)ChangeType((object)value, DoubleType, null); } public override double ToDouble(int value) { return (double)ChangeType((object)value, DoubleType, null); } public override double ToDouble(long value) { return (double)ChangeType((object)value, DoubleType, null); } public override double ToDouble(string value) { return (double)ChangeType((object)value, DoubleType, null); } public override double ToDouble(object value) { return (double)ChangeType((object)value, DoubleType, null); } public override int ToInt32(bool value) { return (int)ChangeType((object)value, Int32Type, null); } public override int ToInt32(DateTime value) { return (int)ChangeType((object)value, Int32Type, null); } public override int ToInt32(double value) { return (int)ChangeType((object)value, Int32Type, null); } public override int ToInt32(long value) { return (int)ChangeType((object)value, Int32Type, null); } public override int ToInt32(string value) { return (int)ChangeType((object)value, Int32Type, null); } public override int ToInt32(object value) { return (int)ChangeType((object)value, Int32Type, null); } public override long ToInt64(bool value) { return (long)ChangeType((object)value, Int64Type, null); } public override long ToInt64(DateTime value) { return (long)ChangeType((object)value, Int64Type, null); } public override long ToInt64(double value) { return (long)ChangeType((object)value, Int64Type, null); } public override long ToInt64(int value) { return (long)ChangeType((object)value, Int64Type, null); } public override long ToInt64(string value) { return (long)ChangeType((object)value, Int64Type, null); } public override long ToInt64(object value) { return (long)ChangeType((object)value, Int64Type, null); } public override float ToSingle(double value) { return (float)ChangeType((object)value, SingleType, null); } public override float ToSingle(string value) { return (float)ChangeType((object)value, SingleType, null); } public override float ToSingle(object value) { return (float)ChangeType((object)value, SingleType, null); } public override string ToString(bool value) { return (string)ChangeType((object)value, StringType, null); } public override string ToString(DateTime value) { return (string)ChangeType((object)value, StringType, null); } public override string ToString(DateTimeOffset value) { return (string)ChangeType((object)value, StringType, null); } public override string ToString(decimal value) { return (string)ChangeType((object)value, StringType, null); } public override string ToString(double value) { return (string)ChangeType((object)value, StringType, null); } public override string ToString(int value) { return (string)ChangeType((object)value, StringType, null); } public override string ToString(long value) { return (string)ChangeType((object)value, StringType, null); } public override string ToString(float value) { return (string)ChangeType((object)value, StringType, null); } public override string ToString(object value, IXmlNamespaceResolver? nsResolver) { return (string)ChangeType((object)value, StringType, nsResolver); } public override string ToString(object value) { return this.ToString(value, null); } public override object ChangeType(bool value, Type destinationType) { return (object)ChangeType((object)value, destinationType, null); } public override object ChangeType(DateTime value, Type destinationType) { return (object)ChangeType((object)value, destinationType, null); } public override object ChangeType(decimal value, Type destinationType) { return (object)ChangeType((object)value, destinationType, null); } public override object ChangeType(double value, Type destinationType) { return (object)ChangeType((object)value, destinationType, null); } public override object ChangeType(int value, Type destinationType) { return (object)ChangeType((object)value, destinationType, null); } public override object ChangeType(long value, Type destinationType) { return (object)ChangeType((object)value, destinationType, null); } public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { return (object)ChangeType((object)value, destinationType, nsResolver); } public override object ChangeType(object value, Type destinationType) { return this.ChangeType(value, destinationType, null); } #endregion /// <summary> /// Return this converter's prime schema type (may be null in case of Node, Item, etc). /// </summary> protected XmlSchemaType? SchemaType { get { return _schemaType; } } /// <summary> /// Return the XmlTypeCode of this converter's prime schema type. /// </summary> protected XmlTypeCode TypeCode { get { return _typeCode; } } /// <summary> /// Return a string representation of this converter's prime schema type. /// </summary> protected string XmlTypeName { get { XmlSchemaType? type = _schemaType; if (type != null) { while (type!.QualifiedName.IsEmpty) { // Walk base classes until one with a name is found (in worst case, all simple types derive from xs:anySimpleType) type = type.BaseXmlSchemaType; } return QNameToString(type.QualifiedName); } // SchemaType is null in the case of item, node, and xdt:anyAtomicType if (_typeCode == XmlTypeCode.Node) return "node"; if (_typeCode == XmlTypeCode.AnyAtomicType) return "xdt:anyAtomicType"; Debug.Assert(_typeCode == XmlTypeCode.Item, "If SchemaType is null, then TypeCode may only be Item, Node, or AnyAtomicType"); return "item"; } } /// <summary> /// Return default V1 Clr mapping of this converter's type. /// </summary> protected Type? DefaultClrType { get { return _clrTypeDefault; } } /// <summary> /// Type.IsSubtypeOf does not return true if types are equal, this method does. /// </summary> protected static bool IsDerivedFrom(Type? derivedType, Type baseType) { while (derivedType != null) { if (derivedType == baseType) return true; derivedType = derivedType.BaseType; } return false; } /// <summary> /// Create an InvalidCastException for cases where either "destinationType" or "sourceType" is not a supported CLR representation /// for this Xml type. /// </summary> protected Exception CreateInvalidClrMappingException(Type sourceType, Type destinationType) { if (sourceType == destinationType) return new InvalidCastException(SR.Format(SR.XmlConvert_TypeBadMapping, XmlTypeName, sourceType.Name)); return new InvalidCastException(SR.Format(SR.XmlConvert_TypeBadMapping2, XmlTypeName, sourceType.Name, destinationType.Name)); } /// <summary> /// Convert an XmlQualifiedName to a string, using somewhat different rules than XmlQualifiedName.ToString(): /// 1. Recognize the built-in xs: and xdt: namespaces and print the short prefix rather than the long namespace /// 2. Use brace characters "{", "}" around the namespace portion of the QName /// </summary> protected static string QNameToString(XmlQualifiedName name) { if (name.Namespace.Length == 0) { return name.Name; } else if (name.Namespace == XmlReservedNs.NsXs) { return $"xs:{name.Name}"; } else if (name.Namespace == XmlReservedNs.NsXQueryDataType) { return $"xdt:{name.Name}"; } else { return $"{{{name.Namespace}}}{name.Name}"; } } /// <summary> /// This method is called when a valid conversion cannot be found. By default, this method throws an error. It can /// be overridden in derived classes to support list conversions. /// </summary> protected virtual object ChangeListType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { throw CreateInvalidClrMappingException(value.GetType(), destinationType); } //------------------------------------------------------------------------ // From String Conversion Helpers //------------------------------------------------------------------------ protected static byte[] StringToBase64Binary(string value) { return Convert.FromBase64String(XmlConvert.TrimString(value)); } protected static DateTime StringToDate(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.Date)); } protected static DateTime StringToDateTime(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.DateTime)); } protected static TimeSpan StringToDayTimeDuration(string value) { // Parse string as DayTimeDuration and convert it to a DayTimeDuration TimeSpan (it is an error to have year and month parts) return new XsdDuration(value, XsdDuration.DurationType.DayTimeDuration).ToTimeSpan(XsdDuration.DurationType.DayTimeDuration); } protected static TimeSpan StringToDuration(string value) { return new XsdDuration(value, XsdDuration.DurationType.Duration).ToTimeSpan(XsdDuration.DurationType.Duration); } protected static DateTime StringToGDay(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.GDay)); } protected static DateTime StringToGMonth(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.GMonth)); } protected static DateTime StringToGMonthDay(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.GMonthDay)); } protected static DateTime StringToGYear(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.GYear)); } protected static DateTime StringToGYearMonth(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.GYearMonth)); } protected static DateTimeOffset StringToDateOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.Date)); } protected static DateTimeOffset StringToDateTimeOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.DateTime)); } protected static DateTimeOffset StringToGDayOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.GDay)); } protected static DateTimeOffset StringToGMonthOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.GMonth)); } protected static DateTimeOffset StringToGMonthDayOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.GMonthDay)); } protected static DateTimeOffset StringToGYearOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.GYear)); } protected static DateTimeOffset StringToGYearMonthOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.GYearMonth)); } protected static byte[] StringToHexBinary(string value) { try { return XmlConvert.FromBinHexString(XmlConvert.TrimString(value), false); } catch (XmlException e) { throw new FormatException(e.Message); } } protected static XmlQualifiedName StringToQName(string value, IXmlNamespaceResolver? nsResolver) { string prefix, localName; string? ns; value = value.Trim(); // Parse prefix:localName try { ValidateNames.ParseQNameThrow(value, out prefix, out localName); } catch (XmlException e) { throw new FormatException(e.Message); } // Throw error if no namespaces are in scope if (nsResolver == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Lookup namespace ns = nsResolver.LookupNamespace(prefix); if (ns == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Create XmlQualfiedName return new XmlQualifiedName(localName, ns); } protected static DateTime StringToTime(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.Time)); } protected static DateTimeOffset StringToTimeOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.Time)); } protected static TimeSpan StringToYearMonthDuration(string value) { // Parse string as YearMonthDuration and convert it to a YearMonthDuration TimeSpan (it is an error to have day and time parts) return new XsdDuration(value, XsdDuration.DurationType.YearMonthDuration).ToTimeSpan(XsdDuration.DurationType.YearMonthDuration); } //------------------------------------------------------------------------ // To String Conversion Helpers //------------------------------------------------------------------------ protected static string AnyUriToString(Uri value) { return value.OriginalString; } protected static string Base64BinaryToString(byte[] value) { return Convert.ToBase64String(value); } protected static string DateToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.Date)).ToString(); } protected static string DateTimeToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.DateTime)).ToString(); } protected static string DayTimeDurationToString(TimeSpan value) { return new XsdDuration(value, XsdDuration.DurationType.DayTimeDuration).ToString(XsdDuration.DurationType.DayTimeDuration); } protected static string DurationToString(TimeSpan value) { return new XsdDuration(value, XsdDuration.DurationType.Duration).ToString(XsdDuration.DurationType.Duration); } protected static string GDayToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.GDay)).ToString(); } protected static string GMonthToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.GMonth)).ToString(); } protected static string GMonthDayToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.GMonthDay)).ToString(); } protected static string GYearToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.GYear)).ToString(); } protected static string GYearMonthToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.GYearMonth)).ToString(); } protected static string DateOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.Date)).ToString(); } protected static string DateTimeOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.DateTime)).ToString(); } protected static string GDayOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.GDay)).ToString(); } protected static string GMonthOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.GMonth)).ToString(); } protected static string GMonthDayOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.GMonthDay)).ToString(); } protected static string GYearOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.GYear)).ToString(); } protected static string GYearMonthOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.GYearMonth)).ToString(); } protected static string QNameToString(XmlQualifiedName qname, IXmlNamespaceResolver? nsResolver) { string? prefix; if (nsResolver == null) return $"{{{qname.Namespace}}}{qname.Name}"; prefix = nsResolver.LookupPrefix(qname.Namespace); if (prefix == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoPrefix, qname, qname.Namespace)); return (prefix.Length != 0) ? $"{prefix}:{qname.Name}" : qname.Name; } protected static string TimeToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.Time)).ToString(); } protected static string TimeOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.Time)).ToString(); } protected static string YearMonthDurationToString(TimeSpan value) { return new XsdDuration(value, XsdDuration.DurationType.YearMonthDuration).ToString(XsdDuration.DurationType.YearMonthDuration); } //------------------------------------------------------------------------ // Other Conversion Helpers //------------------------------------------------------------------------ internal static DateTime DateTimeOffsetToDateTime(DateTimeOffset value) { return value.LocalDateTime; } internal static int DecimalToInt32(decimal value) { if (value < (decimal)int.MinValue || value > (decimal)int.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Int32" })); return (int)value; } protected static long DecimalToInt64(decimal value) { if (value < (decimal)long.MinValue || value > (decimal)long.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Int64" })); return (long)value; } protected static ulong DecimalToUInt64(decimal value) { if (value < (decimal)ulong.MinValue || value > (decimal)ulong.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt64" })); return (ulong)value; } protected static byte Int32ToByte(int value) { if (value < (int)byte.MinValue || value > (int)byte.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Byte" })); return (byte)value; } protected static short Int32ToInt16(int value) { if (value < (int)short.MinValue || value > (int)short.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Int16" })); return (short)value; } protected static sbyte Int32ToSByte(int value) { if (value < (int)sbyte.MinValue || value > (int)sbyte.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "SByte" })); return (sbyte)value; } protected static ushort Int32ToUInt16(int value) { if (value < (int)ushort.MinValue || value > (int)ushort.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt16" })); return (ushort)value; } protected static int Int64ToInt32(long value) { if (value < (long)int.MinValue || value > (long)int.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Int32" })); return (int)value; } protected static uint Int64ToUInt32(long value) { if (value < (long)uint.MinValue || value > (long)uint.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt32" })); return (uint)value; } protected static DateTime UntypedAtomicToDateTime(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.AllXsd)); } protected static DateTimeOffset UntypedAtomicToDateTimeOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.AllXsd)); } } internal sealed class XmlNumeric10Converter : XmlBaseConverter { private XmlNumeric10Converter(XmlSchemaType schemaType) : base(schemaType) { } public static XmlValueConverter Create(XmlSchemaType schemaType) { return new XmlNumeric10Converter(schemaType); } #region AUTOGENERATED_XMLNUMERIC10CONVERTER public override decimal ToDecimal(string value!!) { if (TypeCode == XmlTypeCode.Decimal) return XmlConvert.ToDecimal((string)value); return XmlConvert.ToInteger((string)value); } public override decimal ToDecimal(object value!!) { Type sourceType = value.GetType(); if (sourceType == DecimalType) return ((decimal)value); if (sourceType == Int32Type) return ((decimal)(int)value); if (sourceType == Int64Type) return ((decimal)(long)value); if (sourceType == StringType) return this.ToDecimal((string)value); if (sourceType == XmlAtomicValueType) return ((decimal)((XmlAtomicValue)value).ValueAs(DecimalType)); return (decimal)ChangeTypeWildcardDestination(value, DecimalType, null); } public override int ToInt32(long value) { return Int64ToInt32((long)value); } public override int ToInt32(string value!!) { if (TypeCode == XmlTypeCode.Decimal) return DecimalToInt32(XmlConvert.ToDecimal((string)value)); return XmlConvert.ToInt32((string)value); } public override int ToInt32(object value!!) { Type sourceType = value.GetType(); if (sourceType == DecimalType) return DecimalToInt32((decimal)value); if (sourceType == Int32Type) return ((int)value); if (sourceType == Int64Type) return Int64ToInt32((long)value); if (sourceType == StringType) return this.ToInt32((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsInt; return (int)ChangeTypeWildcardDestination(value, Int32Type, null); } public override long ToInt64(int value) { return ((long)(int)value); } public override long ToInt64(string value!!) { if (TypeCode == XmlTypeCode.Decimal) return DecimalToInt64(XmlConvert.ToDecimal((string)value)); return XmlConvert.ToInt64((string)value); } public override long ToInt64(object value!!) { Type sourceType = value.GetType(); if (sourceType == DecimalType) return DecimalToInt64((decimal)value); if (sourceType == Int32Type) return ((long)(int)value); if (sourceType == Int64Type) return ((long)value); if (sourceType == StringType) return this.ToInt64((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsLong; return (long)ChangeTypeWildcardDestination(value, Int64Type, null); } //----------------------------------------------- // ToSingle //----------------------------------------------- // This converter does not support conversions to Single. //----------------------------------------------- // ToString //----------------------------------------------- public override string ToString(decimal value) { if (TypeCode == XmlTypeCode.Decimal) return XmlConvert.ToString((decimal)value); return XmlConvert.ToString(decimal.Truncate((decimal)value)); } public override string ToString(int value) { return XmlConvert.ToString((int)value); } public override string ToString(long value) { return XmlConvert.ToString((long)value); } public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == DecimalType) return this.ToString((decimal)value); if (sourceType == Int32Type) return XmlConvert.ToString((int)value); if (sourceType == Int64Type) return XmlConvert.ToString((long)value); if (sourceType == StringType) return ((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).Value; return (string)ChangeTypeWildcardDestination(value, StringType, nsResolver); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(decimal value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return ((decimal)value); if (destinationType == Int32Type) return DecimalToInt32((decimal)value); if (destinationType == Int64Type) return DecimalToInt64((decimal)value); if (destinationType == StringType) return this.ToString((decimal)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, value)); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(int value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return ((decimal)(int)value); if (destinationType == Int32Type) return ((int)value); if (destinationType == Int64Type) return ((long)(int)value); if (destinationType == StringType) return XmlConvert.ToString((int)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (int)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (int)value)); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(long value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return ((decimal)(long)value); if (destinationType == Int32Type) return Int64ToInt32((long)value); if (destinationType == Int64Type) return ((long)value); if (destinationType == StringType) return XmlConvert.ToString((long)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (long)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (long)value)); return ChangeTypeWildcardSource(value, destinationType!, null); } public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return this.ToDecimal((string)value); if (destinationType == Int32Type) return this.ToInt32((string)value); if (destinationType == Int64Type) return this.ToInt64((string)value); if (destinationType == StringType) return ((string)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (string)value)); return ChangeTypeWildcardSource(value, destinationType, nsResolver); } public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return this.ToDecimal(value); if (destinationType == Int32Type) return this.ToInt32(value); if (destinationType == Int64Type) return this.ToInt64(value); if (destinationType == StringType) return this.ToString(value, nsResolver); if (destinationType == XmlAtomicValueType) { if (sourceType == DecimalType) return (new XmlAtomicValue(SchemaType!, value)); if (sourceType == Int32Type) return (new XmlAtomicValue(SchemaType!, (int)value)); if (sourceType == Int64Type) return (new XmlAtomicValue(SchemaType!, (long)value)); if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == XPathItemType) { if (sourceType == DecimalType) return (new XmlAtomicValue(SchemaType!, value)); if (sourceType == Int32Type) return (new XmlAtomicValue(SchemaType!, (int)value)); if (sourceType == Int64Type) return (new XmlAtomicValue(SchemaType!, (long)value)); if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == ByteType) return Int32ToByte(this.ToInt32(value)); if (destinationType == Int16Type) return Int32ToInt16(this.ToInt32(value)); if (destinationType == SByteType) return Int32ToSByte(this.ToInt32(value)); if (destinationType == UInt16Type) return Int32ToUInt16(this.ToInt32(value)); if (destinationType == UInt32Type) return Int64ToUInt32(this.ToInt64(value)); if (destinationType == UInt64Type) return DecimalToUInt64(this.ToDecimal(value)); if (sourceType == ByteType) return this.ChangeType((int)(byte)value, destinationType); if (sourceType == Int16Type) return this.ChangeType((int)(short)value, destinationType); if (sourceType == SByteType) return this.ChangeType((int)(sbyte)value, destinationType); if (sourceType == UInt16Type) return this.ChangeType((int)(ushort)value, destinationType); if (sourceType == UInt32Type) return this.ChangeType((long)(uint)value, destinationType); if (sourceType == UInt64Type) return this.ChangeType((decimal)(ulong)value, destinationType); return ChangeListType(value, destinationType, nsResolver); } //----------------------------------------------- // Helpers //----------------------------------------------- private object ChangeTypeWildcardDestination(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == ByteType) return this.ChangeType((int)(byte)value, destinationType); if (sourceType == Int16Type) return this.ChangeType((int)(short)value, destinationType); if (sourceType == SByteType) return this.ChangeType((int)(sbyte)value, destinationType); if (sourceType == UInt16Type) return this.ChangeType((int)(ushort)value, destinationType); if (sourceType == UInt32Type) return this.ChangeType((long)(uint)value, destinationType); if (sourceType == UInt64Type) return this.ChangeType((decimal)(ulong)value, destinationType); return ChangeListType(value, destinationType, nsResolver); } private object ChangeTypeWildcardSource(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { if (destinationType == ByteType) return Int32ToByte(this.ToInt32(value)); if (destinationType == Int16Type) return Int32ToInt16(this.ToInt32(value)); if (destinationType == SByteType) return Int32ToSByte(this.ToInt32(value)); if (destinationType == UInt16Type) return Int32ToUInt16(this.ToInt32(value)); if (destinationType == UInt32Type) return Int64ToUInt32(this.ToInt64(value)); if (destinationType == UInt64Type) return DecimalToUInt64(this.ToDecimal(value)); return ChangeListType(value, destinationType, nsResolver); } #endregion } internal sealed class XmlNumeric2Converter : XmlBaseConverter { private XmlNumeric2Converter(XmlSchemaType schemaType) : base(schemaType) { } public static XmlValueConverter Create(XmlSchemaType schemaType) { return new XmlNumeric2Converter(schemaType); } #region AUTOGENERATED_XMLNUMERIC2CONVERTER public override double ToDouble(string value!!) { if (TypeCode == XmlTypeCode.Float) return ((double)XmlConvert.ToSingle((string)value)); return XmlConvert.ToDouble((string)value); } public override double ToDouble(object value!!) { Type sourceType = value.GetType(); if (sourceType == DoubleType) return ((double)value); if (sourceType == SingleType) return ((double)(float)value); if (sourceType == StringType) return this.ToDouble((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsDouble; return (double)ChangeListType(value, DoubleType, null); } //----------------------------------------------- // ToInt32 //----------------------------------------------- // This converter does not support conversions to Int32. //----------------------------------------------- // ToInt64 //----------------------------------------------- // This converter does not support conversions to Int64. //----------------------------------------------- // ToSingle //----------------------------------------------- public override float ToSingle(double value) { return ((float)(double)value); } public override float ToSingle(string value!!) { if (TypeCode == XmlTypeCode.Float) return XmlConvert.ToSingle((string)value); return ((float)XmlConvert.ToDouble((string)value)); } public override float ToSingle(object value!!) { Type sourceType = value.GetType(); if (sourceType == DoubleType) return ((float)(double)value); if (sourceType == SingleType) return ((float)value); if (sourceType == StringType) return this.ToSingle((string)value); if (sourceType == XmlAtomicValueType) return ((float)((XmlAtomicValue)value).ValueAs(SingleType)); return (float)ChangeListType(value, SingleType, null); } //----------------------------------------------- // ToString //----------------------------------------------- public override string ToString(double value) { if (TypeCode == XmlTypeCode.Float) return XmlConvert.ToString(ToSingle((double)value)); return XmlConvert.ToString((double)value); } public override string ToString(float value) { if (TypeCode == XmlTypeCode.Float) return XmlConvert.ToString((float)value); return XmlConvert.ToString((double)(float)value); } public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == DoubleType) return this.ToString((double)value); if (sourceType == SingleType) return this.ToString((float)value); if (sourceType == StringType) return ((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).Value; return (string)ChangeListType(value, StringType, nsResolver); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(double value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DoubleType) return ((double)value); if (destinationType == SingleType) return ((float)(double)value); if (destinationType == StringType) return this.ToString((double)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (double)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (double)value)); return ChangeListType(value, destinationType, null); } public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DoubleType) return this.ToDouble((string)value); if (destinationType == SingleType) return this.ToSingle((string)value); if (destinationType == StringType) return ((string)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (string)value)); return ChangeListType(value, destinationType, nsResolver); } public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DoubleType) return this.ToDouble(value); if (destinationType == SingleType) return this.ToSingle(value); if (destinationType == StringType) return this.ToString(value, nsResolver); if (destinationType == XmlAtomicValueType) { if (sourceType == DoubleType) return (new XmlAtomicValue(SchemaType!, (double)value)); if (sourceType == SingleType) return (new XmlAtomicValue(SchemaType!, value)); if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == XPathItemType) { if (sourceType == DoubleType) return (new XmlAtomicValue(SchemaType!, (double)value)); if (sourceType == SingleType) return (new XmlAtomicValue(SchemaType!, value)); if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } return ChangeListType(value, destinationType, nsResolver); } #endregion } internal sealed class XmlDateTimeConverter : XmlBaseConverter { private XmlDateTimeConverter(XmlSchemaType schemaType) : base(schemaType) { } public static XmlValueConverter Create(XmlSchemaType schemaType) { return new XmlDateTimeConverter(schemaType); } #region AUTOGENERATED_XMLDATETIMECONVERTER public override DateTime ToDateTime(DateTimeOffset value) { return DateTimeOffsetToDateTime(value); } public override DateTime ToDateTime(string value!!) { return TypeCode switch { XmlTypeCode.Date => StringToDate((string)value), XmlTypeCode.Time => StringToTime((string)value), XmlTypeCode.GDay => StringToGDay((string)value), XmlTypeCode.GMonth => StringToGMonth((string)value), XmlTypeCode.GMonthDay => StringToGMonthDay((string)value), XmlTypeCode.GYear => StringToGYear((string)value), XmlTypeCode.GYearMonth => StringToGYearMonth((string)value), _ => StringToDateTime((string)value), }; } public override DateTime ToDateTime(object value!!) { Type sourceType = value.GetType(); if (sourceType == DateTimeType) return ((DateTime)value); if (sourceType == DateTimeOffsetType) return this.ToDateTime((DateTimeOffset)value); if (sourceType == StringType) return this.ToDateTime((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsDateTime; return (DateTime)ChangeListType(value, DateTimeType, null); } //----------------------------------------------- // ToDateTimeOffset //----------------------------------------------- public override DateTimeOffset ToDateTimeOffset(DateTime value) { return new DateTimeOffset(value); } public override DateTimeOffset ToDateTimeOffset(string value!!) { return TypeCode switch { XmlTypeCode.Date => StringToDateOffset((string)value), XmlTypeCode.Time => StringToTimeOffset((string)value), XmlTypeCode.GDay => StringToGDayOffset((string)value), XmlTypeCode.GMonth => StringToGMonthOffset((string)value), XmlTypeCode.GMonthDay => StringToGMonthDayOffset((string)value), XmlTypeCode.GYear => StringToGYearOffset((string)value), XmlTypeCode.GYearMonth => StringToGYearMonthOffset((string)value), _ => StringToDateTimeOffset((string)value), }; } public override DateTimeOffset ToDateTimeOffset(object value!!) { Type sourceType = value.GetType(); if (sourceType == DateTimeType) return ToDateTimeOffset((DateTime)value); if (sourceType == DateTimeOffsetType) return ((DateTimeOffset)value); if (sourceType == StringType) return this.ToDateTimeOffset((string)value); if (sourceType == XmlAtomicValueType) return (DateTimeOffset)((XmlAtomicValue)value).ValueAsDateTime; return (DateTimeOffset)ChangeListType(value, DateTimeOffsetType, null); } //----------------------------------------------- // ToDecimal //----------------------------------------------- // This converter does not support conversions to Decimal. //----------------------------------------------- // ToDouble //----------------------------------------------- // This converter does not support conversions to Double. //----------------------------------------------- // ToInt32 //----------------------------------------------- // This converter does not support conversions to Int32. //----------------------------------------------- // ToInt64 //----------------------------------------------- // This converter does not support conversions to Int64. //----------------------------------------------- // ToSingle //----------------------------------------------- // This converter does not support conversions to Single. //----------------------------------------------- // ToString //----------------------------------------------- public override string ToString(DateTime value) => TypeCode switch { XmlTypeCode.Date => DateToString((DateTime)value), XmlTypeCode.Time => TimeToString((DateTime)value), XmlTypeCode.GDay => GDayToString((DateTime)value), XmlTypeCode.GMonth => GMonthToString((DateTime)value), XmlTypeCode.GMonthDay => GMonthDayToString((DateTime)value), XmlTypeCode.GYear => GYearToString((DateTime)value), XmlTypeCode.GYearMonth => GYearMonthToString((DateTime)value), _ => DateTimeToString((DateTime)value), }; public override string ToString(DateTimeOffset value) => TypeCode switch { XmlTypeCode.Date => DateOffsetToString((DateTimeOffset)value), XmlTypeCode.Time => TimeOffsetToString((DateTimeOffset)value), XmlTypeCode.GDay => GDayOffsetToString((DateTimeOffset)value), XmlTypeCode.GMonth => GMonthOffsetToString((DateTimeOffset)value), XmlTypeCode.GMonthDay => GMonthDayOffsetToString((DateTimeOffset)value), XmlTypeCode.GYear => GYearOffsetToString((DateTimeOffset)value), XmlTypeCode.GYearMonth => GYearMonthOffsetToString((DateTimeOffset)value), _ => DateTimeOffsetToString((DateTimeOffset)value), }; public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == DateTimeType) return this.ToString((DateTime)value); if (sourceType == DateTimeOffsetType) return this.ToString((DateTimeOffset)value); if (sourceType == StringType) return ((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).Value; return (string)ChangeListType(value, StringType, nsResolver); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(DateTime value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DateTimeType) return ((DateTime)value); if (destinationType == DateTimeOffsetType) return this.ToDateTimeOffset((DateTime)value); if (destinationType == StringType) return this.ToString((DateTime)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (DateTime)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (DateTime)value)); return ChangeListType(value, destinationType, null); } public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DateTimeType) return this.ToDateTime((string)value); if (destinationType == DateTimeOffsetType) return this.ToDateTimeOffset((string)value); if (destinationType == StringType) return ((string)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (string)value)); return ChangeListType(value, destinationType, nsResolver); } public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DateTimeType) return this.ToDateTime(value); if (destinationType == DateTimeOffsetType) return this.ToDateTimeOffset(value); if (destinationType == StringType) return this.ToString(value, nsResolver); if (destinationType == XmlAtomicValueType) { if (sourceType == DateTimeType) return (new XmlAtomicValue(SchemaType!, (DateTime)value)); if (sourceType == DateTimeOffsetType) return (new XmlAtomicValue(SchemaType!, (DateTimeOffset)value)); if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == XPathItemType) { if (sourceType == DateTimeType) return (new XmlAtomicValue(SchemaType!, (DateTime)value)); if (sourceType == DateTimeOffsetType) return (new XmlAtomicValue(SchemaType!, (DateTimeOffset)value)); if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } return ChangeListType(value, destinationType, nsResolver); } #endregion } internal sealed class XmlBooleanConverter : XmlBaseConverter { private XmlBooleanConverter(XmlSchemaType schemaType) : base(schemaType) { } public static XmlValueConverter Create(XmlSchemaType schemaType) { return new XmlBooleanConverter(schemaType); } #region AUTOGENERATED_XMLBOOLEANCONVERTER public override bool ToBoolean(string value!!) { return XmlConvert.ToBoolean((string)value); } public override bool ToBoolean(object value!!) { Type sourceType = value.GetType(); if (sourceType == BooleanType) return ((bool)value); if (sourceType == StringType) return XmlConvert.ToBoolean((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsBoolean; return (bool)ChangeListType(value, BooleanType, null); } //----------------------------------------------- // ToDateTime //----------------------------------------------- // This converter does not support conversions to DateTime. //----------------------------------------------- // ToDecimal //----------------------------------------------- // This converter does not support conversions to Decimal. //----------------------------------------------- // ToDouble //----------------------------------------------- // This converter does not support conversions to Double. //----------------------------------------------- // ToInt32 //----------------------------------------------- // This converter does not support conversions to Int32. //----------------------------------------------- // ToInt64 //----------------------------------------------- // This converter does not support conversions to Int64. //----------------------------------------------- // ToSingle //----------------------------------------------- // This converter does not support conversions to Single. //----------------------------------------------- // ToString //----------------------------------------------- public override string ToString(bool value) { return XmlConvert.ToString((bool)value); } public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == BooleanType) return XmlConvert.ToString((bool)value); if (sourceType == StringType) return ((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).Value; return (string)ChangeListType(value, StringType, nsResolver); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(bool value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) return ((bool)value); if (destinationType == StringType) return XmlConvert.ToString((bool)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (bool)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (bool)value)); return ChangeListType(value, destinationType, null); } public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) return XmlConvert.ToBoolean((string)value); if (destinationType == StringType) return ((string)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (string)value)); return ChangeListType(value, destinationType, nsResolver); } public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) return this.ToBoolean(value); if (destinationType == StringType) return this.ToString(value, nsResolver); if (destinationType == XmlAtomicValueType) { if (sourceType == BooleanType) return (new XmlAtomicValue(SchemaType!, (bool)value)); if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == XPathItemType) { if (sourceType == BooleanType) return (new XmlAtomicValue(SchemaType!, (bool)value)); if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } return ChangeListType(value, destinationType, nsResolver); } #endregion } internal sealed class XmlMiscConverter : XmlBaseConverter { private XmlMiscConverter(XmlSchemaType schemaType) : base(schemaType) { } public static XmlValueConverter Create(XmlSchemaType schemaType) { return new XmlMiscConverter(schemaType); } #region AUTOGENERATED_XMLMISCCONVERTER public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == ByteArrayType) { switch (TypeCode) { case XmlTypeCode.Base64Binary: return Base64BinaryToString((byte[])value); case XmlTypeCode.HexBinary: return XmlConvert.ToBinHexString((byte[])value); } } if (sourceType == StringType) return (string)value; if (IsDerivedFrom(sourceType, UriType)) if (TypeCode == XmlTypeCode.AnyUri) return AnyUriToString((Uri)value); if (sourceType == TimeSpanType) { switch (TypeCode) { case XmlTypeCode.DayTimeDuration: return DayTimeDurationToString((TimeSpan)value); case XmlTypeCode.Duration: return DurationToString((TimeSpan)value); case XmlTypeCode.YearMonthDuration: return YearMonthDurationToString((TimeSpan)value); } } if (IsDerivedFrom(sourceType, XmlQualifiedNameType)) { switch (TypeCode) { case XmlTypeCode.Notation: return QNameToString((XmlQualifiedName)value, nsResolver); case XmlTypeCode.QName: return QNameToString((XmlQualifiedName)value, nsResolver); } } return (string)ChangeTypeWildcardDestination(value, StringType, nsResolver); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == ByteArrayType) { switch (TypeCode) { case XmlTypeCode.Base64Binary: return StringToBase64Binary((string)value); case XmlTypeCode.HexBinary: return StringToHexBinary((string)value); } } if (destinationType == XmlQualifiedNameType) { switch (TypeCode) { case XmlTypeCode.Notation: return StringToQName((string)value, nsResolver); case XmlTypeCode.QName: return StringToQName((string)value, nsResolver); } } if (destinationType == StringType) return (string)value; if (destinationType == TimeSpanType) { switch (TypeCode) { case XmlTypeCode.DayTimeDuration: return StringToDayTimeDuration((string)value); case XmlTypeCode.Duration: return StringToDuration((string)value); case XmlTypeCode.YearMonthDuration: return StringToYearMonthDuration((string)value); } } if (destinationType == UriType) if (TypeCode == XmlTypeCode.AnyUri) return XmlConvert.ToUri((string)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (string)value, nsResolver)); return ChangeTypeWildcardSource(value, destinationType, nsResolver); } public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == ByteArrayType) { if (sourceType == ByteArrayType) { switch (TypeCode) { case XmlTypeCode.Base64Binary: return ((byte[])value); case XmlTypeCode.HexBinary: return ((byte[])value); } } if (sourceType == StringType) { switch (TypeCode) { case XmlTypeCode.Base64Binary: return StringToBase64Binary((string)value); case XmlTypeCode.HexBinary: return StringToHexBinary((string)value); } } } if (destinationType == XmlQualifiedNameType) { if (sourceType == StringType) { switch (TypeCode) { case XmlTypeCode.Notation: return StringToQName((string)value, nsResolver); case XmlTypeCode.QName: return StringToQName((string)value, nsResolver); } } if (IsDerivedFrom(sourceType, XmlQualifiedNameType)) { switch (TypeCode) { case XmlTypeCode.Notation: return ((XmlQualifiedName)value); case XmlTypeCode.QName: return ((XmlQualifiedName)value); } } } if (destinationType == StringType) return this.ToString(value, nsResolver); if (destinationType == TimeSpanType) { if (sourceType == StringType) { switch (TypeCode) { case XmlTypeCode.DayTimeDuration: return StringToDayTimeDuration((string)value); case XmlTypeCode.Duration: return StringToDuration((string)value); case XmlTypeCode.YearMonthDuration: return StringToYearMonthDuration((string)value); } } if (sourceType == TimeSpanType) { switch (TypeCode) { case XmlTypeCode.DayTimeDuration: return ((TimeSpan)value); case XmlTypeCode.Duration: return ((TimeSpan)value); case XmlTypeCode.YearMonthDuration: return ((TimeSpan)value); } } } if (destinationType == UriType) { if (sourceType == StringType) if (TypeCode == XmlTypeCode.AnyUri) return XmlConvert.ToUri((string)value); if (IsDerivedFrom(sourceType, UriType)) if (TypeCode == XmlTypeCode.AnyUri) return ((Uri)value); } if (destinationType == XmlAtomicValueType) { if (sourceType == ByteArrayType) { switch (TypeCode) { case XmlTypeCode.Base64Binary: return (new XmlAtomicValue(SchemaType!, value)); case XmlTypeCode.HexBinary: return (new XmlAtomicValue(SchemaType!, value)); } } if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value, nsResolver)); if (sourceType == TimeSpanType) { switch (TypeCode) { case XmlTypeCode.DayTimeDuration: return (new XmlAtomicValue(SchemaType!, value)); case XmlTypeCode.Duration: return (new XmlAtomicValue(SchemaType!, value)); case XmlTypeCode.YearMonthDuration: return (new XmlAtomicValue(SchemaType!, value)); } } if (IsDerivedFrom(sourceType, UriType)) if (TypeCode == XmlTypeCode.AnyUri) return (new XmlAtomicValue(SchemaType!, value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); if (IsDerivedFrom(sourceType, XmlQualifiedNameType)) { switch (TypeCode) { case XmlTypeCode.Notation: return (new XmlAtomicValue(SchemaType!, value, nsResolver)); case XmlTypeCode.QName: return (new XmlAtomicValue(SchemaType!, value, nsResolver)); } } } if (destinationType == XPathItemType) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == XPathItemType) return ((XPathItem)this.ChangeType(value, XmlAtomicValueType, nsResolver)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAs(destinationType, nsResolver); return ChangeListType(value, destinationType, nsResolver); } //----------------------------------------------- // Helpers //----------------------------------------------- private object ChangeTypeWildcardDestination(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAs(destinationType, nsResolver); return ChangeListType(value, destinationType, nsResolver); } private object ChangeTypeWildcardSource(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { if (destinationType == XPathItemType) return ((XPathItem)this.ChangeType(value, XmlAtomicValueType, nsResolver)); return ChangeListType(value, destinationType, nsResolver); } #endregion } internal sealed class XmlStringConverter : XmlBaseConverter { private XmlStringConverter(XmlSchemaType schemaType) : base(schemaType) { } public static XmlValueConverter Create(XmlSchemaType schemaType) { return new XmlStringConverter(schemaType); } #region AUTOGENERATED_XMLSTRINGCONVERTER public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == StringType) return ((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).Value; return (string)ChangeListType(value, StringType, nsResolver); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return ((string)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (string)value)); return ChangeListType(value, destinationType, nsResolver); } public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return this.ToString(value, nsResolver); if (destinationType == XmlAtomicValueType) { if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == XPathItemType) { if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } return ChangeListType(value, destinationType, nsResolver); } #endregion } internal sealed class XmlUntypedConverter : XmlListConverter { private readonly bool _allowListToList; private XmlUntypedConverter() : base(DatatypeImplementation.UntypedAtomicType) { } private XmlUntypedConverter(XmlUntypedConverter atomicConverter, bool allowListToList) : base(atomicConverter, allowListToList ? StringArrayType : StringType) { _allowListToList = allowListToList; } public static readonly XmlValueConverter Untyped = new XmlUntypedConverter(new XmlUntypedConverter(), false); public static readonly XmlValueConverter UntypedList = new XmlUntypedConverter(new XmlUntypedConverter(), true); #region AUTOGENERATED_XMLUNTYPEDCONVERTER //----------------------------------------------- // ToBoolean //----------------------------------------------- public override bool ToBoolean(string value!!) { return XmlConvert.ToBoolean((string)value); } public override bool ToBoolean(object value!!) { Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToBoolean((string)value); return (bool)ChangeTypeWildcardDestination(value, BooleanType, null); } //----------------------------------------------- // ToDateTime //----------------------------------------------- public override DateTime ToDateTime(string value!!) { return UntypedAtomicToDateTime((string)value); } public override DateTime ToDateTime(object value!!) { Type sourceType = value.GetType(); if (sourceType == StringType) return UntypedAtomicToDateTime((string)value); return (DateTime)ChangeTypeWildcardDestination(value, DateTimeType, null); } //----------------------------------------------- // ToDateTimeOffset //----------------------------------------------- public override DateTimeOffset ToDateTimeOffset(string value!!) { return UntypedAtomicToDateTimeOffset((string)value); } public override DateTimeOffset ToDateTimeOffset(object value!!) { Type sourceType = value.GetType(); if (sourceType == StringType) return UntypedAtomicToDateTimeOffset((string)value); return (DateTimeOffset)ChangeTypeWildcardDestination(value, DateTimeOffsetType, null); } //----------------------------------------------- // ToDecimal //----------------------------------------------- public override decimal ToDecimal(string value!!) { return XmlConvert.ToDecimal((string)value); } public override decimal ToDecimal(object value!!) { Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToDecimal((string)value); return (decimal)ChangeTypeWildcardDestination(value, DecimalType, null); } //----------------------------------------------- // ToDouble //----------------------------------------------- public override double ToDouble(string value!!) { return XmlConvert.ToDouble((string)value); } public override double ToDouble(object value!!) { Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToDouble((string)value); return (double)ChangeTypeWildcardDestination(value, DoubleType, null); } //----------------------------------------------- // ToInt32 //----------------------------------------------- public override int ToInt32(string value!!) { return XmlConvert.ToInt32((string)value); } public override int ToInt32(object value!!) { Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToInt32((string)value); return (int)ChangeTypeWildcardDestination(value, Int32Type, null); } //----------------------------------------------- // ToInt64 //----------------------------------------------- public override long ToInt64(string value!!) { return XmlConvert.ToInt64((string)value); } public override long ToInt64(object value!!) { Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToInt64((string)value); return (long)ChangeTypeWildcardDestination(value, Int64Type, null); } //----------------------------------------------- // ToSingle //----------------------------------------------- public override float ToSingle(string value!!) { return XmlConvert.ToSingle((string)value); } public override float ToSingle(object value!!) { Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToSingle((string)value); return (float)ChangeTypeWildcardDestination(value, SingleType, null); } //----------------------------------------------- // ToString //----------------------------------------------- public override string ToString(bool value) { return XmlConvert.ToString((bool)value); } public override string ToString(DateTime value) { return DateTimeToString((DateTime)value); } public override string ToString(DateTimeOffset value) { return DateTimeOffsetToString((DateTimeOffset)value); } public override string ToString(decimal value) { return XmlConvert.ToString((decimal)value); } public override string ToString(double value) { return XmlConvert.ToString((double)value); } public override string ToString(int value) { return XmlConvert.ToString((int)value); } public override string ToString(long value) { return XmlConvert.ToString((long)value); } public override string ToString(float value) { return XmlConvert.ToString((float)value); } public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == BooleanType) return XmlConvert.ToString((bool)value); if (sourceType == ByteType) return XmlConvert.ToString((byte)value); if (sourceType == ByteArrayType) return Base64BinaryToString((byte[])value); if (sourceType == DateTimeType) return DateTimeToString((DateTime)value); if (sourceType == DateTimeOffsetType) return DateTimeOffsetToString((DateTimeOffset)value); if (sourceType == DecimalType) return XmlConvert.ToString((decimal)value); if (sourceType == DoubleType) return XmlConvert.ToString((double)value); if (sourceType == Int16Type) return XmlConvert.ToString((short)value); if (sourceType == Int32Type) return XmlConvert.ToString((int)value); if (sourceType == Int64Type) return XmlConvert.ToString((long)value); if (sourceType == SByteType) return XmlConvert.ToString((sbyte)value); if (sourceType == SingleType) return XmlConvert.ToString((float)value); if (sourceType == StringType) return ((string)value); if (sourceType == TimeSpanType) return DurationToString((TimeSpan)value); if (sourceType == UInt16Type) return XmlConvert.ToString((ushort)value); if (sourceType == UInt32Type) return XmlConvert.ToString((uint)value); if (sourceType == UInt64Type) return XmlConvert.ToString((ulong)value); if (IsDerivedFrom(sourceType, UriType)) return AnyUriToString((Uri)value); if (sourceType == XmlAtomicValueType) return ((string)((XmlAtomicValue)value).ValueAs(StringType, nsResolver)); if (IsDerivedFrom(sourceType, XmlQualifiedNameType)) return QNameToString((XmlQualifiedName)value, nsResolver); return (string)ChangeTypeWildcardDestination(value, StringType, nsResolver); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(bool value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((bool)value); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(DateTime value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return DateTimeToString((DateTime)value); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(decimal value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((decimal)value); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(double value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((double)value); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(int value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((int)value); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(long value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((long)value); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) return XmlConvert.ToBoolean((string)value); if (destinationType == ByteType) return Int32ToByte(XmlConvert.ToInt32((string)value)); if (destinationType == ByteArrayType) return StringToBase64Binary((string)value); if (destinationType == DateTimeType) return UntypedAtomicToDateTime((string)value); if (destinationType == DateTimeOffsetType) return UntypedAtomicToDateTimeOffset((string)value); if (destinationType == DecimalType) return XmlConvert.ToDecimal((string)value); if (destinationType == DoubleType) return XmlConvert.ToDouble((string)value); if (destinationType == Int16Type) return Int32ToInt16(XmlConvert.ToInt32((string)value)); if (destinationType == Int32Type) return XmlConvert.ToInt32((string)value); if (destinationType == Int64Type) return XmlConvert.ToInt64((string)value); if (destinationType == SByteType) return Int32ToSByte(XmlConvert.ToInt32((string)value)); if (destinationType == SingleType) return XmlConvert.ToSingle((string)value); if (destinationType == TimeSpanType) return StringToDuration((string)value); if (destinationType == UInt16Type) return Int32ToUInt16(XmlConvert.ToInt32((string)value)); if (destinationType == UInt32Type) return Int64ToUInt32(XmlConvert.ToInt64((string)value)); if (destinationType == UInt64Type) return DecimalToUInt64(XmlConvert.ToDecimal((string)value)); if (destinationType == UriType) return XmlConvert.ToUri((string)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (destinationType == XmlQualifiedNameType) return StringToQName((string)value, nsResolver); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (destinationType == StringType) return ((string)value); return ChangeTypeWildcardSource(value, destinationType, nsResolver); } public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) { if (sourceType == StringType) return XmlConvert.ToBoolean((string)value); } if (destinationType == ByteType) { if (sourceType == StringType) return Int32ToByte(XmlConvert.ToInt32((string)value)); } if (destinationType == ByteArrayType) { if (sourceType == StringType) return StringToBase64Binary((string)value); } if (destinationType == DateTimeType) { if (sourceType == StringType) return UntypedAtomicToDateTime((string)value); } if (destinationType == DateTimeOffsetType) { if (sourceType == StringType) return UntypedAtomicToDateTimeOffset((string)value); } if (destinationType == DecimalType) { if (sourceType == StringType) return XmlConvert.ToDecimal((string)value); } if (destinationType == DoubleType) { if (sourceType == StringType) return XmlConvert.ToDouble((string)value); } if (destinationType == Int16Type) { if (sourceType == StringType) return Int32ToInt16(XmlConvert.ToInt32((string)value)); } if (destinationType == Int32Type) { if (sourceType == StringType) return XmlConvert.ToInt32((string)value); } if (destinationType == Int64Type) { if (sourceType == StringType) return XmlConvert.ToInt64((string)value); } if (destinationType == SByteType) { if (sourceType == StringType) return Int32ToSByte(XmlConvert.ToInt32((string)value)); } if (destinationType == SingleType) { if (sourceType == StringType) return XmlConvert.ToSingle((string)value); } if (destinationType == TimeSpanType) { if (sourceType == StringType) return StringToDuration((string)value); } if (destinationType == UInt16Type) { if (sourceType == StringType) return Int32ToUInt16(XmlConvert.ToInt32((string)value)); } if (destinationType == UInt32Type) { if (sourceType == StringType) return Int64ToUInt32(XmlConvert.ToInt64((string)value)); } if (destinationType == UInt64Type) { if (sourceType == StringType) return DecimalToUInt64(XmlConvert.ToDecimal((string)value)); } if (destinationType == UriType) { if (sourceType == StringType) return XmlConvert.ToUri((string)value); } if (destinationType == XmlAtomicValueType) { if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == XmlQualifiedNameType) { if (sourceType == StringType) return StringToQName((string)value, nsResolver); } if (destinationType == XPathItemType) { if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == StringType) return this.ToString(value, nsResolver); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, this.ToString(value, nsResolver))); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, this.ToString(value, nsResolver))); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAs(destinationType, nsResolver); return ChangeListType(value, destinationType, nsResolver); } //----------------------------------------------- // Helpers //----------------------------------------------- private object ChangeTypeWildcardDestination(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAs(destinationType, nsResolver); return ChangeListType(value, destinationType, nsResolver); } private object ChangeTypeWildcardSource(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, this.ToString(value, nsResolver))); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, this.ToString(value, nsResolver))); return ChangeListType(value, destinationType, nsResolver); } #endregion //----------------------------------------------- // Helpers //----------------------------------------------- protected override object ChangeListType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); // 1. If there is no nested atomic converter, then do not support lists at all // 2. If list to list conversions are not allowed, only allow string => list and list => string if ((this.atomicConverter == null) || (!_allowListToList && sourceType != StringType && destinationType != StringType)) { if (SupportsType(sourceType)) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeToString, XmlTypeName, sourceType.Name)); if (SupportsType(destinationType)) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeFromString, XmlTypeName, destinationType.Name)); throw CreateInvalidClrMappingException(sourceType, destinationType); } return base.ChangeListType(value, destinationType, nsResolver); } private bool SupportsType(Type clrType) { if (clrType == BooleanType) return true; if (clrType == ByteType) return true; if (clrType == ByteArrayType) return true; if (clrType == DateTimeType) return true; if (clrType == DateTimeOffsetType) return true; if (clrType == DecimalType) return true; if (clrType == DoubleType) return true; if (clrType == Int16Type) return true; if (clrType == Int32Type) return true; if (clrType == Int64Type) return true; if (clrType == SByteType) return true; if (clrType == SingleType) return true; if (clrType == TimeSpanType) return true; if (clrType == UInt16Type) return true; if (clrType == UInt32Type) return true; if (clrType == UInt64Type) return true; if (clrType == UriType) return true; if (clrType == XmlQualifiedNameType) return true; return false; } } internal sealed class XmlAnyConverter : XmlBaseConverter { private XmlAnyConverter(XmlTypeCode typeCode) : base(typeCode) { } public static readonly XmlValueConverter Item = new XmlAnyConverter(XmlTypeCode.Item); public static readonly XmlValueConverter AnyAtomic = new XmlAnyConverter(XmlTypeCode.AnyAtomicType); #region AUTOGENERATED_XMLANYCONVERTER //----------------------------------------------- // ToBoolean //----------------------------------------------- public override bool ToBoolean(object value!!) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsBoolean; return (bool)ChangeTypeWildcardDestination(value, BooleanType, null); } //----------------------------------------------- // ToDateTime //----------------------------------------------- public override DateTime ToDateTime(object value!!) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsDateTime; return (DateTime)ChangeTypeWildcardDestination(value, DateTimeType, null); } //----------------------------------------------- // ToDateTimeOffset //----------------------------------------------- public override DateTimeOffset ToDateTimeOffset(object value!!) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return (DateTimeOffset)((XmlAtomicValue)value).ValueAs(DateTimeOffsetType); return (DateTimeOffset)ChangeTypeWildcardDestination(value, DateTimeOffsetType, null); } //----------------------------------------------- // ToDecimal //----------------------------------------------- public override decimal ToDecimal(object value!!) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((decimal)((XmlAtomicValue)value).ValueAs(DecimalType)); return (decimal)ChangeTypeWildcardDestination(value, DecimalType, null); } //----------------------------------------------- // ToDouble //----------------------------------------------- public override double ToDouble(object value!!) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsDouble; return (double)ChangeTypeWildcardDestination(value, DoubleType, null); } //----------------------------------------------- // ToInt32 //----------------------------------------------- public override int ToInt32(object value!!) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsInt; return (int)ChangeTypeWildcardDestination(value, Int32Type, null); } //----------------------------------------------- // ToInt64 //----------------------------------------------- public override long ToInt64(object value!!) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsLong; return (long)ChangeTypeWildcardDestination(value, Int64Type, null); } //----------------------------------------------- // ToSingle //----------------------------------------------- public override float ToSingle(object value!!) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((float)((XmlAtomicValue)value).ValueAs(SingleType)); return (float)ChangeTypeWildcardDestination(value, SingleType, null); } //----------------------------------------------- // ToString //----------------------------------------------- // This converter does not support conversions to String. //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(bool value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Boolean), (bool)value)); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(DateTime value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime), (DateTime)value)); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(decimal value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal), value)); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(double value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Double), (double)value)); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(int value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Int), (int)value)); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(long value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Long), (long)value)); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), (string)value)); return ChangeTypeWildcardSource(value, destinationType, nsResolver); } public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsBoolean; } if (destinationType == DateTimeType) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsDateTime; } if (destinationType == DateTimeOffsetType) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAs(DateTimeOffsetType); } if (destinationType == DecimalType) { if (sourceType == XmlAtomicValueType) return ((decimal)((XmlAtomicValue)value).ValueAs(DecimalType)); } if (destinationType == DoubleType) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsDouble; } if (destinationType == Int32Type) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsInt; } if (destinationType == Int64Type) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsLong; } if (destinationType == SingleType) { if (sourceType == XmlAtomicValueType) return ((float)((XmlAtomicValue)value).ValueAs(SingleType)); } if (destinationType == XmlAtomicValueType) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); if (sourceType == BooleanType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Boolean), (bool)value)); if (sourceType == ByteType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.UnsignedByte), value)); if (sourceType == ByteArrayType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Base64Binary), value)); if (sourceType == DateTimeType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime), (DateTime)value)); if (sourceType == DateTimeOffsetType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime), (DateTimeOffset)value)); if (sourceType == DecimalType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal), value)); if (sourceType == DoubleType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Double), (double)value)); if (sourceType == Int16Type) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Short), value)); if (sourceType == Int32Type) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Int), (int)value)); if (sourceType == Int64Type) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Long), (long)value)); if (sourceType == SByteType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Byte), value)); if (sourceType == SingleType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Float), value)); if (sourceType == StringType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), (string)value)); if (sourceType == TimeSpanType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Duration), value)); if (sourceType == UInt16Type) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.UnsignedShort), value)); if (sourceType == UInt32Type) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.UnsignedInt), value)); if (sourceType == UInt64Type) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.UnsignedLong), value)); if (IsDerivedFrom(sourceType, UriType)) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.AnyUri), value)); if (IsDerivedFrom(sourceType, XmlQualifiedNameType)) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.QName), value, nsResolver)); } if (destinationType == XPathItemType) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); if (IsDerivedFrom(sourceType, XPathNavigatorType)) return ((XPathNavigator)value); } if (destinationType == XPathNavigatorType) { if (IsDerivedFrom(sourceType, XPathNavigatorType)) return ToNavigator((XPathNavigator)value); } if (destinationType == XPathItemType) return ((XPathItem)this.ChangeType(value, XmlAtomicValueType, nsResolver)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAs(destinationType, nsResolver); return ChangeListType(value, destinationType, nsResolver); } //----------------------------------------------- // Helpers //----------------------------------------------- private object ChangeTypeWildcardDestination(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAs(destinationType, nsResolver); return ChangeListType(value, destinationType, nsResolver); } private object ChangeTypeWildcardSource(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { if (destinationType == XPathItemType) return ((XPathItem)this.ChangeType(value, XmlAtomicValueType, nsResolver)); return ChangeListType(value, destinationType, nsResolver); } #endregion /// <summary> /// Throw an exception if nodes are not allowed by this converter. /// </summary> private XPathNavigator ToNavigator(XPathNavigator nav) { if (TypeCode != XmlTypeCode.Item) throw CreateInvalidClrMappingException(XPathNavigatorType, XPathNavigatorType); return nav; } } internal sealed class XmlAnyListConverter : XmlListConverter { private XmlAnyListConverter(XmlBaseConverter atomicConverter) : base(atomicConverter) { } public static readonly XmlValueConverter ItemList = new XmlAnyListConverter((XmlBaseConverter)XmlAnyConverter.Item); public static readonly XmlValueConverter AnyAtomicList = new XmlAnyListConverter((XmlBaseConverter)XmlAnyConverter.AnyAtomic); //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { // If source value does not implement IEnumerable, or it is a string or byte[], if (!(value is IEnumerable) || value.GetType() == StringType || value.GetType() == ByteArrayType) { // Then create a list from it value = new object[] { value }; } return ChangeListType(value, destinationType, nsResolver); } } internal class XmlListConverter : XmlBaseConverter { protected XmlValueConverter? atomicConverter; protected XmlListConverter(XmlBaseConverter atomicConverter) : base(atomicConverter) { this.atomicConverter = atomicConverter; } protected XmlListConverter(XmlBaseConverter atomicConverter, Type clrTypeDefault) : base(atomicConverter, clrTypeDefault) { this.atomicConverter = atomicConverter; } protected XmlListConverter(XmlSchemaType schemaType) : base(schemaType) { } public static XmlValueConverter Create(XmlValueConverter atomicConverter) { if (atomicConverter == XmlUntypedConverter.Untyped) return XmlUntypedConverter.UntypedList; if (atomicConverter == XmlAnyConverter.Item) return XmlAnyListConverter.ItemList; if (atomicConverter == XmlAnyConverter.AnyAtomic) return XmlAnyListConverter.AnyAtomicList; Debug.Assert(!(atomicConverter is XmlListConverter) || ((XmlListConverter)atomicConverter).atomicConverter == null, "List converters should not be nested within one another."); return new XmlListConverter((XmlBaseConverter)atomicConverter); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { return ChangeListType(value, destinationType, nsResolver); } //------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------ protected override object ChangeListType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; // Input value must support IEnumerable and destination type should be IEnumerable, ICollection, IList, Type[], or String if (!(value is IEnumerable) || !IsListType(destinationType)) throw CreateInvalidClrMappingException(sourceType, destinationType); // Handle case where destination type is a string if (destinationType == StringType) { // Conversion from string to string is a no-op if (sourceType == StringType) return value; // Convert from list to string return ListAsString((IEnumerable)value, nsResolver); } // Handle case where source type is a string // Tokenize string and create a list out of resulting string tokens if (sourceType == StringType) value = StringAsList((string)value); if (destinationType.IsArray) { // Convert from source value to strongly-typed array; special-case each possible item type for performance Type? itemTypeDst = destinationType.GetElementType(); // Converting from object[] to object[] is not necessarily a no-op (i.e. xs:int* stored as an object[] // containing String values will need to be converted to an object[] containing Int32 values). if (itemTypeDst == ObjectType) return ToArray<object>(value, nsResolver); // For all types except object[], sourceType = destinationType is a no-op conversion if (sourceType == destinationType) return value; // Otherwise, iterate over values in source list, convert them to output item type, and store them in result array if (itemTypeDst == BooleanType) return ToArray<bool>(value, nsResolver); if (itemTypeDst == ByteType) return ToArray<byte>(value, nsResolver); if (itemTypeDst == ByteArrayType) return ToArray<byte[]>(value, nsResolver); if (itemTypeDst == DateTimeType) return ToArray<DateTime>(value, nsResolver); if (itemTypeDst == DateTimeOffsetType) return ToArray<DateTimeOffset>(value, nsResolver); if (itemTypeDst == DecimalType) return ToArray<decimal>(value, nsResolver); if (itemTypeDst == DoubleType) return ToArray<double>(value, nsResolver); if (itemTypeDst == Int16Type) return ToArray<short>(value, nsResolver); if (itemTypeDst == Int32Type) return ToArray<int>(value, nsResolver); if (itemTypeDst == Int64Type) return ToArray<long>(value, nsResolver); if (itemTypeDst == SByteType) return ToArray<sbyte>(value, nsResolver); if (itemTypeDst == SingleType) return ToArray<float>(value, nsResolver); if (itemTypeDst == StringType) return ToArray<string>(value, nsResolver); if (itemTypeDst == TimeSpanType) return ToArray<TimeSpan>(value, nsResolver); if (itemTypeDst == UInt16Type) return ToArray<ushort>(value, nsResolver); if (itemTypeDst == UInt32Type) return ToArray<uint>(value, nsResolver); if (itemTypeDst == UInt64Type) return ToArray<ulong>(value, nsResolver); if (itemTypeDst == UriType) return ToArray<Uri>(value, nsResolver); if (itemTypeDst == XmlAtomicValueType) return ToArray<XmlAtomicValue>(value, nsResolver); if (itemTypeDst == XmlQualifiedNameType) return ToArray<XmlQualifiedName>(value, nsResolver); if (itemTypeDst == XPathItemType) return ToArray<XPathItem>(value, nsResolver); if (itemTypeDst == XPathNavigatorType) return ToArray<XPathNavigator>(value, nsResolver); throw CreateInvalidClrMappingException(sourceType, destinationType); } // Destination type is IList, ICollection or IEnumerable // If source value is an array of values having the default representation, then conversion is a no-op if (sourceType == DefaultClrType && sourceType != ObjectArrayType) return value; return ToList(value, nsResolver); } /// <summary> /// Return true if "type" is one of the following: /// 1. IList, ICollection, IEnumerable /// 2. A strongly-typed array /// 3. A string /// </summary> private bool IsListType(Type type) { // IsClrListType returns true if "type" is one of the list interfaces if (type == IListType || type == ICollectionType || type == IEnumerableType || type == StringType) return true; return type.IsArray; } /// <summary> /// Convert "list" to an array of type T by iterating over each item in "list" and converting it to type "T" /// by invoking the atomic converter. /// </summary> private T[] ToArray<T>(object list, IXmlNamespaceResolver? nsResolver) { // IList --> Array<T> IList? listSrc = list as IList; if (listSrc != null) { T[] arrDst = new T[listSrc.Count]; for (int i = 0; i < listSrc.Count; i++) arrDst[i] = (T)this.atomicConverter!.ChangeType(listSrc[i]!, typeof(T), nsResolver); return arrDst; } // IEnumerable --> Array<T> IEnumerable enumSrc = (list as IEnumerable)!; Debug.Assert(enumSrc != null, "Value passed to ToArray must implement IEnumerable"); List<T> listDst = new List<T>(); foreach (object? value in enumSrc) listDst.Add((T)this.atomicConverter!.ChangeType(value!, typeof(T), nsResolver)); return listDst.ToArray(); } /// <summary> /// Convert "list" to an IList containing items in the atomic type's default representation. /// </summary> private IList ToList(object list, IXmlNamespaceResolver? nsResolver) { // IList --> object[] IList? listSrc = list as IList; if (listSrc != null) { object[] arrDst = new object[listSrc.Count]; for (int i = 0; i < listSrc.Count; i++) arrDst[i] = this.atomicConverter!.ChangeType(listSrc[i]!, ObjectType, nsResolver); return arrDst; } // IEnumerable --> List<object> IEnumerable enumSrc = (list as IEnumerable)!; Debug.Assert(enumSrc != null, "Value passed to ToArray must implement IEnumerable"); List<object> listDst = new List<object>(); foreach (object? value in enumSrc) listDst.Add(this.atomicConverter!.ChangeType(value!, ObjectType, nsResolver)); return listDst; } /// <summary> /// Tokenize "value" by splitting it on whitespace characters. Insert tokens into an ArrayList and return the list. /// </summary> private List<string> StringAsList(string value) { return new List<string>(XmlConvert.SplitString(value)); } /// <summary> /// Convert a list to a corresponding list of strings. Then concatenate the strings, which adjacent values delimited /// by a space character. /// </summary> private string ListAsString(IEnumerable list, IXmlNamespaceResolver? nsResolver) { StringBuilder bldr = new StringBuilder(); foreach (object? value in list) { // skip null values if (value != null) { // Separate values by single space character if (bldr.Length != 0) bldr.Append(' '); // Append string value of next item in the list bldr.Append(this.atomicConverter!.ToString(value, nsResolver)); } } return bldr.ToString(); } /// <summary> /// Create an InvalidCastException for cases where either "destinationType" or "sourceType" is not a supported CLR representation /// for this Xml type. /// </summary> private new Exception CreateInvalidClrMappingException(Type sourceType, Type destinationType) { if (sourceType == destinationType) return new InvalidCastException(SR.Format(SR.XmlConvert_TypeListBadMapping, XmlTypeName, sourceType.Name)); return new InvalidCastException(SR.Format(SR.XmlConvert_TypeListBadMapping2, XmlTypeName, sourceType.Name, destinationType.Name)); } } internal sealed class XmlUnionConverter : XmlBaseConverter { private readonly XmlValueConverter[] _converters; private readonly bool _hasAtomicMember, _hasListMember; private XmlUnionConverter(XmlSchemaType schemaType) : base(schemaType) { // Skip restrictions. It is safe to do that because this is a union, so it's not a built-in type while (schemaType.DerivedBy == XmlSchemaDerivationMethod.Restriction) schemaType = schemaType.BaseXmlSchemaType!; // Get a converter for each member type in the union Debug.Assert(schemaType.DerivedBy == XmlSchemaDerivationMethod.Union); XmlSchemaSimpleType[] memberTypes = ((XmlSchemaSimpleTypeUnion)((XmlSchemaSimpleType)schemaType).Content!).BaseMemberTypes!; _converters = new XmlValueConverter[memberTypes.Length]; for (int i = 0; i < memberTypes.Length; i++) { _converters[i] = memberTypes[i].ValueConverter; // Track whether this union's member types include a list type if (memberTypes[i].Datatype!.Variety == XmlSchemaDatatypeVariety.List) _hasListMember = true; else if (memberTypes[i].Datatype!.Variety == XmlSchemaDatatypeVariety.Atomic) _hasAtomicMember = true; } } public static XmlValueConverter Create(XmlSchemaType schemaType) { return new XmlUnionConverter(schemaType); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); // If source value is an XmlAtomicValue, then allow it to perform the conversion if (sourceType == XmlAtomicValueType && _hasAtomicMember) return ((XmlAtomicValue)value).ValueAs(destinationType, nsResolver); // If source value is an XmlAtomicValue[], then use item* converter if (sourceType == XmlAtomicValueArrayType && _hasListMember) return XmlAnyListConverter.ItemList.ChangeType(value, destinationType, nsResolver); // If source value is a string, then validate the string in order to determine the member type if (sourceType == StringType) { if (destinationType == StringType) return value; XsdSimpleValue simpleValue = (XsdSimpleValue)SchemaType!.Datatype!.ParseValue((string)value, new NameTable(), nsResolver, true); // Allow the member type to perform the conversion return simpleValue.XmlType.ValueConverter.ChangeType((string)value, destinationType, nsResolver); } throw CreateInvalidClrMappingException(sourceType, destinationType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Xml; using System.Xml.XPath; using System.Globalization; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Xml.Schema; using System.IO; using System.Text; using System.Runtime.InteropServices; using System.Reflection; namespace System.Xml.Schema { // // NOTE!!! LARGE PORTIONS OF THIS FILE ARE AUTOGENERATED BY GENERATECONVERTER.CS. DO NOT MANUALLY CHANGE ANY CODE // WITHIN #REGION. INSTEAD, MODIFY GENERATECONVERTER.CS. // // SUMMARY // ======= // For each Xml type, there is a set of Clr types that can represent it. Some of these mappings involve // loss of fidelity. For example, xsd:dateTime can be represented as System.DateTime, but only at the expense // of normalizing the time zone. And xs:duration can be represented as System.TimeSpan, but only at the expense // of discarding variations such as "P50H", "P1D26H", "P2D2H", all of which are normalized as "P2D2H". // // Implementations of this class convert between the various Clr representations of Xml types. Note that // in *no* case is the Xml type ever modified. Only the Clr type is changed. This means that in cases where // the Xml type is part of the representation (such as XmlAtomicValue), the destination value is guaranteed // to have the same Xml type. // // For all converters, converting to typeof(object) is identical to converting to XmlSchemaType.Datatype.ValueType. // // // ATOMIC MAPPINGS // =============== // // ----------------------------------------------------------------------------------------------------------- // Source/Destination System.String Other Clr Type // ----------------------------------------------------------------------------------------------------------- // System.String No-op conversion. Use Xsd rules to convert from the string // to primitive, full-fidelity Clr type (use // XmlConvert where possible). Use Clr rules // to convert to destination type. // ----------------------------------------------------------------------------------------------------------- // Other Clr Type Use Clr rules to convert from Use Clr rules to convert from source to // source type to primitive, full- destination type. // fidelity Clr type. Use Xsd rules // to convert to a string (use // XmlConvert where possible). // ----------------------------------------------------------------------------------------------------------- // // // LIST MAPPINGS // ============= // The following Clr types can be used to represent Xsd list types: IList, ICollection, IEnumerable, Type[], // String. // // ----------------------------------------------------------------------------------------------------------- // Source/Destination System.String Clr List Type // ----------------------------------------------------------------------------------------------------------- // System.String No-op conversion Tokenize the string by whitespace, create a // String[] from tokens, and follow List => List // rules. // ----------------------------------------------------------------------------------------------------------- // Clr List Type Follow List => String[] rules, Create destination list having the same length // then concatenate strings from array, as the source list. For each item in the // separating adjacent strings with a source list, call the atomic converter to // single space character. convert to the destination type. The destination // item type for IList, ICollection, IEnumerable // is typeof(object). The destination item type // for Type[] is Type. // ----------------------------------------------------------------------------------------------------------- // // // UNION MAPPINGS // ============== // Union types may only be represented using System.Xml.Schema.XmlAtomicValue or System.String. Either the // source type or the destination type must therefore always be either System.String or // System.Xml.Schema.XmlAtomicValue. // // ----------------------------------------------------------------------------------------------------------- // Source/Destination System.String XmlAtomicValue Other Clr Type // ----------------------------------------------------------------------------------------------------------- // System.String No-op conversion Follow System.String=> Call ParseValue in order to determine // Other Clr Type rules. the member type. Call ChangeType on // the member type's converter to convert // to desired Clr type. // ----------------------------------------------------------------------------------------------------------- // XmlAtomicValue Follow XmlAtomicValue No-op conversion. Call ReadValueAs, where destinationType // => Other Clr Type is the desired Clr type. // rules. // ----------------------------------------------------------------------------------------------------------- // Other Clr Type InvalidCastException InvalidCastException InvalidCastException // ----------------------------------------------------------------------------------------------------------- // // // EXAMPLES // ======== // // ----------------------------------------------------------------------------------------------------------- // Source Destination // Xml Type Value Type Conversion Steps Explanation // ----------------------------------------------------------------------------------------------------------- // xs:int "10" Byte "10" => 10M => (byte) 10 Primitive, full-fidelity for xs:int // is a truncated decimal // ----------------------------------------------------------------------------------------------------------- // xs:int "10.10" Byte FormatException xs:integer parsing rules do not // allow fractional parts // ----------------------------------------------------------------------------------------------------------- // xs:int 10.10M Byte 10.10M => (byte) 10 Default Clr rules truncate when // converting from Decimal to Byte // ----------------------------------------------------------------------------------------------------------- // xs:int 10.10M Decimal 10.10M => 10.10M Decimal => Decimal is no-op // ----------------------------------------------------------------------------------------------------------- // xs:int 10.10M String 10.10M => 10M => "10" // ----------------------------------------------------------------------------------------------------------- // xs:int "hello" String "hello" => "hello" String => String is no-op // ----------------------------------------------------------------------------------------------------------- // xs:byte "300" Int32 "300" => 300M => (int) 300 // ----------------------------------------------------------------------------------------------------------- // xs:byte 300 Byte 300 => 300M => OverflowException Clr overflows when converting from // Decimal to Byte // ----------------------------------------------------------------------------------------------------------- // xs:byte 300 XmlAtomicValue new XmlAtomicValue(xs:byte, 300) Invalid atomic value created // ----------------------------------------------------------------------------------------------------------- // xs:double 1.234f String 1.234f => 1.2339999675750732d => Converting a Single value to a Double // "1.2339999675750732" value zero-extends it in base-2, so // "garbage" digits appear when it's // converted to base-10. // ----------------------------------------------------------------------------------------------------------- // xs:int* {1, "2", String {1, "2", 3.1M} => Delegate to xs:int converter to // 3.1M} {"1", "2", "3"} => "1 2 3" convert each item to a string. // ----------------------------------------------------------------------------------------------------------- // xs:int* "1 2 3" Int32[] "1 2 3" => {"1", "2", "3"} => // {1, 2, 3} // ----------------------------------------------------------------------------------------------------------- // xs:int* {1, "2", Object[] {1, "2", 3.1M} => xs:int converter uses Int32 by default, // 3.1M} {(object)1, (object)2, (object)3} so returns boxed Int32 values. // ----------------------------------------------------------------------------------------------------------- // (xs:int | "1 2001" XmlAtomicValue[] "1 2001" => {(xs:int) 1, // xs:gYear)* (xs:gYear) 2001} // ----------------------------------------------------------------------------------------------------------- // (xs:int* | "1 2001" String "1 2001" No-op conversion even though // xs:gYear*) ParseValue would fail if it were called. // ----------------------------------------------------------------------------------------------------------- // (xs:int* | "1 2001" Int[] XmlSchemaException ParseValue fails. // xs:gYear*) // ----------------------------------------------------------------------------------------------------------- // internal abstract class XmlValueConverter { public abstract bool ToBoolean(long value); public abstract bool ToBoolean(int value); public abstract bool ToBoolean(double value); public abstract bool ToBoolean(DateTime value); public abstract bool ToBoolean(string value); public abstract bool ToBoolean(object value); public abstract int ToInt32(bool value); public abstract int ToInt32(long value); public abstract int ToInt32(double value); public abstract int ToInt32(DateTime value); public abstract int ToInt32(string value); public abstract int ToInt32(object value); public abstract long ToInt64(bool value); public abstract long ToInt64(int value); public abstract long ToInt64(double value); public abstract long ToInt64(DateTime value); public abstract long ToInt64(string value); public abstract long ToInt64(object value); public abstract decimal ToDecimal(string value); public abstract decimal ToDecimal(object value); public abstract double ToDouble(bool value); public abstract double ToDouble(int value); public abstract double ToDouble(long value); public abstract double ToDouble(DateTime value); public abstract double ToDouble(string value); public abstract double ToDouble(object value); public abstract float ToSingle(double value); public abstract float ToSingle(string value); public abstract float ToSingle(object value); public abstract DateTime ToDateTime(bool value); public abstract DateTime ToDateTime(int value); public abstract DateTime ToDateTime(long value); public abstract DateTime ToDateTime(double value); public abstract DateTime ToDateTime(DateTimeOffset value); public abstract DateTime ToDateTime(string value); public abstract DateTime ToDateTime(object value); public abstract DateTimeOffset ToDateTimeOffset(DateTime value); public abstract DateTimeOffset ToDateTimeOffset(string value); public abstract DateTimeOffset ToDateTimeOffset(object value); public abstract string ToString(bool value); public abstract string ToString(int value); public abstract string ToString(long value); public abstract string ToString(decimal value); public abstract string ToString(float value); public abstract string ToString(double value); public abstract string ToString(DateTime value); public abstract string ToString(DateTimeOffset value); public abstract string ToString(object value); public abstract string ToString(object value, IXmlNamespaceResolver? nsResolver); public abstract object ChangeType(bool value, Type destinationType); public abstract object ChangeType(int value, Type destinationType); public abstract object ChangeType(long value, Type destinationType); public abstract object ChangeType(decimal value, Type destinationType); public abstract object ChangeType(double value, Type destinationType); public abstract object ChangeType(DateTime value, Type destinationType); public abstract object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver); public abstract object ChangeType(object value, Type destinationType); public abstract object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver); } internal abstract class XmlBaseConverter : XmlValueConverter { private readonly XmlSchemaType? _schemaType; private readonly XmlTypeCode _typeCode; private readonly Type? _clrTypeDefault; protected XmlBaseConverter(XmlSchemaType schemaType) { // XmlValueConverter is defined only on types with simple content XmlSchemaDatatype? datatype = schemaType.Datatype; Debug.Assert(schemaType != null && datatype != null, "schemaType or schemaType.Datatype may not be null"); while (schemaType != null && !(schemaType is XmlSchemaSimpleType)) { schemaType = schemaType.BaseXmlSchemaType!; } if (schemaType == null) { //Did not find any simple type in the parent chain schemaType = XmlSchemaType.GetBuiltInSimpleType(datatype.TypeCode); } Debug.Assert(schemaType.Datatype!.Variety != XmlSchemaDatatypeVariety.List, "schemaType must be list's item type, not list itself"); _schemaType = schemaType; _typeCode = schemaType.TypeCode; _clrTypeDefault = schemaType.Datatype.ValueType; } protected XmlBaseConverter(XmlTypeCode typeCode) { switch (typeCode) { case XmlTypeCode.Item: _clrTypeDefault = XPathItemType; break; case XmlTypeCode.Node: _clrTypeDefault = XPathNavigatorType; break; case XmlTypeCode.AnyAtomicType: _clrTypeDefault = XmlAtomicValueType; break; default: Debug.Fail($"Type code {typeCode} is not supported."); break; } _typeCode = typeCode; } protected XmlBaseConverter(XmlBaseConverter converterAtomic) { _schemaType = converterAtomic._schemaType; _typeCode = converterAtomic._typeCode; _clrTypeDefault = Array.CreateInstance(converterAtomic.DefaultClrType!, 0).GetType(); } protected XmlBaseConverter(XmlBaseConverter converterAtomic, Type clrTypeDefault) { _schemaType = converterAtomic._schemaType; _typeCode = converterAtomic._typeCode; _clrTypeDefault = clrTypeDefault; } protected static readonly Type ICollectionType = typeof(ICollection); protected static readonly Type IEnumerableType = typeof(IEnumerable); protected static readonly Type IListType = typeof(IList); protected static readonly Type ObjectArrayType = typeof(object[]); protected static readonly Type StringArrayType = typeof(string[]); protected static readonly Type XmlAtomicValueArrayType = typeof(XmlAtomicValue[]); #region AUTOGENERATED_XMLBASECONVERTER protected static readonly Type DecimalType = typeof(decimal); protected static readonly Type Int32Type = typeof(int); protected static readonly Type Int64Type = typeof(long); protected static readonly Type StringType = typeof(string); protected static readonly Type XmlAtomicValueType = typeof(XmlAtomicValue); protected static readonly Type ObjectType = typeof(object); protected static readonly Type ByteType = typeof(byte); protected static readonly Type Int16Type = typeof(short); protected static readonly Type SByteType = typeof(sbyte); protected static readonly Type UInt16Type = typeof(ushort); protected static readonly Type UInt32Type = typeof(uint); protected static readonly Type UInt64Type = typeof(ulong); protected static readonly Type XPathItemType = typeof(XPathItem); protected static readonly Type DoubleType = typeof(double); protected static readonly Type SingleType = typeof(float); protected static readonly Type DateTimeType = typeof(DateTime); protected static readonly Type DateTimeOffsetType = typeof(DateTimeOffset); protected static readonly Type BooleanType = typeof(bool); protected static readonly Type ByteArrayType = typeof(byte[]); protected static readonly Type XmlQualifiedNameType = typeof(XmlQualifiedName); protected static readonly Type UriType = typeof(Uri); protected static readonly Type TimeSpanType = typeof(TimeSpan); protected static readonly Type XPathNavigatorType = typeof(XPathNavigator); public override bool ToBoolean(DateTime value) { return (bool)ChangeType((object)value, BooleanType, null); } public override bool ToBoolean(double value) { return (bool)ChangeType((object)value, BooleanType, null); } public override bool ToBoolean(int value) { return (bool)ChangeType((object)value, BooleanType, null); } public override bool ToBoolean(long value) { return (bool)ChangeType((object)value, BooleanType, null); } public override bool ToBoolean(string value) { return (bool)ChangeType((object)value, BooleanType, null); } public override bool ToBoolean(object value) { return (bool)ChangeType((object)value, BooleanType, null); } public override DateTime ToDateTime(bool value) { return (DateTime)ChangeType((object)value, DateTimeType, null); } public override DateTime ToDateTime(DateTimeOffset value) { return (DateTime)ChangeType((object)value, DateTimeType, null); } public override DateTime ToDateTime(double value) { return (DateTime)ChangeType((object)value, DateTimeType, null); } public override DateTime ToDateTime(int value) { return (DateTime)ChangeType((object)value, DateTimeType, null); } public override DateTime ToDateTime(long value) { return (DateTime)ChangeType((object)value, DateTimeType, null); } public override DateTime ToDateTime(string value) { return (DateTime)ChangeType((object)value, DateTimeType, null); } public override DateTime ToDateTime(object value) { return (DateTime)ChangeType((object)value, DateTimeType, null); } public override DateTimeOffset ToDateTimeOffset(DateTime value) { return (DateTimeOffset)ChangeType((object)value, DateTimeOffsetType, null); } public override DateTimeOffset ToDateTimeOffset(string value) { return (DateTimeOffset)ChangeType((object)value, DateTimeOffsetType, null); } public override DateTimeOffset ToDateTimeOffset(object value) { return (DateTimeOffset)ChangeType((object)value, DateTimeOffsetType, null); } public override decimal ToDecimal(string value) { return (decimal)ChangeType((object)value, DecimalType, null); } public override decimal ToDecimal(object value) { return (decimal)ChangeType((object)value, DecimalType, null); } public override double ToDouble(bool value) { return (double)ChangeType((object)value, DoubleType, null); } public override double ToDouble(DateTime value) { return (double)ChangeType((object)value, DoubleType, null); } public override double ToDouble(int value) { return (double)ChangeType((object)value, DoubleType, null); } public override double ToDouble(long value) { return (double)ChangeType((object)value, DoubleType, null); } public override double ToDouble(string value) { return (double)ChangeType((object)value, DoubleType, null); } public override double ToDouble(object value) { return (double)ChangeType((object)value, DoubleType, null); } public override int ToInt32(bool value) { return (int)ChangeType((object)value, Int32Type, null); } public override int ToInt32(DateTime value) { return (int)ChangeType((object)value, Int32Type, null); } public override int ToInt32(double value) { return (int)ChangeType((object)value, Int32Type, null); } public override int ToInt32(long value) { return (int)ChangeType((object)value, Int32Type, null); } public override int ToInt32(string value) { return (int)ChangeType((object)value, Int32Type, null); } public override int ToInt32(object value) { return (int)ChangeType((object)value, Int32Type, null); } public override long ToInt64(bool value) { return (long)ChangeType((object)value, Int64Type, null); } public override long ToInt64(DateTime value) { return (long)ChangeType((object)value, Int64Type, null); } public override long ToInt64(double value) { return (long)ChangeType((object)value, Int64Type, null); } public override long ToInt64(int value) { return (long)ChangeType((object)value, Int64Type, null); } public override long ToInt64(string value) { return (long)ChangeType((object)value, Int64Type, null); } public override long ToInt64(object value) { return (long)ChangeType((object)value, Int64Type, null); } public override float ToSingle(double value) { return (float)ChangeType((object)value, SingleType, null); } public override float ToSingle(string value) { return (float)ChangeType((object)value, SingleType, null); } public override float ToSingle(object value) { return (float)ChangeType((object)value, SingleType, null); } public override string ToString(bool value) { return (string)ChangeType((object)value, StringType, null); } public override string ToString(DateTime value) { return (string)ChangeType((object)value, StringType, null); } public override string ToString(DateTimeOffset value) { return (string)ChangeType((object)value, StringType, null); } public override string ToString(decimal value) { return (string)ChangeType((object)value, StringType, null); } public override string ToString(double value) { return (string)ChangeType((object)value, StringType, null); } public override string ToString(int value) { return (string)ChangeType((object)value, StringType, null); } public override string ToString(long value) { return (string)ChangeType((object)value, StringType, null); } public override string ToString(float value) { return (string)ChangeType((object)value, StringType, null); } public override string ToString(object value, IXmlNamespaceResolver? nsResolver) { return (string)ChangeType((object)value, StringType, nsResolver); } public override string ToString(object value) { return this.ToString(value, null); } public override object ChangeType(bool value, Type destinationType) { return (object)ChangeType((object)value, destinationType, null); } public override object ChangeType(DateTime value, Type destinationType) { return (object)ChangeType((object)value, destinationType, null); } public override object ChangeType(decimal value, Type destinationType) { return (object)ChangeType((object)value, destinationType, null); } public override object ChangeType(double value, Type destinationType) { return (object)ChangeType((object)value, destinationType, null); } public override object ChangeType(int value, Type destinationType) { return (object)ChangeType((object)value, destinationType, null); } public override object ChangeType(long value, Type destinationType) { return (object)ChangeType((object)value, destinationType, null); } public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { return (object)ChangeType((object)value, destinationType, nsResolver); } public override object ChangeType(object value, Type destinationType) { return this.ChangeType(value, destinationType, null); } #endregion /// <summary> /// Return this converter's prime schema type (may be null in case of Node, Item, etc). /// </summary> protected XmlSchemaType? SchemaType { get { return _schemaType; } } /// <summary> /// Return the XmlTypeCode of this converter's prime schema type. /// </summary> protected XmlTypeCode TypeCode { get { return _typeCode; } } /// <summary> /// Return a string representation of this converter's prime schema type. /// </summary> protected string XmlTypeName { get { XmlSchemaType? type = _schemaType; if (type != null) { while (type!.QualifiedName.IsEmpty) { // Walk base classes until one with a name is found (in worst case, all simple types derive from xs:anySimpleType) type = type.BaseXmlSchemaType; } return QNameToString(type.QualifiedName); } // SchemaType is null in the case of item, node, and xdt:anyAtomicType if (_typeCode == XmlTypeCode.Node) return "node"; if (_typeCode == XmlTypeCode.AnyAtomicType) return "xdt:anyAtomicType"; Debug.Assert(_typeCode == XmlTypeCode.Item, "If SchemaType is null, then TypeCode may only be Item, Node, or AnyAtomicType"); return "item"; } } /// <summary> /// Return default V1 Clr mapping of this converter's type. /// </summary> protected Type? DefaultClrType { get { return _clrTypeDefault; } } /// <summary> /// Type.IsSubtypeOf does not return true if types are equal, this method does. /// </summary> protected static bool IsDerivedFrom(Type? derivedType, Type baseType) { while (derivedType != null) { if (derivedType == baseType) return true; derivedType = derivedType.BaseType; } return false; } /// <summary> /// Create an InvalidCastException for cases where either "destinationType" or "sourceType" is not a supported CLR representation /// for this Xml type. /// </summary> protected Exception CreateInvalidClrMappingException(Type sourceType, Type destinationType) { if (sourceType == destinationType) return new InvalidCastException(SR.Format(SR.XmlConvert_TypeBadMapping, XmlTypeName, sourceType.Name)); return new InvalidCastException(SR.Format(SR.XmlConvert_TypeBadMapping2, XmlTypeName, sourceType.Name, destinationType.Name)); } /// <summary> /// Convert an XmlQualifiedName to a string, using somewhat different rules than XmlQualifiedName.ToString(): /// 1. Recognize the built-in xs: and xdt: namespaces and print the short prefix rather than the long namespace /// 2. Use brace characters "{", "}" around the namespace portion of the QName /// </summary> protected static string QNameToString(XmlQualifiedName name) { if (name.Namespace.Length == 0) { return name.Name; } else if (name.Namespace == XmlReservedNs.NsXs) { return $"xs:{name.Name}"; } else if (name.Namespace == XmlReservedNs.NsXQueryDataType) { return $"xdt:{name.Name}"; } else { return $"{{{name.Namespace}}}{name.Name}"; } } /// <summary> /// This method is called when a valid conversion cannot be found. By default, this method throws an error. It can /// be overridden in derived classes to support list conversions. /// </summary> protected virtual object ChangeListType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { throw CreateInvalidClrMappingException(value.GetType(), destinationType); } //------------------------------------------------------------------------ // From String Conversion Helpers //------------------------------------------------------------------------ protected static byte[] StringToBase64Binary(string value) { return Convert.FromBase64String(XmlConvert.TrimString(value)); } protected static DateTime StringToDate(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.Date)); } protected static DateTime StringToDateTime(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.DateTime)); } protected static TimeSpan StringToDayTimeDuration(string value) { // Parse string as DayTimeDuration and convert it to a DayTimeDuration TimeSpan (it is an error to have year and month parts) return new XsdDuration(value, XsdDuration.DurationType.DayTimeDuration).ToTimeSpan(XsdDuration.DurationType.DayTimeDuration); } protected static TimeSpan StringToDuration(string value) { return new XsdDuration(value, XsdDuration.DurationType.Duration).ToTimeSpan(XsdDuration.DurationType.Duration); } protected static DateTime StringToGDay(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.GDay)); } protected static DateTime StringToGMonth(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.GMonth)); } protected static DateTime StringToGMonthDay(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.GMonthDay)); } protected static DateTime StringToGYear(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.GYear)); } protected static DateTime StringToGYearMonth(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.GYearMonth)); } protected static DateTimeOffset StringToDateOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.Date)); } protected static DateTimeOffset StringToDateTimeOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.DateTime)); } protected static DateTimeOffset StringToGDayOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.GDay)); } protected static DateTimeOffset StringToGMonthOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.GMonth)); } protected static DateTimeOffset StringToGMonthDayOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.GMonthDay)); } protected static DateTimeOffset StringToGYearOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.GYear)); } protected static DateTimeOffset StringToGYearMonthOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.GYearMonth)); } protected static byte[] StringToHexBinary(string value) { try { return XmlConvert.FromBinHexString(XmlConvert.TrimString(value), false); } catch (XmlException e) { throw new FormatException(e.Message); } } protected static XmlQualifiedName StringToQName(string value, IXmlNamespaceResolver? nsResolver) { string prefix, localName; string? ns; value = value.Trim(); // Parse prefix:localName try { ValidateNames.ParseQNameThrow(value, out prefix, out localName); } catch (XmlException e) { throw new FormatException(e.Message); } // Throw error if no namespaces are in scope if (nsResolver == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Lookup namespace ns = nsResolver.LookupNamespace(prefix); if (ns == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Create XmlQualfiedName return new XmlQualifiedName(localName, ns); } protected static DateTime StringToTime(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.Time)); } protected static DateTimeOffset StringToTimeOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.Time)); } protected static TimeSpan StringToYearMonthDuration(string value) { // Parse string as YearMonthDuration and convert it to a YearMonthDuration TimeSpan (it is an error to have day and time parts) return new XsdDuration(value, XsdDuration.DurationType.YearMonthDuration).ToTimeSpan(XsdDuration.DurationType.YearMonthDuration); } //------------------------------------------------------------------------ // To String Conversion Helpers //------------------------------------------------------------------------ protected static string AnyUriToString(Uri value) { return value.OriginalString; } protected static string Base64BinaryToString(byte[] value) { return Convert.ToBase64String(value); } protected static string DateToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.Date)).ToString(); } protected static string DateTimeToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.DateTime)).ToString(); } protected static string DayTimeDurationToString(TimeSpan value) { return new XsdDuration(value, XsdDuration.DurationType.DayTimeDuration).ToString(XsdDuration.DurationType.DayTimeDuration); } protected static string DurationToString(TimeSpan value) { return new XsdDuration(value, XsdDuration.DurationType.Duration).ToString(XsdDuration.DurationType.Duration); } protected static string GDayToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.GDay)).ToString(); } protected static string GMonthToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.GMonth)).ToString(); } protected static string GMonthDayToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.GMonthDay)).ToString(); } protected static string GYearToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.GYear)).ToString(); } protected static string GYearMonthToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.GYearMonth)).ToString(); } protected static string DateOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.Date)).ToString(); } protected static string DateTimeOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.DateTime)).ToString(); } protected static string GDayOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.GDay)).ToString(); } protected static string GMonthOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.GMonth)).ToString(); } protected static string GMonthDayOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.GMonthDay)).ToString(); } protected static string GYearOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.GYear)).ToString(); } protected static string GYearMonthOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.GYearMonth)).ToString(); } protected static string QNameToString(XmlQualifiedName qname, IXmlNamespaceResolver? nsResolver) { string? prefix; if (nsResolver == null) return $"{{{qname.Namespace}}}{qname.Name}"; prefix = nsResolver.LookupPrefix(qname.Namespace); if (prefix == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoPrefix, qname, qname.Namespace)); return (prefix.Length != 0) ? $"{prefix}:{qname.Name}" : qname.Name; } protected static string TimeToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.Time)).ToString(); } protected static string TimeOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.Time)).ToString(); } protected static string YearMonthDurationToString(TimeSpan value) { return new XsdDuration(value, XsdDuration.DurationType.YearMonthDuration).ToString(XsdDuration.DurationType.YearMonthDuration); } //------------------------------------------------------------------------ // Other Conversion Helpers //------------------------------------------------------------------------ internal static DateTime DateTimeOffsetToDateTime(DateTimeOffset value) { return value.LocalDateTime; } internal static int DecimalToInt32(decimal value) { if (value < (decimal)int.MinValue || value > (decimal)int.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Int32" })); return (int)value; } protected static long DecimalToInt64(decimal value) { if (value < (decimal)long.MinValue || value > (decimal)long.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Int64" })); return (long)value; } protected static ulong DecimalToUInt64(decimal value) { if (value < (decimal)ulong.MinValue || value > (decimal)ulong.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt64" })); return (ulong)value; } protected static byte Int32ToByte(int value) { if (value < (int)byte.MinValue || value > (int)byte.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Byte" })); return (byte)value; } protected static short Int32ToInt16(int value) { if (value < (int)short.MinValue || value > (int)short.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Int16" })); return (short)value; } protected static sbyte Int32ToSByte(int value) { if (value < (int)sbyte.MinValue || value > (int)sbyte.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "SByte" })); return (sbyte)value; } protected static ushort Int32ToUInt16(int value) { if (value < (int)ushort.MinValue || value > (int)ushort.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt16" })); return (ushort)value; } protected static int Int64ToInt32(long value) { if (value < (long)int.MinValue || value > (long)int.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Int32" })); return (int)value; } protected static uint Int64ToUInt32(long value) { if (value < (long)uint.MinValue || value > (long)uint.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt32" })); return (uint)value; } protected static DateTime UntypedAtomicToDateTime(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.AllXsd)); } protected static DateTimeOffset UntypedAtomicToDateTimeOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.AllXsd)); } } internal sealed class XmlNumeric10Converter : XmlBaseConverter { private XmlNumeric10Converter(XmlSchemaType schemaType) : base(schemaType) { } public static XmlValueConverter Create(XmlSchemaType schemaType) { return new XmlNumeric10Converter(schemaType); } #region AUTOGENERATED_XMLNUMERIC10CONVERTER public override decimal ToDecimal(string value!!) { if (TypeCode == XmlTypeCode.Decimal) return XmlConvert.ToDecimal((string)value); return XmlConvert.ToInteger((string)value); } public override decimal ToDecimal(object value!!) { Type sourceType = value.GetType(); if (sourceType == DecimalType) return ((decimal)value); if (sourceType == Int32Type) return ((decimal)(int)value); if (sourceType == Int64Type) return ((decimal)(long)value); if (sourceType == StringType) return this.ToDecimal((string)value); if (sourceType == XmlAtomicValueType) return ((decimal)((XmlAtomicValue)value).ValueAs(DecimalType)); return (decimal)ChangeTypeWildcardDestination(value, DecimalType, null); } public override int ToInt32(long value) { return Int64ToInt32((long)value); } public override int ToInt32(string value!!) { if (TypeCode == XmlTypeCode.Decimal) return DecimalToInt32(XmlConvert.ToDecimal((string)value)); return XmlConvert.ToInt32((string)value); } public override int ToInt32(object value!!) { Type sourceType = value.GetType(); if (sourceType == DecimalType) return DecimalToInt32((decimal)value); if (sourceType == Int32Type) return ((int)value); if (sourceType == Int64Type) return Int64ToInt32((long)value); if (sourceType == StringType) return this.ToInt32((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsInt; return (int)ChangeTypeWildcardDestination(value, Int32Type, null); } public override long ToInt64(int value) { return ((long)(int)value); } public override long ToInt64(string value!!) { if (TypeCode == XmlTypeCode.Decimal) return DecimalToInt64(XmlConvert.ToDecimal((string)value)); return XmlConvert.ToInt64((string)value); } public override long ToInt64(object value!!) { Type sourceType = value.GetType(); if (sourceType == DecimalType) return DecimalToInt64((decimal)value); if (sourceType == Int32Type) return ((long)(int)value); if (sourceType == Int64Type) return ((long)value); if (sourceType == StringType) return this.ToInt64((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsLong; return (long)ChangeTypeWildcardDestination(value, Int64Type, null); } //----------------------------------------------- // ToSingle //----------------------------------------------- // This converter does not support conversions to Single. //----------------------------------------------- // ToString //----------------------------------------------- public override string ToString(decimal value) { if (TypeCode == XmlTypeCode.Decimal) return XmlConvert.ToString((decimal)value); return XmlConvert.ToString(decimal.Truncate((decimal)value)); } public override string ToString(int value) { return XmlConvert.ToString((int)value); } public override string ToString(long value) { return XmlConvert.ToString((long)value); } public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == DecimalType) return this.ToString((decimal)value); if (sourceType == Int32Type) return XmlConvert.ToString((int)value); if (sourceType == Int64Type) return XmlConvert.ToString((long)value); if (sourceType == StringType) return ((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).Value; return (string)ChangeTypeWildcardDestination(value, StringType, nsResolver); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(decimal value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return ((decimal)value); if (destinationType == Int32Type) return DecimalToInt32((decimal)value); if (destinationType == Int64Type) return DecimalToInt64((decimal)value); if (destinationType == StringType) return this.ToString((decimal)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, value)); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(int value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return ((decimal)(int)value); if (destinationType == Int32Type) return ((int)value); if (destinationType == Int64Type) return ((long)(int)value); if (destinationType == StringType) return XmlConvert.ToString((int)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (int)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (int)value)); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(long value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return ((decimal)(long)value); if (destinationType == Int32Type) return Int64ToInt32((long)value); if (destinationType == Int64Type) return ((long)value); if (destinationType == StringType) return XmlConvert.ToString((long)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (long)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (long)value)); return ChangeTypeWildcardSource(value, destinationType!, null); } public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return this.ToDecimal((string)value); if (destinationType == Int32Type) return this.ToInt32((string)value); if (destinationType == Int64Type) return this.ToInt64((string)value); if (destinationType == StringType) return ((string)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (string)value)); return ChangeTypeWildcardSource(value, destinationType, nsResolver); } public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return this.ToDecimal(value); if (destinationType == Int32Type) return this.ToInt32(value); if (destinationType == Int64Type) return this.ToInt64(value); if (destinationType == StringType) return this.ToString(value, nsResolver); if (destinationType == XmlAtomicValueType) { if (sourceType == DecimalType) return (new XmlAtomicValue(SchemaType!, value)); if (sourceType == Int32Type) return (new XmlAtomicValue(SchemaType!, (int)value)); if (sourceType == Int64Type) return (new XmlAtomicValue(SchemaType!, (long)value)); if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == XPathItemType) { if (sourceType == DecimalType) return (new XmlAtomicValue(SchemaType!, value)); if (sourceType == Int32Type) return (new XmlAtomicValue(SchemaType!, (int)value)); if (sourceType == Int64Type) return (new XmlAtomicValue(SchemaType!, (long)value)); if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == ByteType) return Int32ToByte(this.ToInt32(value)); if (destinationType == Int16Type) return Int32ToInt16(this.ToInt32(value)); if (destinationType == SByteType) return Int32ToSByte(this.ToInt32(value)); if (destinationType == UInt16Type) return Int32ToUInt16(this.ToInt32(value)); if (destinationType == UInt32Type) return Int64ToUInt32(this.ToInt64(value)); if (destinationType == UInt64Type) return DecimalToUInt64(this.ToDecimal(value)); if (sourceType == ByteType) return this.ChangeType((int)(byte)value, destinationType); if (sourceType == Int16Type) return this.ChangeType((int)(short)value, destinationType); if (sourceType == SByteType) return this.ChangeType((int)(sbyte)value, destinationType); if (sourceType == UInt16Type) return this.ChangeType((int)(ushort)value, destinationType); if (sourceType == UInt32Type) return this.ChangeType((long)(uint)value, destinationType); if (sourceType == UInt64Type) return this.ChangeType((decimal)(ulong)value, destinationType); return ChangeListType(value, destinationType, nsResolver); } //----------------------------------------------- // Helpers //----------------------------------------------- private object ChangeTypeWildcardDestination(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == ByteType) return this.ChangeType((int)(byte)value, destinationType); if (sourceType == Int16Type) return this.ChangeType((int)(short)value, destinationType); if (sourceType == SByteType) return this.ChangeType((int)(sbyte)value, destinationType); if (sourceType == UInt16Type) return this.ChangeType((int)(ushort)value, destinationType); if (sourceType == UInt32Type) return this.ChangeType((long)(uint)value, destinationType); if (sourceType == UInt64Type) return this.ChangeType((decimal)(ulong)value, destinationType); return ChangeListType(value, destinationType, nsResolver); } private object ChangeTypeWildcardSource(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { if (destinationType == ByteType) return Int32ToByte(this.ToInt32(value)); if (destinationType == Int16Type) return Int32ToInt16(this.ToInt32(value)); if (destinationType == SByteType) return Int32ToSByte(this.ToInt32(value)); if (destinationType == UInt16Type) return Int32ToUInt16(this.ToInt32(value)); if (destinationType == UInt32Type) return Int64ToUInt32(this.ToInt64(value)); if (destinationType == UInt64Type) return DecimalToUInt64(this.ToDecimal(value)); return ChangeListType(value, destinationType, nsResolver); } #endregion } internal sealed class XmlNumeric2Converter : XmlBaseConverter { private XmlNumeric2Converter(XmlSchemaType schemaType) : base(schemaType) { } public static XmlValueConverter Create(XmlSchemaType schemaType) { return new XmlNumeric2Converter(schemaType); } #region AUTOGENERATED_XMLNUMERIC2CONVERTER public override double ToDouble(string value!!) { if (TypeCode == XmlTypeCode.Float) return ((double)XmlConvert.ToSingle((string)value)); return XmlConvert.ToDouble((string)value); } public override double ToDouble(object value!!) { Type sourceType = value.GetType(); if (sourceType == DoubleType) return ((double)value); if (sourceType == SingleType) return ((double)(float)value); if (sourceType == StringType) return this.ToDouble((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsDouble; return (double)ChangeListType(value, DoubleType, null); } //----------------------------------------------- // ToInt32 //----------------------------------------------- // This converter does not support conversions to Int32. //----------------------------------------------- // ToInt64 //----------------------------------------------- // This converter does not support conversions to Int64. //----------------------------------------------- // ToSingle //----------------------------------------------- public override float ToSingle(double value) { return ((float)(double)value); } public override float ToSingle(string value!!) { if (TypeCode == XmlTypeCode.Float) return XmlConvert.ToSingle((string)value); return ((float)XmlConvert.ToDouble((string)value)); } public override float ToSingle(object value!!) { Type sourceType = value.GetType(); if (sourceType == DoubleType) return ((float)(double)value); if (sourceType == SingleType) return ((float)value); if (sourceType == StringType) return this.ToSingle((string)value); if (sourceType == XmlAtomicValueType) return ((float)((XmlAtomicValue)value).ValueAs(SingleType)); return (float)ChangeListType(value, SingleType, null); } //----------------------------------------------- // ToString //----------------------------------------------- public override string ToString(double value) { if (TypeCode == XmlTypeCode.Float) return XmlConvert.ToString(ToSingle((double)value)); return XmlConvert.ToString((double)value); } public override string ToString(float value) { if (TypeCode == XmlTypeCode.Float) return XmlConvert.ToString((float)value); return XmlConvert.ToString((double)(float)value); } public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == DoubleType) return this.ToString((double)value); if (sourceType == SingleType) return this.ToString((float)value); if (sourceType == StringType) return ((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).Value; return (string)ChangeListType(value, StringType, nsResolver); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(double value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DoubleType) return ((double)value); if (destinationType == SingleType) return ((float)(double)value); if (destinationType == StringType) return this.ToString((double)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (double)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (double)value)); return ChangeListType(value, destinationType, null); } public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DoubleType) return this.ToDouble((string)value); if (destinationType == SingleType) return this.ToSingle((string)value); if (destinationType == StringType) return ((string)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (string)value)); return ChangeListType(value, destinationType, nsResolver); } public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DoubleType) return this.ToDouble(value); if (destinationType == SingleType) return this.ToSingle(value); if (destinationType == StringType) return this.ToString(value, nsResolver); if (destinationType == XmlAtomicValueType) { if (sourceType == DoubleType) return (new XmlAtomicValue(SchemaType!, (double)value)); if (sourceType == SingleType) return (new XmlAtomicValue(SchemaType!, value)); if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == XPathItemType) { if (sourceType == DoubleType) return (new XmlAtomicValue(SchemaType!, (double)value)); if (sourceType == SingleType) return (new XmlAtomicValue(SchemaType!, value)); if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } return ChangeListType(value, destinationType, nsResolver); } #endregion } internal sealed class XmlDateTimeConverter : XmlBaseConverter { private XmlDateTimeConverter(XmlSchemaType schemaType) : base(schemaType) { } public static XmlValueConverter Create(XmlSchemaType schemaType) { return new XmlDateTimeConverter(schemaType); } #region AUTOGENERATED_XMLDATETIMECONVERTER public override DateTime ToDateTime(DateTimeOffset value) { return DateTimeOffsetToDateTime(value); } public override DateTime ToDateTime(string value!!) { return TypeCode switch { XmlTypeCode.Date => StringToDate((string)value), XmlTypeCode.Time => StringToTime((string)value), XmlTypeCode.GDay => StringToGDay((string)value), XmlTypeCode.GMonth => StringToGMonth((string)value), XmlTypeCode.GMonthDay => StringToGMonthDay((string)value), XmlTypeCode.GYear => StringToGYear((string)value), XmlTypeCode.GYearMonth => StringToGYearMonth((string)value), _ => StringToDateTime((string)value), }; } public override DateTime ToDateTime(object value!!) { Type sourceType = value.GetType(); if (sourceType == DateTimeType) return ((DateTime)value); if (sourceType == DateTimeOffsetType) return this.ToDateTime((DateTimeOffset)value); if (sourceType == StringType) return this.ToDateTime((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsDateTime; return (DateTime)ChangeListType(value, DateTimeType, null); } //----------------------------------------------- // ToDateTimeOffset //----------------------------------------------- public override DateTimeOffset ToDateTimeOffset(DateTime value) { return new DateTimeOffset(value); } public override DateTimeOffset ToDateTimeOffset(string value!!) { return TypeCode switch { XmlTypeCode.Date => StringToDateOffset((string)value), XmlTypeCode.Time => StringToTimeOffset((string)value), XmlTypeCode.GDay => StringToGDayOffset((string)value), XmlTypeCode.GMonth => StringToGMonthOffset((string)value), XmlTypeCode.GMonthDay => StringToGMonthDayOffset((string)value), XmlTypeCode.GYear => StringToGYearOffset((string)value), XmlTypeCode.GYearMonth => StringToGYearMonthOffset((string)value), _ => StringToDateTimeOffset((string)value), }; } public override DateTimeOffset ToDateTimeOffset(object value!!) { Type sourceType = value.GetType(); if (sourceType == DateTimeType) return ToDateTimeOffset((DateTime)value); if (sourceType == DateTimeOffsetType) return ((DateTimeOffset)value); if (sourceType == StringType) return this.ToDateTimeOffset((string)value); if (sourceType == XmlAtomicValueType) return (DateTimeOffset)((XmlAtomicValue)value).ValueAsDateTime; return (DateTimeOffset)ChangeListType(value, DateTimeOffsetType, null); } //----------------------------------------------- // ToDecimal //----------------------------------------------- // This converter does not support conversions to Decimal. //----------------------------------------------- // ToDouble //----------------------------------------------- // This converter does not support conversions to Double. //----------------------------------------------- // ToInt32 //----------------------------------------------- // This converter does not support conversions to Int32. //----------------------------------------------- // ToInt64 //----------------------------------------------- // This converter does not support conversions to Int64. //----------------------------------------------- // ToSingle //----------------------------------------------- // This converter does not support conversions to Single. //----------------------------------------------- // ToString //----------------------------------------------- public override string ToString(DateTime value) => TypeCode switch { XmlTypeCode.Date => DateToString((DateTime)value), XmlTypeCode.Time => TimeToString((DateTime)value), XmlTypeCode.GDay => GDayToString((DateTime)value), XmlTypeCode.GMonth => GMonthToString((DateTime)value), XmlTypeCode.GMonthDay => GMonthDayToString((DateTime)value), XmlTypeCode.GYear => GYearToString((DateTime)value), XmlTypeCode.GYearMonth => GYearMonthToString((DateTime)value), _ => DateTimeToString((DateTime)value), }; public override string ToString(DateTimeOffset value) => TypeCode switch { XmlTypeCode.Date => DateOffsetToString((DateTimeOffset)value), XmlTypeCode.Time => TimeOffsetToString((DateTimeOffset)value), XmlTypeCode.GDay => GDayOffsetToString((DateTimeOffset)value), XmlTypeCode.GMonth => GMonthOffsetToString((DateTimeOffset)value), XmlTypeCode.GMonthDay => GMonthDayOffsetToString((DateTimeOffset)value), XmlTypeCode.GYear => GYearOffsetToString((DateTimeOffset)value), XmlTypeCode.GYearMonth => GYearMonthOffsetToString((DateTimeOffset)value), _ => DateTimeOffsetToString((DateTimeOffset)value), }; public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == DateTimeType) return this.ToString((DateTime)value); if (sourceType == DateTimeOffsetType) return this.ToString((DateTimeOffset)value); if (sourceType == StringType) return ((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).Value; return (string)ChangeListType(value, StringType, nsResolver); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(DateTime value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DateTimeType) return ((DateTime)value); if (destinationType == DateTimeOffsetType) return this.ToDateTimeOffset((DateTime)value); if (destinationType == StringType) return this.ToString((DateTime)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (DateTime)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (DateTime)value)); return ChangeListType(value, destinationType, null); } public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DateTimeType) return this.ToDateTime((string)value); if (destinationType == DateTimeOffsetType) return this.ToDateTimeOffset((string)value); if (destinationType == StringType) return ((string)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (string)value)); return ChangeListType(value, destinationType, nsResolver); } public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DateTimeType) return this.ToDateTime(value); if (destinationType == DateTimeOffsetType) return this.ToDateTimeOffset(value); if (destinationType == StringType) return this.ToString(value, nsResolver); if (destinationType == XmlAtomicValueType) { if (sourceType == DateTimeType) return (new XmlAtomicValue(SchemaType!, (DateTime)value)); if (sourceType == DateTimeOffsetType) return (new XmlAtomicValue(SchemaType!, (DateTimeOffset)value)); if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == XPathItemType) { if (sourceType == DateTimeType) return (new XmlAtomicValue(SchemaType!, (DateTime)value)); if (sourceType == DateTimeOffsetType) return (new XmlAtomicValue(SchemaType!, (DateTimeOffset)value)); if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } return ChangeListType(value, destinationType, nsResolver); } #endregion } internal sealed class XmlBooleanConverter : XmlBaseConverter { private XmlBooleanConverter(XmlSchemaType schemaType) : base(schemaType) { } public static XmlValueConverter Create(XmlSchemaType schemaType) { return new XmlBooleanConverter(schemaType); } #region AUTOGENERATED_XMLBOOLEANCONVERTER public override bool ToBoolean(string value!!) { return XmlConvert.ToBoolean((string)value); } public override bool ToBoolean(object value!!) { Type sourceType = value.GetType(); if (sourceType == BooleanType) return ((bool)value); if (sourceType == StringType) return XmlConvert.ToBoolean((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsBoolean; return (bool)ChangeListType(value, BooleanType, null); } //----------------------------------------------- // ToDateTime //----------------------------------------------- // This converter does not support conversions to DateTime. //----------------------------------------------- // ToDecimal //----------------------------------------------- // This converter does not support conversions to Decimal. //----------------------------------------------- // ToDouble //----------------------------------------------- // This converter does not support conversions to Double. //----------------------------------------------- // ToInt32 //----------------------------------------------- // This converter does not support conversions to Int32. //----------------------------------------------- // ToInt64 //----------------------------------------------- // This converter does not support conversions to Int64. //----------------------------------------------- // ToSingle //----------------------------------------------- // This converter does not support conversions to Single. //----------------------------------------------- // ToString //----------------------------------------------- public override string ToString(bool value) { return XmlConvert.ToString((bool)value); } public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == BooleanType) return XmlConvert.ToString((bool)value); if (sourceType == StringType) return ((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).Value; return (string)ChangeListType(value, StringType, nsResolver); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(bool value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) return ((bool)value); if (destinationType == StringType) return XmlConvert.ToString((bool)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (bool)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (bool)value)); return ChangeListType(value, destinationType, null); } public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) return XmlConvert.ToBoolean((string)value); if (destinationType == StringType) return ((string)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (string)value)); return ChangeListType(value, destinationType, nsResolver); } public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) return this.ToBoolean(value); if (destinationType == StringType) return this.ToString(value, nsResolver); if (destinationType == XmlAtomicValueType) { if (sourceType == BooleanType) return (new XmlAtomicValue(SchemaType!, (bool)value)); if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == XPathItemType) { if (sourceType == BooleanType) return (new XmlAtomicValue(SchemaType!, (bool)value)); if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } return ChangeListType(value, destinationType, nsResolver); } #endregion } internal sealed class XmlMiscConverter : XmlBaseConverter { private XmlMiscConverter(XmlSchemaType schemaType) : base(schemaType) { } public static XmlValueConverter Create(XmlSchemaType schemaType) { return new XmlMiscConverter(schemaType); } #region AUTOGENERATED_XMLMISCCONVERTER public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == ByteArrayType) { switch (TypeCode) { case XmlTypeCode.Base64Binary: return Base64BinaryToString((byte[])value); case XmlTypeCode.HexBinary: return XmlConvert.ToBinHexString((byte[])value); } } if (sourceType == StringType) return (string)value; if (IsDerivedFrom(sourceType, UriType)) if (TypeCode == XmlTypeCode.AnyUri) return AnyUriToString((Uri)value); if (sourceType == TimeSpanType) { switch (TypeCode) { case XmlTypeCode.DayTimeDuration: return DayTimeDurationToString((TimeSpan)value); case XmlTypeCode.Duration: return DurationToString((TimeSpan)value); case XmlTypeCode.YearMonthDuration: return YearMonthDurationToString((TimeSpan)value); } } if (IsDerivedFrom(sourceType, XmlQualifiedNameType)) { switch (TypeCode) { case XmlTypeCode.Notation: return QNameToString((XmlQualifiedName)value, nsResolver); case XmlTypeCode.QName: return QNameToString((XmlQualifiedName)value, nsResolver); } } return (string)ChangeTypeWildcardDestination(value, StringType, nsResolver); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == ByteArrayType) { switch (TypeCode) { case XmlTypeCode.Base64Binary: return StringToBase64Binary((string)value); case XmlTypeCode.HexBinary: return StringToHexBinary((string)value); } } if (destinationType == XmlQualifiedNameType) { switch (TypeCode) { case XmlTypeCode.Notation: return StringToQName((string)value, nsResolver); case XmlTypeCode.QName: return StringToQName((string)value, nsResolver); } } if (destinationType == StringType) return (string)value; if (destinationType == TimeSpanType) { switch (TypeCode) { case XmlTypeCode.DayTimeDuration: return StringToDayTimeDuration((string)value); case XmlTypeCode.Duration: return StringToDuration((string)value); case XmlTypeCode.YearMonthDuration: return StringToYearMonthDuration((string)value); } } if (destinationType == UriType) if (TypeCode == XmlTypeCode.AnyUri) return XmlConvert.ToUri((string)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (string)value, nsResolver)); return ChangeTypeWildcardSource(value, destinationType, nsResolver); } public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == ByteArrayType) { if (sourceType == ByteArrayType) { switch (TypeCode) { case XmlTypeCode.Base64Binary: return ((byte[])value); case XmlTypeCode.HexBinary: return ((byte[])value); } } if (sourceType == StringType) { switch (TypeCode) { case XmlTypeCode.Base64Binary: return StringToBase64Binary((string)value); case XmlTypeCode.HexBinary: return StringToHexBinary((string)value); } } } if (destinationType == XmlQualifiedNameType) { if (sourceType == StringType) { switch (TypeCode) { case XmlTypeCode.Notation: return StringToQName((string)value, nsResolver); case XmlTypeCode.QName: return StringToQName((string)value, nsResolver); } } if (IsDerivedFrom(sourceType, XmlQualifiedNameType)) { switch (TypeCode) { case XmlTypeCode.Notation: return ((XmlQualifiedName)value); case XmlTypeCode.QName: return ((XmlQualifiedName)value); } } } if (destinationType == StringType) return this.ToString(value, nsResolver); if (destinationType == TimeSpanType) { if (sourceType == StringType) { switch (TypeCode) { case XmlTypeCode.DayTimeDuration: return StringToDayTimeDuration((string)value); case XmlTypeCode.Duration: return StringToDuration((string)value); case XmlTypeCode.YearMonthDuration: return StringToYearMonthDuration((string)value); } } if (sourceType == TimeSpanType) { switch (TypeCode) { case XmlTypeCode.DayTimeDuration: return ((TimeSpan)value); case XmlTypeCode.Duration: return ((TimeSpan)value); case XmlTypeCode.YearMonthDuration: return ((TimeSpan)value); } } } if (destinationType == UriType) { if (sourceType == StringType) if (TypeCode == XmlTypeCode.AnyUri) return XmlConvert.ToUri((string)value); if (IsDerivedFrom(sourceType, UriType)) if (TypeCode == XmlTypeCode.AnyUri) return ((Uri)value); } if (destinationType == XmlAtomicValueType) { if (sourceType == ByteArrayType) { switch (TypeCode) { case XmlTypeCode.Base64Binary: return (new XmlAtomicValue(SchemaType!, value)); case XmlTypeCode.HexBinary: return (new XmlAtomicValue(SchemaType!, value)); } } if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value, nsResolver)); if (sourceType == TimeSpanType) { switch (TypeCode) { case XmlTypeCode.DayTimeDuration: return (new XmlAtomicValue(SchemaType!, value)); case XmlTypeCode.Duration: return (new XmlAtomicValue(SchemaType!, value)); case XmlTypeCode.YearMonthDuration: return (new XmlAtomicValue(SchemaType!, value)); } } if (IsDerivedFrom(sourceType, UriType)) if (TypeCode == XmlTypeCode.AnyUri) return (new XmlAtomicValue(SchemaType!, value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); if (IsDerivedFrom(sourceType, XmlQualifiedNameType)) { switch (TypeCode) { case XmlTypeCode.Notation: return (new XmlAtomicValue(SchemaType!, value, nsResolver)); case XmlTypeCode.QName: return (new XmlAtomicValue(SchemaType!, value, nsResolver)); } } } if (destinationType == XPathItemType) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == XPathItemType) return ((XPathItem)this.ChangeType(value, XmlAtomicValueType, nsResolver)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAs(destinationType, nsResolver); return ChangeListType(value, destinationType, nsResolver); } //----------------------------------------------- // Helpers //----------------------------------------------- private object ChangeTypeWildcardDestination(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAs(destinationType, nsResolver); return ChangeListType(value, destinationType, nsResolver); } private object ChangeTypeWildcardSource(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { if (destinationType == XPathItemType) return ((XPathItem)this.ChangeType(value, XmlAtomicValueType, nsResolver)); return ChangeListType(value, destinationType, nsResolver); } #endregion } internal sealed class XmlStringConverter : XmlBaseConverter { private XmlStringConverter(XmlSchemaType schemaType) : base(schemaType) { } public static XmlValueConverter Create(XmlSchemaType schemaType) { return new XmlStringConverter(schemaType); } #region AUTOGENERATED_XMLSTRINGCONVERTER public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == StringType) return ((string)value); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).Value; return (string)ChangeListType(value, StringType, nsResolver); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return ((string)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (string)value)); return ChangeListType(value, destinationType, nsResolver); } public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return this.ToString(value, nsResolver); if (destinationType == XmlAtomicValueType) { if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == XPathItemType) { if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } return ChangeListType(value, destinationType, nsResolver); } #endregion } internal sealed class XmlUntypedConverter : XmlListConverter { private readonly bool _allowListToList; private XmlUntypedConverter() : base(DatatypeImplementation.UntypedAtomicType) { } private XmlUntypedConverter(XmlUntypedConverter atomicConverter, bool allowListToList) : base(atomicConverter, allowListToList ? StringArrayType : StringType) { _allowListToList = allowListToList; } public static readonly XmlValueConverter Untyped = new XmlUntypedConverter(new XmlUntypedConverter(), false); public static readonly XmlValueConverter UntypedList = new XmlUntypedConverter(new XmlUntypedConverter(), true); #region AUTOGENERATED_XMLUNTYPEDCONVERTER //----------------------------------------------- // ToBoolean //----------------------------------------------- public override bool ToBoolean(string value!!) { return XmlConvert.ToBoolean((string)value); } public override bool ToBoolean(object value!!) { Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToBoolean((string)value); return (bool)ChangeTypeWildcardDestination(value, BooleanType, null); } //----------------------------------------------- // ToDateTime //----------------------------------------------- public override DateTime ToDateTime(string value!!) { return UntypedAtomicToDateTime((string)value); } public override DateTime ToDateTime(object value!!) { Type sourceType = value.GetType(); if (sourceType == StringType) return UntypedAtomicToDateTime((string)value); return (DateTime)ChangeTypeWildcardDestination(value, DateTimeType, null); } //----------------------------------------------- // ToDateTimeOffset //----------------------------------------------- public override DateTimeOffset ToDateTimeOffset(string value!!) { return UntypedAtomicToDateTimeOffset((string)value); } public override DateTimeOffset ToDateTimeOffset(object value!!) { Type sourceType = value.GetType(); if (sourceType == StringType) return UntypedAtomicToDateTimeOffset((string)value); return (DateTimeOffset)ChangeTypeWildcardDestination(value, DateTimeOffsetType, null); } //----------------------------------------------- // ToDecimal //----------------------------------------------- public override decimal ToDecimal(string value!!) { return XmlConvert.ToDecimal((string)value); } public override decimal ToDecimal(object value!!) { Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToDecimal((string)value); return (decimal)ChangeTypeWildcardDestination(value, DecimalType, null); } //----------------------------------------------- // ToDouble //----------------------------------------------- public override double ToDouble(string value!!) { return XmlConvert.ToDouble((string)value); } public override double ToDouble(object value!!) { Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToDouble((string)value); return (double)ChangeTypeWildcardDestination(value, DoubleType, null); } //----------------------------------------------- // ToInt32 //----------------------------------------------- public override int ToInt32(string value!!) { return XmlConvert.ToInt32((string)value); } public override int ToInt32(object value!!) { Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToInt32((string)value); return (int)ChangeTypeWildcardDestination(value, Int32Type, null); } //----------------------------------------------- // ToInt64 //----------------------------------------------- public override long ToInt64(string value!!) { return XmlConvert.ToInt64((string)value); } public override long ToInt64(object value!!) { Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToInt64((string)value); return (long)ChangeTypeWildcardDestination(value, Int64Type, null); } //----------------------------------------------- // ToSingle //----------------------------------------------- public override float ToSingle(string value!!) { return XmlConvert.ToSingle((string)value); } public override float ToSingle(object value!!) { Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToSingle((string)value); return (float)ChangeTypeWildcardDestination(value, SingleType, null); } //----------------------------------------------- // ToString //----------------------------------------------- public override string ToString(bool value) { return XmlConvert.ToString((bool)value); } public override string ToString(DateTime value) { return DateTimeToString((DateTime)value); } public override string ToString(DateTimeOffset value) { return DateTimeOffsetToString((DateTimeOffset)value); } public override string ToString(decimal value) { return XmlConvert.ToString((decimal)value); } public override string ToString(double value) { return XmlConvert.ToString((double)value); } public override string ToString(int value) { return XmlConvert.ToString((int)value); } public override string ToString(long value) { return XmlConvert.ToString((long)value); } public override string ToString(float value) { return XmlConvert.ToString((float)value); } public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == BooleanType) return XmlConvert.ToString((bool)value); if (sourceType == ByteType) return XmlConvert.ToString((byte)value); if (sourceType == ByteArrayType) return Base64BinaryToString((byte[])value); if (sourceType == DateTimeType) return DateTimeToString((DateTime)value); if (sourceType == DateTimeOffsetType) return DateTimeOffsetToString((DateTimeOffset)value); if (sourceType == DecimalType) return XmlConvert.ToString((decimal)value); if (sourceType == DoubleType) return XmlConvert.ToString((double)value); if (sourceType == Int16Type) return XmlConvert.ToString((short)value); if (sourceType == Int32Type) return XmlConvert.ToString((int)value); if (sourceType == Int64Type) return XmlConvert.ToString((long)value); if (sourceType == SByteType) return XmlConvert.ToString((sbyte)value); if (sourceType == SingleType) return XmlConvert.ToString((float)value); if (sourceType == StringType) return ((string)value); if (sourceType == TimeSpanType) return DurationToString((TimeSpan)value); if (sourceType == UInt16Type) return XmlConvert.ToString((ushort)value); if (sourceType == UInt32Type) return XmlConvert.ToString((uint)value); if (sourceType == UInt64Type) return XmlConvert.ToString((ulong)value); if (IsDerivedFrom(sourceType, UriType)) return AnyUriToString((Uri)value); if (sourceType == XmlAtomicValueType) return ((string)((XmlAtomicValue)value).ValueAs(StringType, nsResolver)); if (IsDerivedFrom(sourceType, XmlQualifiedNameType)) return QNameToString((XmlQualifiedName)value, nsResolver); return (string)ChangeTypeWildcardDestination(value, StringType, nsResolver); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(bool value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((bool)value); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(DateTime value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return DateTimeToString((DateTime)value); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(decimal value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((decimal)value); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(double value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((double)value); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(int value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((int)value); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(long value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((long)value); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) return XmlConvert.ToBoolean((string)value); if (destinationType == ByteType) return Int32ToByte(XmlConvert.ToInt32((string)value)); if (destinationType == ByteArrayType) return StringToBase64Binary((string)value); if (destinationType == DateTimeType) return UntypedAtomicToDateTime((string)value); if (destinationType == DateTimeOffsetType) return UntypedAtomicToDateTimeOffset((string)value); if (destinationType == DecimalType) return XmlConvert.ToDecimal((string)value); if (destinationType == DoubleType) return XmlConvert.ToDouble((string)value); if (destinationType == Int16Type) return Int32ToInt16(XmlConvert.ToInt32((string)value)); if (destinationType == Int32Type) return XmlConvert.ToInt32((string)value); if (destinationType == Int64Type) return XmlConvert.ToInt64((string)value); if (destinationType == SByteType) return Int32ToSByte(XmlConvert.ToInt32((string)value)); if (destinationType == SingleType) return XmlConvert.ToSingle((string)value); if (destinationType == TimeSpanType) return StringToDuration((string)value); if (destinationType == UInt16Type) return Int32ToUInt16(XmlConvert.ToInt32((string)value)); if (destinationType == UInt32Type) return Int64ToUInt32(XmlConvert.ToInt64((string)value)); if (destinationType == UInt64Type) return DecimalToUInt64(XmlConvert.ToDecimal((string)value)); if (destinationType == UriType) return XmlConvert.ToUri((string)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (destinationType == XmlQualifiedNameType) return StringToQName((string)value, nsResolver); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (destinationType == StringType) return ((string)value); return ChangeTypeWildcardSource(value, destinationType, nsResolver); } public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) { if (sourceType == StringType) return XmlConvert.ToBoolean((string)value); } if (destinationType == ByteType) { if (sourceType == StringType) return Int32ToByte(XmlConvert.ToInt32((string)value)); } if (destinationType == ByteArrayType) { if (sourceType == StringType) return StringToBase64Binary((string)value); } if (destinationType == DateTimeType) { if (sourceType == StringType) return UntypedAtomicToDateTime((string)value); } if (destinationType == DateTimeOffsetType) { if (sourceType == StringType) return UntypedAtomicToDateTimeOffset((string)value); } if (destinationType == DecimalType) { if (sourceType == StringType) return XmlConvert.ToDecimal((string)value); } if (destinationType == DoubleType) { if (sourceType == StringType) return XmlConvert.ToDouble((string)value); } if (destinationType == Int16Type) { if (sourceType == StringType) return Int32ToInt16(XmlConvert.ToInt32((string)value)); } if (destinationType == Int32Type) { if (sourceType == StringType) return XmlConvert.ToInt32((string)value); } if (destinationType == Int64Type) { if (sourceType == StringType) return XmlConvert.ToInt64((string)value); } if (destinationType == SByteType) { if (sourceType == StringType) return Int32ToSByte(XmlConvert.ToInt32((string)value)); } if (destinationType == SingleType) { if (sourceType == StringType) return XmlConvert.ToSingle((string)value); } if (destinationType == TimeSpanType) { if (sourceType == StringType) return StringToDuration((string)value); } if (destinationType == UInt16Type) { if (sourceType == StringType) return Int32ToUInt16(XmlConvert.ToInt32((string)value)); } if (destinationType == UInt32Type) { if (sourceType == StringType) return Int64ToUInt32(XmlConvert.ToInt64((string)value)); } if (destinationType == UInt64Type) { if (sourceType == StringType) return DecimalToUInt64(XmlConvert.ToDecimal((string)value)); } if (destinationType == UriType) { if (sourceType == StringType) return XmlConvert.ToUri((string)value); } if (destinationType == XmlAtomicValueType) { if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == XmlQualifiedNameType) { if (sourceType == StringType) return StringToQName((string)value, nsResolver); } if (destinationType == XPathItemType) { if (sourceType == StringType) return (new XmlAtomicValue(SchemaType!, (string)value)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); } if (destinationType == StringType) return this.ToString(value, nsResolver); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, this.ToString(value, nsResolver))); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, this.ToString(value, nsResolver))); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAs(destinationType, nsResolver); return ChangeListType(value, destinationType, nsResolver); } //----------------------------------------------- // Helpers //----------------------------------------------- private object ChangeTypeWildcardDestination(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAs(destinationType, nsResolver); return ChangeListType(value, destinationType, nsResolver); } private object ChangeTypeWildcardSource(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, this.ToString(value, nsResolver))); if (destinationType == XPathItemType) return (new XmlAtomicValue(SchemaType!, this.ToString(value, nsResolver))); return ChangeListType(value, destinationType, nsResolver); } #endregion //----------------------------------------------- // Helpers //----------------------------------------------- protected override object ChangeListType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); // 1. If there is no nested atomic converter, then do not support lists at all // 2. If list to list conversions are not allowed, only allow string => list and list => string if ((this.atomicConverter == null) || (!_allowListToList && sourceType != StringType && destinationType != StringType)) { if (SupportsType(sourceType)) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeToString, XmlTypeName, sourceType.Name)); if (SupportsType(destinationType)) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeFromString, XmlTypeName, destinationType.Name)); throw CreateInvalidClrMappingException(sourceType, destinationType); } return base.ChangeListType(value, destinationType, nsResolver); } private bool SupportsType(Type clrType) { if (clrType == BooleanType) return true; if (clrType == ByteType) return true; if (clrType == ByteArrayType) return true; if (clrType == DateTimeType) return true; if (clrType == DateTimeOffsetType) return true; if (clrType == DecimalType) return true; if (clrType == DoubleType) return true; if (clrType == Int16Type) return true; if (clrType == Int32Type) return true; if (clrType == Int64Type) return true; if (clrType == SByteType) return true; if (clrType == SingleType) return true; if (clrType == TimeSpanType) return true; if (clrType == UInt16Type) return true; if (clrType == UInt32Type) return true; if (clrType == UInt64Type) return true; if (clrType == UriType) return true; if (clrType == XmlQualifiedNameType) return true; return false; } } internal sealed class XmlAnyConverter : XmlBaseConverter { private XmlAnyConverter(XmlTypeCode typeCode) : base(typeCode) { } public static readonly XmlValueConverter Item = new XmlAnyConverter(XmlTypeCode.Item); public static readonly XmlValueConverter AnyAtomic = new XmlAnyConverter(XmlTypeCode.AnyAtomicType); #region AUTOGENERATED_XMLANYCONVERTER //----------------------------------------------- // ToBoolean //----------------------------------------------- public override bool ToBoolean(object value!!) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsBoolean; return (bool)ChangeTypeWildcardDestination(value, BooleanType, null); } //----------------------------------------------- // ToDateTime //----------------------------------------------- public override DateTime ToDateTime(object value!!) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsDateTime; return (DateTime)ChangeTypeWildcardDestination(value, DateTimeType, null); } //----------------------------------------------- // ToDateTimeOffset //----------------------------------------------- public override DateTimeOffset ToDateTimeOffset(object value!!) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return (DateTimeOffset)((XmlAtomicValue)value).ValueAs(DateTimeOffsetType); return (DateTimeOffset)ChangeTypeWildcardDestination(value, DateTimeOffsetType, null); } //----------------------------------------------- // ToDecimal //----------------------------------------------- public override decimal ToDecimal(object value!!) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((decimal)((XmlAtomicValue)value).ValueAs(DecimalType)); return (decimal)ChangeTypeWildcardDestination(value, DecimalType, null); } //----------------------------------------------- // ToDouble //----------------------------------------------- public override double ToDouble(object value!!) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsDouble; return (double)ChangeTypeWildcardDestination(value, DoubleType, null); } //----------------------------------------------- // ToInt32 //----------------------------------------------- public override int ToInt32(object value!!) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsInt; return (int)ChangeTypeWildcardDestination(value, Int32Type, null); } //----------------------------------------------- // ToInt64 //----------------------------------------------- public override long ToInt64(object value!!) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsLong; return (long)ChangeTypeWildcardDestination(value, Int64Type, null); } //----------------------------------------------- // ToSingle //----------------------------------------------- public override float ToSingle(object value!!) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((float)((XmlAtomicValue)value).ValueAs(SingleType)); return (float)ChangeTypeWildcardDestination(value, SingleType, null); } //----------------------------------------------- // ToString //----------------------------------------------- // This converter does not support conversions to String. //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(bool value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Boolean), (bool)value)); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(DateTime value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime), (DateTime)value)); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(decimal value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal), value)); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(double value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Double), (double)value)); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(int value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Int), (int)value)); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(long value, Type destinationType!!) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Long), (long)value)); return ChangeTypeWildcardSource(value, destinationType, null); } public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), (string)value)); return ChangeTypeWildcardSource(value, destinationType, nsResolver); } public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsBoolean; } if (destinationType == DateTimeType) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsDateTime; } if (destinationType == DateTimeOffsetType) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAs(DateTimeOffsetType); } if (destinationType == DecimalType) { if (sourceType == XmlAtomicValueType) return ((decimal)((XmlAtomicValue)value).ValueAs(DecimalType)); } if (destinationType == DoubleType) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsDouble; } if (destinationType == Int32Type) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsInt; } if (destinationType == Int64Type) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsLong; } if (destinationType == SingleType) { if (sourceType == XmlAtomicValueType) return ((float)((XmlAtomicValue)value).ValueAs(SingleType)); } if (destinationType == XmlAtomicValueType) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); if (sourceType == BooleanType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Boolean), (bool)value)); if (sourceType == ByteType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.UnsignedByte), value)); if (sourceType == ByteArrayType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Base64Binary), value)); if (sourceType == DateTimeType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime), (DateTime)value)); if (sourceType == DateTimeOffsetType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime), (DateTimeOffset)value)); if (sourceType == DecimalType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal), value)); if (sourceType == DoubleType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Double), (double)value)); if (sourceType == Int16Type) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Short), value)); if (sourceType == Int32Type) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Int), (int)value)); if (sourceType == Int64Type) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Long), (long)value)); if (sourceType == SByteType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Byte), value)); if (sourceType == SingleType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Float), value)); if (sourceType == StringType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), (string)value)); if (sourceType == TimeSpanType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Duration), value)); if (sourceType == UInt16Type) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.UnsignedShort), value)); if (sourceType == UInt32Type) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.UnsignedInt), value)); if (sourceType == UInt64Type) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.UnsignedLong), value)); if (IsDerivedFrom(sourceType, UriType)) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.AnyUri), value)); if (IsDerivedFrom(sourceType, XmlQualifiedNameType)) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.QName), value, nsResolver)); } if (destinationType == XPathItemType) { if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value); if (IsDerivedFrom(sourceType, XPathNavigatorType)) return ((XPathNavigator)value); } if (destinationType == XPathNavigatorType) { if (IsDerivedFrom(sourceType, XPathNavigatorType)) return ToNavigator((XPathNavigator)value); } if (destinationType == XPathItemType) return ((XPathItem)this.ChangeType(value, XmlAtomicValueType, nsResolver)); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAs(destinationType, nsResolver); return ChangeListType(value, destinationType, nsResolver); } //----------------------------------------------- // Helpers //----------------------------------------------- private object ChangeTypeWildcardDestination(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAs(destinationType, nsResolver); return ChangeListType(value, destinationType, nsResolver); } private object ChangeTypeWildcardSource(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { if (destinationType == XPathItemType) return ((XPathItem)this.ChangeType(value, XmlAtomicValueType, nsResolver)); return ChangeListType(value, destinationType, nsResolver); } #endregion /// <summary> /// Throw an exception if nodes are not allowed by this converter. /// </summary> private XPathNavigator ToNavigator(XPathNavigator nav) { if (TypeCode != XmlTypeCode.Item) throw CreateInvalidClrMappingException(XPathNavigatorType, XPathNavigatorType); return nav; } } internal sealed class XmlAnyListConverter : XmlListConverter { private XmlAnyListConverter(XmlBaseConverter atomicConverter) : base(atomicConverter) { } public static readonly XmlValueConverter ItemList = new XmlAnyListConverter((XmlBaseConverter)XmlAnyConverter.Item); public static readonly XmlValueConverter AnyAtomicList = new XmlAnyListConverter((XmlBaseConverter)XmlAnyConverter.AnyAtomic); //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { // If source value does not implement IEnumerable, or it is a string or byte[], if (!(value is IEnumerable) || value.GetType() == StringType || value.GetType() == ByteArrayType) { // Then create a list from it value = new object[] { value }; } return ChangeListType(value, destinationType, nsResolver); } } internal class XmlListConverter : XmlBaseConverter { protected XmlValueConverter? atomicConverter; protected XmlListConverter(XmlBaseConverter atomicConverter) : base(atomicConverter) { this.atomicConverter = atomicConverter; } protected XmlListConverter(XmlBaseConverter atomicConverter, Type clrTypeDefault) : base(atomicConverter, clrTypeDefault) { this.atomicConverter = atomicConverter; } protected XmlListConverter(XmlSchemaType schemaType) : base(schemaType) { } public static XmlValueConverter Create(XmlValueConverter atomicConverter) { if (atomicConverter == XmlUntypedConverter.Untyped) return XmlUntypedConverter.UntypedList; if (atomicConverter == XmlAnyConverter.Item) return XmlAnyListConverter.ItemList; if (atomicConverter == XmlAnyConverter.AnyAtomic) return XmlAnyListConverter.AnyAtomicList; Debug.Assert(!(atomicConverter is XmlListConverter) || ((XmlListConverter)atomicConverter).atomicConverter == null, "List converters should not be nested within one another."); return new XmlListConverter((XmlBaseConverter)atomicConverter); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { return ChangeListType(value, destinationType, nsResolver); } //------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------ protected override object ChangeListType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; // Input value must support IEnumerable and destination type should be IEnumerable, ICollection, IList, Type[], or String if (!(value is IEnumerable) || !IsListType(destinationType)) throw CreateInvalidClrMappingException(sourceType, destinationType); // Handle case where destination type is a string if (destinationType == StringType) { // Conversion from string to string is a no-op if (sourceType == StringType) return value; // Convert from list to string return ListAsString((IEnumerable)value, nsResolver); } // Handle case where source type is a string // Tokenize string and create a list out of resulting string tokens if (sourceType == StringType) value = StringAsList((string)value); if (destinationType.IsArray) { // Convert from source value to strongly-typed array; special-case each possible item type for performance Type? itemTypeDst = destinationType.GetElementType(); // Converting from object[] to object[] is not necessarily a no-op (i.e. xs:int* stored as an object[] // containing String values will need to be converted to an object[] containing Int32 values). if (itemTypeDst == ObjectType) return ToArray<object>(value, nsResolver); // For all types except object[], sourceType = destinationType is a no-op conversion if (sourceType == destinationType) return value; // Otherwise, iterate over values in source list, convert them to output item type, and store them in result array if (itemTypeDst == BooleanType) return ToArray<bool>(value, nsResolver); if (itemTypeDst == ByteType) return ToArray<byte>(value, nsResolver); if (itemTypeDst == ByteArrayType) return ToArray<byte[]>(value, nsResolver); if (itemTypeDst == DateTimeType) return ToArray<DateTime>(value, nsResolver); if (itemTypeDst == DateTimeOffsetType) return ToArray<DateTimeOffset>(value, nsResolver); if (itemTypeDst == DecimalType) return ToArray<decimal>(value, nsResolver); if (itemTypeDst == DoubleType) return ToArray<double>(value, nsResolver); if (itemTypeDst == Int16Type) return ToArray<short>(value, nsResolver); if (itemTypeDst == Int32Type) return ToArray<int>(value, nsResolver); if (itemTypeDst == Int64Type) return ToArray<long>(value, nsResolver); if (itemTypeDst == SByteType) return ToArray<sbyte>(value, nsResolver); if (itemTypeDst == SingleType) return ToArray<float>(value, nsResolver); if (itemTypeDst == StringType) return ToArray<string>(value, nsResolver); if (itemTypeDst == TimeSpanType) return ToArray<TimeSpan>(value, nsResolver); if (itemTypeDst == UInt16Type) return ToArray<ushort>(value, nsResolver); if (itemTypeDst == UInt32Type) return ToArray<uint>(value, nsResolver); if (itemTypeDst == UInt64Type) return ToArray<ulong>(value, nsResolver); if (itemTypeDst == UriType) return ToArray<Uri>(value, nsResolver); if (itemTypeDst == XmlAtomicValueType) return ToArray<XmlAtomicValue>(value, nsResolver); if (itemTypeDst == XmlQualifiedNameType) return ToArray<XmlQualifiedName>(value, nsResolver); if (itemTypeDst == XPathItemType) return ToArray<XPathItem>(value, nsResolver); if (itemTypeDst == XPathNavigatorType) return ToArray<XPathNavigator>(value, nsResolver); throw CreateInvalidClrMappingException(sourceType, destinationType); } // Destination type is IList, ICollection or IEnumerable // If source value is an array of values having the default representation, then conversion is a no-op if (sourceType == DefaultClrType && sourceType != ObjectArrayType) return value; return ToList(value, nsResolver); } /// <summary> /// Return true if "type" is one of the following: /// 1. IList, ICollection, IEnumerable /// 2. A strongly-typed array /// 3. A string /// </summary> private bool IsListType(Type type) { // IsClrListType returns true if "type" is one of the list interfaces if (type == IListType || type == ICollectionType || type == IEnumerableType || type == StringType) return true; return type.IsArray; } /// <summary> /// Convert "list" to an array of type T by iterating over each item in "list" and converting it to type "T" /// by invoking the atomic converter. /// </summary> private T[] ToArray<T>(object list, IXmlNamespaceResolver? nsResolver) { // IList --> Array<T> IList? listSrc = list as IList; if (listSrc != null) { T[] arrDst = new T[listSrc.Count]; for (int i = 0; i < listSrc.Count; i++) arrDst[i] = (T)this.atomicConverter!.ChangeType(listSrc[i]!, typeof(T), nsResolver); return arrDst; } // IEnumerable --> Array<T> IEnumerable enumSrc = (list as IEnumerable)!; Debug.Assert(enumSrc != null, "Value passed to ToArray must implement IEnumerable"); List<T> listDst = new List<T>(); foreach (object? value in enumSrc) listDst.Add((T)this.atomicConverter!.ChangeType(value!, typeof(T), nsResolver)); return listDst.ToArray(); } /// <summary> /// Convert "list" to an IList containing items in the atomic type's default representation. /// </summary> private IList ToList(object list, IXmlNamespaceResolver? nsResolver) { // IList --> object[] IList? listSrc = list as IList; if (listSrc != null) { object[] arrDst = new object[listSrc.Count]; for (int i = 0; i < listSrc.Count; i++) arrDst[i] = this.atomicConverter!.ChangeType(listSrc[i]!, ObjectType, nsResolver); return arrDst; } // IEnumerable --> List<object> IEnumerable enumSrc = (list as IEnumerable)!; Debug.Assert(enumSrc != null, "Value passed to ToArray must implement IEnumerable"); List<object> listDst = new List<object>(); foreach (object? value in enumSrc) listDst.Add(this.atomicConverter!.ChangeType(value!, ObjectType, nsResolver)); return listDst; } /// <summary> /// Tokenize "value" by splitting it on whitespace characters. Insert tokens into an ArrayList and return the list. /// </summary> private List<string> StringAsList(string value) { return new List<string>(XmlConvert.SplitString(value)); } /// <summary> /// Convert a list to a corresponding list of strings. Then concatenate the strings, which adjacent values delimited /// by a space character. /// </summary> private string ListAsString(IEnumerable list, IXmlNamespaceResolver? nsResolver) { StringBuilder bldr = new StringBuilder(); foreach (object? value in list) { // skip null values if (value != null) { // Separate values by single space character if (bldr.Length != 0) bldr.Append(' '); // Append string value of next item in the list bldr.Append(this.atomicConverter!.ToString(value, nsResolver)); } } return bldr.ToString(); } /// <summary> /// Create an InvalidCastException for cases where either "destinationType" or "sourceType" is not a supported CLR representation /// for this Xml type. /// </summary> private new Exception CreateInvalidClrMappingException(Type sourceType, Type destinationType) { if (sourceType == destinationType) return new InvalidCastException(SR.Format(SR.XmlConvert_TypeListBadMapping, XmlTypeName, sourceType.Name)); return new InvalidCastException(SR.Format(SR.XmlConvert_TypeListBadMapping2, XmlTypeName, sourceType.Name, destinationType.Name)); } } internal sealed class XmlUnionConverter : XmlBaseConverter { private readonly XmlValueConverter[] _converters; private readonly bool _hasAtomicMember, _hasListMember; private XmlUnionConverter(XmlSchemaType schemaType) : base(schemaType) { // Skip restrictions. It is safe to do that because this is a union, so it's not a built-in type while (schemaType.DerivedBy == XmlSchemaDerivationMethod.Restriction) schemaType = schemaType.BaseXmlSchemaType!; // Get a converter for each member type in the union Debug.Assert(schemaType.DerivedBy == XmlSchemaDerivationMethod.Union); XmlSchemaSimpleType[] memberTypes = ((XmlSchemaSimpleTypeUnion)((XmlSchemaSimpleType)schemaType).Content!).BaseMemberTypes!; _converters = new XmlValueConverter[memberTypes.Length]; for (int i = 0; i < memberTypes.Length; i++) { _converters[i] = memberTypes[i].ValueConverter; // Track whether this union's member types include a list type if (memberTypes[i].Datatype!.Variety == XmlSchemaDatatypeVariety.List) _hasListMember = true; else if (memberTypes[i].Datatype!.Variety == XmlSchemaDatatypeVariety.Atomic) _hasAtomicMember = true; } } public static XmlValueConverter Create(XmlSchemaType schemaType) { return new XmlUnionConverter(schemaType); } //----------------------------------------------- // ChangeType //----------------------------------------------- public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { Type sourceType = value.GetType(); // If source value is an XmlAtomicValue, then allow it to perform the conversion if (sourceType == XmlAtomicValueType && _hasAtomicMember) return ((XmlAtomicValue)value).ValueAs(destinationType, nsResolver); // If source value is an XmlAtomicValue[], then use item* converter if (sourceType == XmlAtomicValueArrayType && _hasListMember) return XmlAnyListConverter.ItemList.ChangeType(value, destinationType, nsResolver); // If source value is a string, then validate the string in order to determine the member type if (sourceType == StringType) { if (destinationType == StringType) return value; XsdSimpleValue simpleValue = (XsdSimpleValue)SchemaType!.Datatype!.ParseValue((string)value, new NameTable(), nsResolver, true); // Allow the member type to perform the conversion return simpleValue.XmlType.ValueConverter.ChangeType((string)value, destinationType, nsResolver); } throw CreateInvalidClrMappingException(sourceType, destinationType); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/nativeaot/SmokeTests/DynamicGenerics/GenericVirtualMethods.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; using System.Collections.Generic; using CoreFXTestLibrary; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; public static class GenericVirtualMethods { public interface IInterfaceWithGVM { string GVM<T>(object o); } class GVMClass : IInterfaceWithGVM { public virtual string GVM<T>(object o) { if (!(o is T)) return "FAIL"; else return "Called GVM<T>"; } } class GVMDerivedClass : GVMClass, IInterfaceWithGVM { public override string GVM<T>(object o) { if (o == null) return "FAIL"; if (!(o is T)) return "FAIL2"; else { if (o.GetType() != typeof(T) && o.GetType() != typeof(GVMDerivedClass)) return "FAIL3"; if (typeof(T) == typeof(int)) { return "Called Derived.GVM<int>"; } if (typeof(T) == typeof(GVMDerivedClass)) { return "Called Derived.GVM<GVMDerivedClass>"; } if (typeof(T) == typeof(GVMClass)) { return "Called Derived.GVM<GVMClass>"; } if (typeof(T) == typeof(string)) { return "Called Derived.GVM<string>"; } return "Called GVMStruct.GVM<Unknown>"; } } } struct GVMStruct : IInterfaceWithGVM { public string GVM<T>(object o) { if (o == null) return "FAIL"; if (!(o is T)) return "FAIL2"; else { if (o.GetType() != typeof(T)) return "FAIL3"; if (typeof(T) == typeof(int)) { return "Called GVMStruct.GVM<int>"; } if (typeof(T) == typeof(GVMDerivedClass)) { return "Called GVMStruct.GVM<GVMDerivedClass>"; } if (typeof(T) == typeof(string)) { return "Called GVMStruct.GVM<string>"; } return "Called GVMStruct.GVM<Unknown>"; } } } struct GVMStructGeneric<U> : IInterfaceWithGVM { public string GVM<T>(object o) { if (o == null) return "FAIL"; if (!(o is T)) return "FAIL2"; else { if (o.GetType() != typeof(T)) return "FAIL3"; if (typeof(U) == typeof(int)) { if (typeof(T) == typeof(int)) { return "Called GVMStructGeneric<int>.GVM<int>"; } if (typeof(T) == typeof(GVMDerivedClass)) { return "Called GVMStructGeneric<int>.GVM<GVMDerivedClass>"; } if (typeof(T) == typeof(string)) { return "Called GVMStructGeneric<int>.GVM<string>"; } return "Called GVMStructGeneric<int>.GVM<Unknown>"; } else if (typeof(U) == typeof(object)) { if (typeof(T) == typeof(int)) { return "Called GVMStructGeneric<object>.GVM<int>"; } if (typeof(T) == typeof(GVMDerivedClass)) { return "Called GVMStructGeneric<object>.GVM<GVMDerivedClass>"; } if (typeof(T) == typeof(string)) { return "Called GVMStructGeneric<object>.GVM<string>"; } return "Called GVMStructGeneric<object>.GVM<Unknown>"; } return "Called GVMStructGeneric<unknown>.GVM<Unknown>"; } } } [MethodImpl(MethodImplOptions.NoInlining)] public static void TestConstrainedCalls<T> (T t, string intString, string derivedClassString, string stringString) where T:IInterfaceWithGVM { Assert.AreEqual(intString, t.GVM<int>(54)); Assert.AreEqual(derivedClassString, t.GVM<GVMDerivedClass>(new GVMDerivedClass())); Assert.AreEqual(stringString, t.GVM<string>("testString")); } //TEST:GenericVirtualMethods.TestCalls [TestMethod] public static void TestCalls() { GVMClass testObject = new GVMDerivedClass(); IInterfaceWithGVM igvm = testObject; // Test normal GVM call Assert.AreEqual("Called Derived.GVM<int>", testObject.GVM<int>(54)); Assert.AreEqual("Called Derived.GVM<GVMClass>", testObject.GVM<GVMClass>(testObject)); Assert.AreEqual("Called Derived.GVM<string>", testObject.GVM<string>("testString")); Assert.AreEqual("Called Derived.GVM<int>", igvm.GVM<int>(54)); Assert.AreEqual("Called Derived.GVM<GVMDerivedClass>", igvm.GVM<GVMDerivedClass>(testObject)); Assert.AreEqual("Called Derived.GVM<string>", igvm.GVM<string>("testString")); // Test GVM delegate dispatch Func<object, string> d; d = testObject.GVM<int>; Assert.AreEqual("Called Derived.GVM<int>", d(54)); d = testObject.GVM<GVMClass>; Assert.AreEqual("Called Derived.GVM<GVMClass>", d(testObject)); d = testObject.GVM<string>; Assert.AreEqual("Called Derived.GVM<string>", d("testString")); d = igvm.GVM<int>; Assert.AreEqual("Called Derived.GVM<int>", d(54)); d = igvm.GVM<GVMClass>; Assert.AreEqual("Called Derived.GVM<GVMClass>", d(testObject)); d = igvm.GVM<string>; Assert.AreEqual("Called Derived.GVM<string>", d("testString")); TestConstrainedCalls<IInterfaceWithGVM>(igvm, "Called Derived.GVM<int>", "Called Derived.GVM<GVMDerivedClass>", "Called Derived.GVM<string>"); // GVM on structure IInterfaceWithGVM igvmStruct = new GVMStruct(); Assert.AreEqual("Called GVMStruct.GVM<int>", igvmStruct.GVM<int>(54)); Assert.AreEqual("Called GVMStruct.GVM<GVMDerivedClass>", igvmStruct.GVM<GVMDerivedClass>(testObject)); Assert.AreEqual("Called GVMStruct.GVM<string>", igvmStruct.GVM<string>("testString")); TestConstrainedCalls<GVMStruct>(new GVMStruct(), "Called GVMStruct.GVM<int>", "Called GVMStruct.GVM<GVMDerivedClass>", "Called GVMStruct.GVM<string>"); TestConstrainedCalls<IInterfaceWithGVM>(new GVMStruct(), "Called GVMStruct.GVM<int>", "Called GVMStruct.GVM<GVMDerivedClass>", "Called GVMStruct.GVM<string>"); // GVM on Generic Structure (struct instantiated over exact type) IInterfaceWithGVM igvmStructGenericOverInt = new GVMStructGeneric<int>(); Assert.AreEqual("Called GVMStructGeneric<int>.GVM<int>", igvmStructGenericOverInt.GVM<int>(54)); Assert.AreEqual("Called GVMStructGeneric<int>.GVM<GVMDerivedClass>", igvmStructGenericOverInt.GVM<GVMDerivedClass>(testObject)); Assert.AreEqual("Called GVMStructGeneric<int>.GVM<string>", igvmStructGenericOverInt.GVM<string>("testString")); TestConstrainedCalls<GVMStructGeneric<int>>(new GVMStructGeneric<int>(), "Called GVMStructGeneric<int>.GVM<int>", "Called GVMStructGeneric<int>.GVM<GVMDerivedClass>", "Called GVMStructGeneric<int>.GVM<string>"); TestConstrainedCalls<IInterfaceWithGVM>(new GVMStructGeneric<int>(), "Called GVMStructGeneric<int>.GVM<int>", "Called GVMStructGeneric<int>.GVM<GVMDerivedClass>", "Called GVMStructGeneric<int>.GVM<string>"); // GVM on Generic Structure (struct instantiated over reference type) IInterfaceWithGVM igvmStructGenericOverObject = new GVMStructGeneric<object>(); Assert.AreEqual("Called GVMStructGeneric<object>.GVM<int>", igvmStructGenericOverObject.GVM<int>(54)); Assert.AreEqual("Called GVMStructGeneric<object>.GVM<GVMDerivedClass>", igvmStructGenericOverObject.GVM<GVMDerivedClass>(testObject)); Assert.AreEqual("Called GVMStructGeneric<object>.GVM<string>", igvmStructGenericOverObject.GVM<string>("testString")); TestConstrainedCalls<GVMStructGeneric<object>>(new GVMStructGeneric<object>(), "Called GVMStructGeneric<object>.GVM<int>", "Called GVMStructGeneric<object>.GVM<GVMDerivedClass>", "Called GVMStructGeneric<object>.GVM<string>"); TestConstrainedCalls<IInterfaceWithGVM>(new GVMStructGeneric<object>(), "Called GVMStructGeneric<object>.GVM<int>", "Called GVMStructGeneric<object>.GVM<GVMDerivedClass>", "Called GVMStructGeneric<object>.GVM<string>"); } static class GenericStaticClass<T> { [MethodImpl(MethodImplOptions.NoInlining)] public static string Function() { if (typeof(T) == typeof(string)) { return "string"; } else if (typeof(T) == typeof(object)) { return "object"; } else { return "unknown"; } } } class ClassThatUsesGenericStaticClass<T> { [MethodImpl(MethodImplOptions.NoInlining)] public Func<string> GetTypeName() { return new Func<string>(GenericStaticClass<T>.Function); } } //TEST:GenericVirtualMethods.TestLdFtnToGetStaticMethodOnGenericType [TestMethod] public static void TestLdFtnToGetStaticMethodOnGenericType() { ClassThatUsesGenericStaticClass<object> testObject1 = new ClassThatUsesGenericStaticClass<object>(); ClassThatUsesGenericStaticClass<string> testObject2 = new ClassThatUsesGenericStaticClass<string>(); ClassThatUsesGenericStaticClass<Type> testObject3 = new ClassThatUsesGenericStaticClass<Type>(); string result; result = testObject1.GetTypeName()(); Console.WriteLine(result); Assert.IsTrue("object" == result); result = testObject2.GetTypeName()(); Console.WriteLine(result); Assert.IsTrue("string" == result); result = testObject3.GetTypeName()(); Console.WriteLine(result); Assert.IsTrue("unknown" == result); } public class GenericTypeWithThreeParameters<X, Y, Z> { public GenericTypeWithThreeParameters(int x) { } private GenericTypeWithThreeParameters(String s) { } public void SimpleMethod() { } public M SimpleGenericMethod<M, N>(X arg1, N arg2) { return default(M); } } public class GenericTypeWithTwoParametersWhereOnlyTheFirstIsActuallyUsed<T,U> { public static bool Method(object o) { return o is T; } } public class GenericTypeWhereNoParametersAreUsed<T> { public static bool Method(object o) { return o is string; } } public class ClassWithGenericMethod { public static bool MethodWithTwoGenericParametersWhereOnlyTheFirstIsUsed<T,U>(object o) { return o is T; } } //TEST:GenericVirtualMethods.TestLdFtnToInstanceGenericMethod [TestMethod] public static void TestLdFtnToInstanceGenericMethod() { GenericTypeWithThreeParameters<int, string, object> o = new GenericTypeWithThreeParameters<int, string, object>(123); Func<int, double, float> d = new Func<int, double, float>(o.SimpleGenericMethod<float, double>); Assert.AreEqual(default(float), d(1, 2)); Assert.IsNotNull(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d)); GenericTypeWithThreeParameters<int, string, Type> o2 = new GenericTypeWithThreeParameters<int, string, Type>(123); Func<int, double, float> d2 = new Func<int, double, float>(o2.SimpleGenericMethod<float, double>); Assert.AreEqual(default(float), d2(1, 2)); Assert.IsNotNull(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d2)); // Start checking to ensure that duplicate and/or empty generic dictionaries don't result in not having // the correct equality behavior // Empty Generic MethodDictionaries Assert.AreNotEqual(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d), System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d2)); // Duplicate Generic Method Dictionaries Func<object, bool> d7 = ClassWithGenericMethod.MethodWithTwoGenericParametersWhereOnlyTheFirstIsUsed<object, string>; Func<object, bool> d8 = ClassWithGenericMethod.MethodWithTwoGenericParametersWhereOnlyTheFirstIsUsed<object, Type>; Assert.IsNotNull(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d7)); Assert.IsNotNull(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d8)); Assert.AreNotEqual(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d7), System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d8)); // Empty Generic Type Dictionaries Func<object, bool> d3 = GenericTypeWhereNoParametersAreUsed<object>.Method; Func<object, bool> d4 = GenericTypeWhereNoParametersAreUsed<string>.Method; Assert.IsNotNull(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d3)); Assert.IsNotNull(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d4)); Assert.AreNotEqual(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d3), System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d4)); // Duplicate Generic Type Dictionary Func<object, bool> d5 = GenericTypeWithTwoParametersWhereOnlyTheFirstIsActuallyUsed<object, string>.Method; Func<object, bool> d6 = GenericTypeWithTwoParametersWhereOnlyTheFirstIsActuallyUsed<object, Type>.Method; Assert.IsNotNull(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d5)); Assert.IsNotNull(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d6)); Assert.AreNotEqual(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d5), System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d6)); } class Exception<T> : Exception { } class MyGenericTypeWithExceptionCatchingSupport<T> { [MethodImpl(MethodImplOptions.NoInlining)] public MyGenericTypeWithExceptionCatchingSupport(bool b) { object o = 3; try { if (b) throw new Exception<T>(); } catch (Exception<T> e) { o = e; } if (!(o is Exception<T>)) { throw new ArgumentException(); } } public IEnumerable<string> EnumerateStrings(bool b) { yield return "x"; List<string> strings = new List<string>(); strings.Add("Hmm"); try { bool x = !b; if (!x) throw new Exception<T>(); } catch (Exception<T> e) { strings.Add("caught - " + e.ToString()); } foreach (string s in strings) yield return s; } void ThrowGenericException() { throw new Exception<T>(); } Task ThrowGenericExceptionAsync() { Task t = Task.Run(new Action(ThrowGenericException)); return t; } public async Task<bool> AsyncMethod(bool b) { try { await ThrowGenericExceptionAsync(); } catch (Exception<T>) { return true; } return false; } public bool RunAsyncMethod(bool b) { Task<bool> t = AsyncMethod(b); t.Wait(); return t.Result; } } //TEST:GenericVirtualMethods.TestGenericExceptionType [TestMethod] public static void TestGenericExceptionType() { MyGenericTypeWithExceptionCatchingSupport<string> mgt = new MyGenericTypeWithExceptionCatchingSupport<string>(true); bool foundCaught = false; foreach (string s in mgt.EnumerateStrings(true)) { if (s.Contains("caught")) foundCaught = true; } Assert.IsTrue(foundCaught); Assert.IsTrue(mgt.RunAsyncMethod(true)); } class Base { } class Derived : Base { } interface IInVariant<in T> { string Func<U>(T t); } interface IOutVariant<out T> { string Func<U>(); } class ClassWithVariantGvms : IInVariant<object>, IInVariant<Base>, IOutVariant<Derived>, IOutVariant<Base> { string IInVariant<object>.Func<U>(object t) { return "CallOnObject"; } string IInVariant<Base>.Func<U>(Base t) { return "CallOnBase"; } string IOutVariant<Derived>.Func<U>() { return "CallOnDerived"; } string IOutVariant<Base>.Func<U>() { return "CallOnBase"; } } //TEST:GenericVirtualMethods.TestCoAndContraVariantCalls [TestMethod] public static void TestCoAndContraVariantCalls() { ClassWithVariantGvms testClass = new ClassWithVariantGvms(); Assert.AreEqual<string>("CallOnObject" , ((IInVariant<object>)testClass).Func<object>(new Derived())); Assert.AreEqual<string>("CallOnBase" , ((IInVariant<Base >)testClass).Func<object>(new Derived())); Assert.AreEqual<string>("CallOnObject" , ((IInVariant<Derived>)testClass).Func<object>(new Derived())); Assert.AreEqual<string>("CallOnDerived" , ((IOutVariant<object>)testClass).Func<object>()); Assert.AreEqual<string>("CallOnBase" , ((IOutVariant<Base>)testClass).Func<object>()); Assert.AreEqual<string>("CallOnDerived" , ((IOutVariant<Derived>)testClass).Func<object>()); } }
// 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; using System.Collections.Generic; using CoreFXTestLibrary; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; public static class GenericVirtualMethods { public interface IInterfaceWithGVM { string GVM<T>(object o); } class GVMClass : IInterfaceWithGVM { public virtual string GVM<T>(object o) { if (!(o is T)) return "FAIL"; else return "Called GVM<T>"; } } class GVMDerivedClass : GVMClass, IInterfaceWithGVM { public override string GVM<T>(object o) { if (o == null) return "FAIL"; if (!(o is T)) return "FAIL2"; else { if (o.GetType() != typeof(T) && o.GetType() != typeof(GVMDerivedClass)) return "FAIL3"; if (typeof(T) == typeof(int)) { return "Called Derived.GVM<int>"; } if (typeof(T) == typeof(GVMDerivedClass)) { return "Called Derived.GVM<GVMDerivedClass>"; } if (typeof(T) == typeof(GVMClass)) { return "Called Derived.GVM<GVMClass>"; } if (typeof(T) == typeof(string)) { return "Called Derived.GVM<string>"; } return "Called GVMStruct.GVM<Unknown>"; } } } struct GVMStruct : IInterfaceWithGVM { public string GVM<T>(object o) { if (o == null) return "FAIL"; if (!(o is T)) return "FAIL2"; else { if (o.GetType() != typeof(T)) return "FAIL3"; if (typeof(T) == typeof(int)) { return "Called GVMStruct.GVM<int>"; } if (typeof(T) == typeof(GVMDerivedClass)) { return "Called GVMStruct.GVM<GVMDerivedClass>"; } if (typeof(T) == typeof(string)) { return "Called GVMStruct.GVM<string>"; } return "Called GVMStruct.GVM<Unknown>"; } } } struct GVMStructGeneric<U> : IInterfaceWithGVM { public string GVM<T>(object o) { if (o == null) return "FAIL"; if (!(o is T)) return "FAIL2"; else { if (o.GetType() != typeof(T)) return "FAIL3"; if (typeof(U) == typeof(int)) { if (typeof(T) == typeof(int)) { return "Called GVMStructGeneric<int>.GVM<int>"; } if (typeof(T) == typeof(GVMDerivedClass)) { return "Called GVMStructGeneric<int>.GVM<GVMDerivedClass>"; } if (typeof(T) == typeof(string)) { return "Called GVMStructGeneric<int>.GVM<string>"; } return "Called GVMStructGeneric<int>.GVM<Unknown>"; } else if (typeof(U) == typeof(object)) { if (typeof(T) == typeof(int)) { return "Called GVMStructGeneric<object>.GVM<int>"; } if (typeof(T) == typeof(GVMDerivedClass)) { return "Called GVMStructGeneric<object>.GVM<GVMDerivedClass>"; } if (typeof(T) == typeof(string)) { return "Called GVMStructGeneric<object>.GVM<string>"; } return "Called GVMStructGeneric<object>.GVM<Unknown>"; } return "Called GVMStructGeneric<unknown>.GVM<Unknown>"; } } } [MethodImpl(MethodImplOptions.NoInlining)] public static void TestConstrainedCalls<T> (T t, string intString, string derivedClassString, string stringString) where T:IInterfaceWithGVM { Assert.AreEqual(intString, t.GVM<int>(54)); Assert.AreEqual(derivedClassString, t.GVM<GVMDerivedClass>(new GVMDerivedClass())); Assert.AreEqual(stringString, t.GVM<string>("testString")); } //TEST:GenericVirtualMethods.TestCalls [TestMethod] public static void TestCalls() { GVMClass testObject = new GVMDerivedClass(); IInterfaceWithGVM igvm = testObject; // Test normal GVM call Assert.AreEqual("Called Derived.GVM<int>", testObject.GVM<int>(54)); Assert.AreEqual("Called Derived.GVM<GVMClass>", testObject.GVM<GVMClass>(testObject)); Assert.AreEqual("Called Derived.GVM<string>", testObject.GVM<string>("testString")); Assert.AreEqual("Called Derived.GVM<int>", igvm.GVM<int>(54)); Assert.AreEqual("Called Derived.GVM<GVMDerivedClass>", igvm.GVM<GVMDerivedClass>(testObject)); Assert.AreEqual("Called Derived.GVM<string>", igvm.GVM<string>("testString")); // Test GVM delegate dispatch Func<object, string> d; d = testObject.GVM<int>; Assert.AreEqual("Called Derived.GVM<int>", d(54)); d = testObject.GVM<GVMClass>; Assert.AreEqual("Called Derived.GVM<GVMClass>", d(testObject)); d = testObject.GVM<string>; Assert.AreEqual("Called Derived.GVM<string>", d("testString")); d = igvm.GVM<int>; Assert.AreEqual("Called Derived.GVM<int>", d(54)); d = igvm.GVM<GVMClass>; Assert.AreEqual("Called Derived.GVM<GVMClass>", d(testObject)); d = igvm.GVM<string>; Assert.AreEqual("Called Derived.GVM<string>", d("testString")); TestConstrainedCalls<IInterfaceWithGVM>(igvm, "Called Derived.GVM<int>", "Called Derived.GVM<GVMDerivedClass>", "Called Derived.GVM<string>"); // GVM on structure IInterfaceWithGVM igvmStruct = new GVMStruct(); Assert.AreEqual("Called GVMStruct.GVM<int>", igvmStruct.GVM<int>(54)); Assert.AreEqual("Called GVMStruct.GVM<GVMDerivedClass>", igvmStruct.GVM<GVMDerivedClass>(testObject)); Assert.AreEqual("Called GVMStruct.GVM<string>", igvmStruct.GVM<string>("testString")); TestConstrainedCalls<GVMStruct>(new GVMStruct(), "Called GVMStruct.GVM<int>", "Called GVMStruct.GVM<GVMDerivedClass>", "Called GVMStruct.GVM<string>"); TestConstrainedCalls<IInterfaceWithGVM>(new GVMStruct(), "Called GVMStruct.GVM<int>", "Called GVMStruct.GVM<GVMDerivedClass>", "Called GVMStruct.GVM<string>"); // GVM on Generic Structure (struct instantiated over exact type) IInterfaceWithGVM igvmStructGenericOverInt = new GVMStructGeneric<int>(); Assert.AreEqual("Called GVMStructGeneric<int>.GVM<int>", igvmStructGenericOverInt.GVM<int>(54)); Assert.AreEqual("Called GVMStructGeneric<int>.GVM<GVMDerivedClass>", igvmStructGenericOverInt.GVM<GVMDerivedClass>(testObject)); Assert.AreEqual("Called GVMStructGeneric<int>.GVM<string>", igvmStructGenericOverInt.GVM<string>("testString")); TestConstrainedCalls<GVMStructGeneric<int>>(new GVMStructGeneric<int>(), "Called GVMStructGeneric<int>.GVM<int>", "Called GVMStructGeneric<int>.GVM<GVMDerivedClass>", "Called GVMStructGeneric<int>.GVM<string>"); TestConstrainedCalls<IInterfaceWithGVM>(new GVMStructGeneric<int>(), "Called GVMStructGeneric<int>.GVM<int>", "Called GVMStructGeneric<int>.GVM<GVMDerivedClass>", "Called GVMStructGeneric<int>.GVM<string>"); // GVM on Generic Structure (struct instantiated over reference type) IInterfaceWithGVM igvmStructGenericOverObject = new GVMStructGeneric<object>(); Assert.AreEqual("Called GVMStructGeneric<object>.GVM<int>", igvmStructGenericOverObject.GVM<int>(54)); Assert.AreEqual("Called GVMStructGeneric<object>.GVM<GVMDerivedClass>", igvmStructGenericOverObject.GVM<GVMDerivedClass>(testObject)); Assert.AreEqual("Called GVMStructGeneric<object>.GVM<string>", igvmStructGenericOverObject.GVM<string>("testString")); TestConstrainedCalls<GVMStructGeneric<object>>(new GVMStructGeneric<object>(), "Called GVMStructGeneric<object>.GVM<int>", "Called GVMStructGeneric<object>.GVM<GVMDerivedClass>", "Called GVMStructGeneric<object>.GVM<string>"); TestConstrainedCalls<IInterfaceWithGVM>(new GVMStructGeneric<object>(), "Called GVMStructGeneric<object>.GVM<int>", "Called GVMStructGeneric<object>.GVM<GVMDerivedClass>", "Called GVMStructGeneric<object>.GVM<string>"); } static class GenericStaticClass<T> { [MethodImpl(MethodImplOptions.NoInlining)] public static string Function() { if (typeof(T) == typeof(string)) { return "string"; } else if (typeof(T) == typeof(object)) { return "object"; } else { return "unknown"; } } } class ClassThatUsesGenericStaticClass<T> { [MethodImpl(MethodImplOptions.NoInlining)] public Func<string> GetTypeName() { return new Func<string>(GenericStaticClass<T>.Function); } } //TEST:GenericVirtualMethods.TestLdFtnToGetStaticMethodOnGenericType [TestMethod] public static void TestLdFtnToGetStaticMethodOnGenericType() { ClassThatUsesGenericStaticClass<object> testObject1 = new ClassThatUsesGenericStaticClass<object>(); ClassThatUsesGenericStaticClass<string> testObject2 = new ClassThatUsesGenericStaticClass<string>(); ClassThatUsesGenericStaticClass<Type> testObject3 = new ClassThatUsesGenericStaticClass<Type>(); string result; result = testObject1.GetTypeName()(); Console.WriteLine(result); Assert.IsTrue("object" == result); result = testObject2.GetTypeName()(); Console.WriteLine(result); Assert.IsTrue("string" == result); result = testObject3.GetTypeName()(); Console.WriteLine(result); Assert.IsTrue("unknown" == result); } public class GenericTypeWithThreeParameters<X, Y, Z> { public GenericTypeWithThreeParameters(int x) { } private GenericTypeWithThreeParameters(String s) { } public void SimpleMethod() { } public M SimpleGenericMethod<M, N>(X arg1, N arg2) { return default(M); } } public class GenericTypeWithTwoParametersWhereOnlyTheFirstIsActuallyUsed<T,U> { public static bool Method(object o) { return o is T; } } public class GenericTypeWhereNoParametersAreUsed<T> { public static bool Method(object o) { return o is string; } } public class ClassWithGenericMethod { public static bool MethodWithTwoGenericParametersWhereOnlyTheFirstIsUsed<T,U>(object o) { return o is T; } } //TEST:GenericVirtualMethods.TestLdFtnToInstanceGenericMethod [TestMethod] public static void TestLdFtnToInstanceGenericMethod() { GenericTypeWithThreeParameters<int, string, object> o = new GenericTypeWithThreeParameters<int, string, object>(123); Func<int, double, float> d = new Func<int, double, float>(o.SimpleGenericMethod<float, double>); Assert.AreEqual(default(float), d(1, 2)); Assert.IsNotNull(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d)); GenericTypeWithThreeParameters<int, string, Type> o2 = new GenericTypeWithThreeParameters<int, string, Type>(123); Func<int, double, float> d2 = new Func<int, double, float>(o2.SimpleGenericMethod<float, double>); Assert.AreEqual(default(float), d2(1, 2)); Assert.IsNotNull(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d2)); // Start checking to ensure that duplicate and/or empty generic dictionaries don't result in not having // the correct equality behavior // Empty Generic MethodDictionaries Assert.AreNotEqual(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d), System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d2)); // Duplicate Generic Method Dictionaries Func<object, bool> d7 = ClassWithGenericMethod.MethodWithTwoGenericParametersWhereOnlyTheFirstIsUsed<object, string>; Func<object, bool> d8 = ClassWithGenericMethod.MethodWithTwoGenericParametersWhereOnlyTheFirstIsUsed<object, Type>; Assert.IsNotNull(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d7)); Assert.IsNotNull(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d8)); Assert.AreNotEqual(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d7), System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d8)); // Empty Generic Type Dictionaries Func<object, bool> d3 = GenericTypeWhereNoParametersAreUsed<object>.Method; Func<object, bool> d4 = GenericTypeWhereNoParametersAreUsed<string>.Method; Assert.IsNotNull(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d3)); Assert.IsNotNull(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d4)); Assert.AreNotEqual(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d3), System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d4)); // Duplicate Generic Type Dictionary Func<object, bool> d5 = GenericTypeWithTwoParametersWhereOnlyTheFirstIsActuallyUsed<object, string>.Method; Func<object, bool> d6 = GenericTypeWithTwoParametersWhereOnlyTheFirstIsActuallyUsed<object, Type>.Method; Assert.IsNotNull(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d5)); Assert.IsNotNull(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d6)); Assert.AreNotEqual(System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d5), System.Reflection.RuntimeReflectionExtensions.GetMethodInfo(d6)); } class Exception<T> : Exception { } class MyGenericTypeWithExceptionCatchingSupport<T> { [MethodImpl(MethodImplOptions.NoInlining)] public MyGenericTypeWithExceptionCatchingSupport(bool b) { object o = 3; try { if (b) throw new Exception<T>(); } catch (Exception<T> e) { o = e; } if (!(o is Exception<T>)) { throw new ArgumentException(); } } public IEnumerable<string> EnumerateStrings(bool b) { yield return "x"; List<string> strings = new List<string>(); strings.Add("Hmm"); try { bool x = !b; if (!x) throw new Exception<T>(); } catch (Exception<T> e) { strings.Add("caught - " + e.ToString()); } foreach (string s in strings) yield return s; } void ThrowGenericException() { throw new Exception<T>(); } Task ThrowGenericExceptionAsync() { Task t = Task.Run(new Action(ThrowGenericException)); return t; } public async Task<bool> AsyncMethod(bool b) { try { await ThrowGenericExceptionAsync(); } catch (Exception<T>) { return true; } return false; } public bool RunAsyncMethod(bool b) { Task<bool> t = AsyncMethod(b); t.Wait(); return t.Result; } } //TEST:GenericVirtualMethods.TestGenericExceptionType [TestMethod] public static void TestGenericExceptionType() { MyGenericTypeWithExceptionCatchingSupport<string> mgt = new MyGenericTypeWithExceptionCatchingSupport<string>(true); bool foundCaught = false; foreach (string s in mgt.EnumerateStrings(true)) { if (s.Contains("caught")) foundCaught = true; } Assert.IsTrue(foundCaught); Assert.IsTrue(mgt.RunAsyncMethod(true)); } class Base { } class Derived : Base { } interface IInVariant<in T> { string Func<U>(T t); } interface IOutVariant<out T> { string Func<U>(); } class ClassWithVariantGvms : IInVariant<object>, IInVariant<Base>, IOutVariant<Derived>, IOutVariant<Base> { string IInVariant<object>.Func<U>(object t) { return "CallOnObject"; } string IInVariant<Base>.Func<U>(Base t) { return "CallOnBase"; } string IOutVariant<Derived>.Func<U>() { return "CallOnDerived"; } string IOutVariant<Base>.Func<U>() { return "CallOnBase"; } } //TEST:GenericVirtualMethods.TestCoAndContraVariantCalls [TestMethod] public static void TestCoAndContraVariantCalls() { ClassWithVariantGvms testClass = new ClassWithVariantGvms(); Assert.AreEqual<string>("CallOnObject" , ((IInVariant<object>)testClass).Func<object>(new Derived())); Assert.AreEqual<string>("CallOnBase" , ((IInVariant<Base >)testClass).Func<object>(new Derived())); Assert.AreEqual<string>("CallOnObject" , ((IInVariant<Derived>)testClass).Func<object>(new Derived())); Assert.AreEqual<string>("CallOnDerived" , ((IOutVariant<object>)testClass).Func<object>()); Assert.AreEqual<string>("CallOnBase" , ((IOutVariant<Base>)testClass).Func<object>()); Assert.AreEqual<string>("CallOnDerived" , ((IOutVariant<Derived>)testClass).Func<object>()); } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/Methodical/NaN/r4NaNrem_cs_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="r4NaNrem.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="r4NaNrem.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Threading.Tasks/tests/TaskFactory/TaskFactoryTests.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 System.Collections.Generic; using System.Text; namespace System.Threading.Tasks.Tests { public class TaskFactoryTests { #region Test Methods // Exercise functionality of TaskFactory and TaskFactory<TResult> [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public static void RunTaskFactoryTests() { TaskScheduler tm = TaskScheduler.Default; TaskCreationOptions tco = TaskCreationOptions.LongRunning; TaskFactory tf; TaskFactory<int> tfi; tf = new TaskFactory(); ExerciseTaskFactory(tf, TaskScheduler.Current, TaskCreationOptions.None, CancellationToken.None, TaskContinuationOptions.None); CancellationTokenSource cancellationSrc = new CancellationTokenSource(); tf = new TaskFactory(cancellationSrc.Token); var task = tf.StartNew(() => { }); task.Wait(); // Exercising TF(scheduler) tf = new TaskFactory(tm); ExerciseTaskFactory(tf, tm, TaskCreationOptions.None, CancellationToken.None, TaskContinuationOptions.None); //Exercising TF(TCrO, TCoO) tf = new TaskFactory(tco, TaskContinuationOptions.None); ExerciseTaskFactory(tf, TaskScheduler.Current, tco, CancellationToken.None, TaskContinuationOptions.None); // Exercising TF(scheduler, TCrO, TCoO)" tf = new TaskFactory(CancellationToken.None, tco, TaskContinuationOptions.None, tm); ExerciseTaskFactory(tf, tm, tco, CancellationToken.None, TaskContinuationOptions.None); //TaskFactory<TResult> tests // Exercising TF<int>() tfi = new TaskFactory<int>(); ExerciseTaskFactoryInt(tfi, TaskScheduler.Current, TaskCreationOptions.None, CancellationToken.None, TaskContinuationOptions.None); //Test constructor that accepts cancellationToken // Exercising TF<int>(cancellationToken) with a noncancelled token cancellationSrc = new CancellationTokenSource(); tfi = new TaskFactory<int>(cancellationSrc.Token); task = tfi.StartNew(() => 0); task.Wait(); // Exercising TF<int>(scheduler) tfi = new TaskFactory<int>(tm); ExerciseTaskFactoryInt(tfi, tm, TaskCreationOptions.None, CancellationToken.None, TaskContinuationOptions.None); // Exercising TF<int>(TCrO, TCoO) tfi = new TaskFactory<int>(tco, TaskContinuationOptions.None); ExerciseTaskFactoryInt(tfi, TaskScheduler.Current, tco, CancellationToken.None, TaskContinuationOptions.None); // Exercising TF<int>(scheduler, TCrO, TCoO) tfi = new TaskFactory<int>(CancellationToken.None, tco, TaskContinuationOptions.None, tm); ExerciseTaskFactoryInt(tfi, tm, tco, CancellationToken.None, TaskContinuationOptions.None); } // Exercise functionality of TaskFactory and TaskFactory<TResult> [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public static void RunTaskFactoryTests_Cancellation_Negative() { CancellationTokenSource cancellationSrc = new CancellationTokenSource(); //Test constructor that accepts cancellationToken cancellationSrc.Cancel(); TaskFactory tf = new TaskFactory(cancellationSrc.Token); var cancelledTask = tf.StartNew(() => { }); EnsureTaskCanceledExceptionThrown(() => cancelledTask.Wait()); // Exercising TF<int>(cancellationToken) with a cancelled token cancellationSrc.Cancel(); TaskFactory<int> tfi = new TaskFactory<int>(cancellationSrc.Token); cancelledTask = tfi.StartNew(() => 0); EnsureTaskCanceledExceptionThrown(() => cancelledTask.Wait()); } [Fact] public static void RunTaskFactoryExceptionTests() { TaskFactory tf = new TaskFactory(); // Checking top-level TF exception handling. Assert.Throws<ArgumentOutOfRangeException>( () => tf = new TaskFactory((TaskCreationOptions)0x40000000, TaskContinuationOptions.None)); Assert.Throws<ArgumentOutOfRangeException>( () => tf = new TaskFactory((TaskCreationOptions)0x100, TaskContinuationOptions.None)); Assert.Throws<ArgumentOutOfRangeException>( () => tf = new TaskFactory(TaskCreationOptions.None, (TaskContinuationOptions)0x40000000)); Assert.Throws<ArgumentOutOfRangeException>( () => tf = new TaskFactory(TaskCreationOptions.None, TaskContinuationOptions.NotOnFaulted)); Assert.Throws<ArgumentNullException>( () => { tf.FromAsync(null, (obj) => { }, TaskCreationOptions.None); }); // testing exceptions in null endMethods Assert.Throws<ArgumentNullException>( () => { tf.FromAsync(new myAsyncResult((obj) => { }, null), null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<int>(new myAsyncResult((obj) => { }, null), null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<int>(new myAsyncResult((obj) => { }, null), null, TaskCreationOptions.None, null); }); TaskFactory<int> tfi = new TaskFactory<int>(); // Checking top-level TF<int> exception handling. Assert.Throws<ArgumentOutOfRangeException>( () => tfi = new TaskFactory<int>((TaskCreationOptions)0x40000000, TaskContinuationOptions.None)); Assert.Throws<ArgumentOutOfRangeException>( () => tfi = new TaskFactory<int>((TaskCreationOptions)0x100, TaskContinuationOptions.None)); Assert.Throws<ArgumentOutOfRangeException>( () => tfi = new TaskFactory<int>(TaskCreationOptions.None, (TaskContinuationOptions)0x40000000)); Assert.Throws<ArgumentOutOfRangeException>( () => tfi = new TaskFactory<int>(TaskCreationOptions.None, TaskContinuationOptions.NotOnFaulted)); } [Fact] public static void RunTaskFactoryFromAsyncExceptionTests() { // Checking TF special FromAsync exception handling." FakeAsyncClass fac = new FakeAsyncClass(); TaskFactory tf; tf = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.None); Assert.Throws<ArgumentOutOfRangeException>( () => { tf.FromAsync(fac.StartWrite, fac.EndWrite, null /* state */); }); Assert.Throws<ArgumentOutOfRangeException>( () => { tf.FromAsync(fac.StartWrite, fac.EndWrite, "abc", null /* state */); }); Assert.Throws<ArgumentOutOfRangeException>( () => { tf.FromAsync(fac.StartWrite, fac.EndWrite, "abc", 2, null /* state */); }); Assert.Throws<ArgumentOutOfRangeException>( () => { tf.FromAsync(fac.StartWrite, fac.EndWrite, "abc", 0, 2, null /* state */); }); // testing exceptions in null endMethods or begin method //0 parameter Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<string>(fac.StartWrite, null, (object)null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<string>(null, fac.EndRead, (object)null, TaskCreationOptions.None); }); //1 parameter Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<string, int>(fac.StartWrite, null, "arg1", (object)null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<string, string>(null, fac.EndRead, "arg1", (object)null, TaskCreationOptions.None); }); //2 parameters Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<string, int, int>(fac.StartWrite, null, "arg1", 1, (object)null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<string, string, string>(null, fac.EndRead, "arg1", "arg2", (object)null, TaskCreationOptions.None); }); //3 parameters Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<string, int, int, int>(fac.StartWrite, null, "arg1", 1, 2, (object)null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<string, string, string, string>(null, fac.EndRead, "arg1", "arg2", "arg3", (object)null, TaskCreationOptions.None); }); // Checking TF<string> special FromAsync exception handling. TaskFactory<string> tfs = new TaskFactory<string>(TaskCreationOptions.LongRunning, TaskContinuationOptions.None); char[] charbuf = new char[128]; // Test that we throw on bad default task options Assert.Throws<ArgumentOutOfRangeException>( () => { tfs.FromAsync(fac.StartRead, fac.EndRead, null); }); Assert.Throws<ArgumentOutOfRangeException>( () => { tfs.FromAsync(fac.StartRead, fac.EndRead, 64, null); }); Assert.Throws<ArgumentOutOfRangeException>( () => { tfs.FromAsync(fac.StartRead, fac.EndRead, 64, charbuf, null); }); Assert.Throws<ArgumentOutOfRangeException>( () => { tfs.FromAsync(fac.StartRead, fac.EndRead, 64, charbuf, 0, null); }); // Test that we throw on null endMethod Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync(fac.StartRead, null, null); }); Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync(fac.StartRead, null, 64, null); }); Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync(fac.StartRead, null, 64, charbuf, null); }); Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync(fac.StartRead, null, 64, charbuf, 0, null); }); Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync(null, (obj) => "", TaskCreationOptions.None); }); //test null begin or end methods with various overloads //0 parameter Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync(fac.StartWrite, null, null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync(null, fac.EndRead, null, TaskCreationOptions.None); }); //1 parameter Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync<string>(fac.StartWrite, null, "arg1", null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync<string>(null, fac.EndRead, "arg1", null, TaskCreationOptions.None); }); //2 parameters Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync<string, int>(fac.StartWrite, null, "arg1", 2, null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync<string, int>(null, fac.EndRead, "arg1", 2, null, TaskCreationOptions.None); }); //3 parameters Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync<string, int, int>(fac.StartWrite, null, "arg1", 2, 3, null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync<string, int, int>(null, fac.EndRead, "arg1", 2, 3, null, TaskCreationOptions.None); }); } #endregion #region Helper Methods // Utility method for RunTaskFactoryTests(). private static void ExerciseTaskFactory(TaskFactory tf, TaskScheduler tmDefault, TaskCreationOptions tcoDefault, CancellationToken tokenDefault, TaskContinuationOptions continuationDefault) { TaskScheduler myTM = TaskScheduler.Default; TaskCreationOptions myTCO = TaskCreationOptions.LongRunning; TaskScheduler tmObserved = null; Task t; Task<int> f; // // Helper delegates to make the code below a lot shorter // Action init = delegate { tmObserved = null; }; Action void_delegate = delegate { tmObserved = TaskScheduler.Current; }; Action<object> voidState_delegate = delegate (object o) { tmObserved = TaskScheduler.Current; }; Func<int> int_delegate = delegate { tmObserved = TaskScheduler.Current; return 10; }; Func<object, int> intState_delegate = delegate (object o) { tmObserved = TaskScheduler.Current; return 10; }; //check Factory properties Assert.Equal(tf.CreationOptions, tcoDefault); if (tf.Scheduler != null) { Assert.Equal(tmDefault, tf.Scheduler); } Assert.Equal(tokenDefault, tf.CancellationToken); Assert.Equal(continuationDefault, tf.ContinuationOptions); // // StartNew(action) // init(); t = tf.StartNew(void_delegate); t.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(t.CreationOptions, tcoDefault); // // StartNew(action, TCO) // init(); t = tf.StartNew(void_delegate, myTCO); t.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(t.CreationOptions, myTCO); // // StartNew(action, CT, TCO, scheduler) // init(); t = tf.StartNew(void_delegate, CancellationToken.None, myTCO, myTM); t.Wait(); Assert.Equal(tmObserved, myTM); Assert.Equal(t.CreationOptions, myTCO); // // StartNew(action<object>, object) // init(); t = tf.StartNew(voidState_delegate, 100); t.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(t.CreationOptions, tcoDefault); // // StartNew(action<object>, object, TCO) // init(); t = tf.StartNew(voidState_delegate, 100, myTCO); t.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(t.CreationOptions, myTCO); // // StartNew(action<object>, object, CT, TCO, scheduler) // init(); t = tf.StartNew(voidState_delegate, 100, CancellationToken.None, myTCO, myTM); t.Wait(); Assert.Equal(tmObserved, myTM); Assert.Equal(t.CreationOptions, myTCO); // // StartNew(func) // init(); f = tf.StartNew(int_delegate); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func, token) // init(); f = tf.StartNew(int_delegate, tokenDefault); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func, options) // init(); f = tf.StartNew(int_delegate, myTCO); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, myTCO); // // StartNew(func, CT, options, scheduler) // init(); f = tf.StartNew(int_delegate, CancellationToken.None, myTCO, myTM); f.Wait(); Assert.Equal(tmObserved, myTM); Assert.Equal(f.CreationOptions, myTCO); // // StartNew(func<object>, object) // init(); f = tf.StartNew(intState_delegate, 100); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func<object>, object, token) // init(); f = tf.StartNew(intState_delegate, 100, tokenDefault); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func<object>, object, options) // init(); f = tf.StartNew(intState_delegate, 100, myTCO); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, myTCO); // // StartNew(func<object>, object, CT, options, scheduler) // init(); f = tf.StartNew(intState_delegate, 100, CancellationToken.None, myTCO, myTM); f.Wait(); Assert.Equal(tmObserved, myTM); Assert.Equal(f.CreationOptions, myTCO); } // Utility method for RunTaskFactoryTests(). private static void ExerciseTaskFactoryInt(TaskFactory<int> tf, TaskScheduler tmDefault, TaskCreationOptions tcoDefault, CancellationToken tokenDefault, TaskContinuationOptions continuationDefault) { TaskScheduler myTM = TaskScheduler.Default; TaskCreationOptions myTCO = TaskCreationOptions.LongRunning; TaskScheduler tmObserved = null; Task<int> f; // Helper delegates to make the code shorter. Action init = delegate { tmObserved = null; }; Func<int> int_delegate = delegate { tmObserved = TaskScheduler.Current; return 10; }; Func<object, int> intState_delegate = delegate (object o) { tmObserved = TaskScheduler.Current; return 10; }; //check Factory properties Assert.Equal(tf.CreationOptions, tcoDefault); if (tf.Scheduler != null) { Assert.Equal(tmDefault, tf.Scheduler); } Assert.Equal(tokenDefault, tf.CancellationToken); Assert.Equal(continuationDefault, tf.ContinuationOptions); // // StartNew(func) // init(); f = tf.StartNew(int_delegate); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func, options) // init(); f = tf.StartNew(int_delegate, myTCO); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, myTCO); // // StartNew(func, CT, options, scheduler) // init(); f = tf.StartNew(int_delegate, CancellationToken.None, myTCO, myTM); f.Wait(); Assert.Equal(tmObserved, myTM); Assert.Equal(f.CreationOptions, myTCO); // // StartNew(func<object>, object) // init(); f = tf.StartNew(intState_delegate, 100); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func<object>, object, token) // init(); f = tf.StartNew(intState_delegate, 100, tokenDefault); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func<object>, object, options) // init(); f = tf.StartNew(intState_delegate, 100, myTCO); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, myTCO); // // StartNew(func<object>, object, CT, options, scheduler) // init(); f = tf.StartNew(intState_delegate, 100, CancellationToken.None, myTCO, myTM); f.Wait(); Assert.Equal(tmObserved, myTM); Assert.Equal(f.CreationOptions, myTCO); } // Ensures that the specified action throws a AggregateException wrapping a TaskCanceledException private static void EnsureTaskCanceledExceptionThrown(Action action) { AggregateException ae = Assert.Throws<AggregateException>(action); Assert.Equal(typeof(TaskCanceledException), ae.InnerException.GetType()); } // This class is used in testing Factory tests. private class FakeAsyncClass { private List<char> _list = new List<char>(); public override string ToString() { StringBuilder sb = new StringBuilder(); lock (_list) { for (int i = 0; i < _list.Count; i++) sb.Append(_list[i]); } return sb.ToString(); } // Silly use of Write, but I wanted to test no-argument StartXXX handling. public IAsyncResult StartWrite(AsyncCallback cb, object o) { return StartWrite("", 0, 0, cb, o); } public IAsyncResult StartWrite(string s, AsyncCallback cb, object o) { return StartWrite(s, 0, s.Length, cb, o); } public IAsyncResult StartWrite(string s, int length, AsyncCallback cb, object o) { return StartWrite(s, 0, length, cb, o); } public IAsyncResult StartWrite(string s, int offset, int length, AsyncCallback cb, object o) { myAsyncResult mar = new myAsyncResult(cb, o); // Allow for exception throwing to test our handling of that. if (s == null) throw new ArgumentNullException(nameof(s)); Task t = Task.Factory.StartNew(delegate { try { lock (_list) { for (int i = 0; i < length; i++) _list.Add(s[i + offset]); } mar.Signal(); } catch (Exception e) { mar.Signal(e); } }); return mar; } public void EndWrite(IAsyncResult iar) { myAsyncResult mar = iar as myAsyncResult; mar.Wait(); if (mar.IsFaulted) throw (mar.Exception); } public IAsyncResult StartRead(AsyncCallback cb, object o) { return StartRead(128 /*=maxbytes*/, null, 0, cb, o); } public IAsyncResult StartRead(int maxBytes, AsyncCallback cb, object o) { return StartRead(maxBytes, null, 0, cb, o); } public IAsyncResult StartRead(int maxBytes, char[] buf, AsyncCallback cb, object o) { return StartRead(maxBytes, buf, 0, cb, o); } public IAsyncResult StartRead(int maxBytes, char[] buf, int offset, AsyncCallback cb, object o) { myAsyncResult mar = new myAsyncResult(cb, o); // Allow for exception throwing to test our handling of that. if (maxBytes == -1) throw new ArgumentException("Value was not valid", nameof(maxBytes)); Task t = Task.Factory.StartNew(delegate { StringBuilder sb = new StringBuilder(); int bytesRead = 0; try { lock (_list) { while ((_list.Count > 0) && (bytesRead < maxBytes)) { sb.Append(_list[0]); if (buf != null) { buf[offset] = _list[0]; offset++; } _list.RemoveAt(0); bytesRead++; } } mar.SignalState(sb.ToString()); } catch (Exception e) { mar.Signal(e); } }); return mar; } public string EndRead(IAsyncResult iar) { myAsyncResult mar = iar as myAsyncResult; if (mar.IsFaulted) throw (mar.Exception); return (string)mar.AsyncState; } public void ResetStateTo(string s) { _list.Clear(); for (int i = 0; i < s.Length; i++) _list.Add(s[i]); } } // This is an internal class used for a concrete IAsyncResult in the APM Factory tests. private class myAsyncResult : IAsyncResult { private volatile int _isCompleted; private ManualResetEvent _asyncWaitHandle; private AsyncCallback _callback; private object _asyncState; private Exception _exception; public myAsyncResult(AsyncCallback cb, object o) { _isCompleted = 0; _asyncWaitHandle = new ManualResetEvent(false); _callback = cb; _asyncState = o; _exception = null; } public bool IsCompleted { get { return (_isCompleted == 1); } } public bool CompletedSynchronously { get { return false; } } public WaitHandle AsyncWaitHandle { get { return _asyncWaitHandle; } } public object AsyncState { get { return _asyncState; } } public void Signal() { _isCompleted = 1; _asyncWaitHandle.Set(); if (_callback != null) _callback(this); } public void Signal(Exception e) { _exception = e; Signal(); } public void SignalState(object o) { _asyncState = o; Signal(); } public void Wait() { _asyncWaitHandle.WaitOne(); if (_exception != null) throw (_exception); } public bool IsFaulted { get { return ((_isCompleted == 1) && (_exception != null)); } } public Exception Exception { get { return _exception; } } } #endregion } }
// 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 System.Collections.Generic; using System.Text; namespace System.Threading.Tasks.Tests { public class TaskFactoryTests { #region Test Methods // Exercise functionality of TaskFactory and TaskFactory<TResult> [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public static void RunTaskFactoryTests() { TaskScheduler tm = TaskScheduler.Default; TaskCreationOptions tco = TaskCreationOptions.LongRunning; TaskFactory tf; TaskFactory<int> tfi; tf = new TaskFactory(); ExerciseTaskFactory(tf, TaskScheduler.Current, TaskCreationOptions.None, CancellationToken.None, TaskContinuationOptions.None); CancellationTokenSource cancellationSrc = new CancellationTokenSource(); tf = new TaskFactory(cancellationSrc.Token); var task = tf.StartNew(() => { }); task.Wait(); // Exercising TF(scheduler) tf = new TaskFactory(tm); ExerciseTaskFactory(tf, tm, TaskCreationOptions.None, CancellationToken.None, TaskContinuationOptions.None); //Exercising TF(TCrO, TCoO) tf = new TaskFactory(tco, TaskContinuationOptions.None); ExerciseTaskFactory(tf, TaskScheduler.Current, tco, CancellationToken.None, TaskContinuationOptions.None); // Exercising TF(scheduler, TCrO, TCoO)" tf = new TaskFactory(CancellationToken.None, tco, TaskContinuationOptions.None, tm); ExerciseTaskFactory(tf, tm, tco, CancellationToken.None, TaskContinuationOptions.None); //TaskFactory<TResult> tests // Exercising TF<int>() tfi = new TaskFactory<int>(); ExerciseTaskFactoryInt(tfi, TaskScheduler.Current, TaskCreationOptions.None, CancellationToken.None, TaskContinuationOptions.None); //Test constructor that accepts cancellationToken // Exercising TF<int>(cancellationToken) with a noncancelled token cancellationSrc = new CancellationTokenSource(); tfi = new TaskFactory<int>(cancellationSrc.Token); task = tfi.StartNew(() => 0); task.Wait(); // Exercising TF<int>(scheduler) tfi = new TaskFactory<int>(tm); ExerciseTaskFactoryInt(tfi, tm, TaskCreationOptions.None, CancellationToken.None, TaskContinuationOptions.None); // Exercising TF<int>(TCrO, TCoO) tfi = new TaskFactory<int>(tco, TaskContinuationOptions.None); ExerciseTaskFactoryInt(tfi, TaskScheduler.Current, tco, CancellationToken.None, TaskContinuationOptions.None); // Exercising TF<int>(scheduler, TCrO, TCoO) tfi = new TaskFactory<int>(CancellationToken.None, tco, TaskContinuationOptions.None, tm); ExerciseTaskFactoryInt(tfi, tm, tco, CancellationToken.None, TaskContinuationOptions.None); } // Exercise functionality of TaskFactory and TaskFactory<TResult> [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public static void RunTaskFactoryTests_Cancellation_Negative() { CancellationTokenSource cancellationSrc = new CancellationTokenSource(); //Test constructor that accepts cancellationToken cancellationSrc.Cancel(); TaskFactory tf = new TaskFactory(cancellationSrc.Token); var cancelledTask = tf.StartNew(() => { }); EnsureTaskCanceledExceptionThrown(() => cancelledTask.Wait()); // Exercising TF<int>(cancellationToken) with a cancelled token cancellationSrc.Cancel(); TaskFactory<int> tfi = new TaskFactory<int>(cancellationSrc.Token); cancelledTask = tfi.StartNew(() => 0); EnsureTaskCanceledExceptionThrown(() => cancelledTask.Wait()); } [Fact] public static void RunTaskFactoryExceptionTests() { TaskFactory tf = new TaskFactory(); // Checking top-level TF exception handling. Assert.Throws<ArgumentOutOfRangeException>( () => tf = new TaskFactory((TaskCreationOptions)0x40000000, TaskContinuationOptions.None)); Assert.Throws<ArgumentOutOfRangeException>( () => tf = new TaskFactory((TaskCreationOptions)0x100, TaskContinuationOptions.None)); Assert.Throws<ArgumentOutOfRangeException>( () => tf = new TaskFactory(TaskCreationOptions.None, (TaskContinuationOptions)0x40000000)); Assert.Throws<ArgumentOutOfRangeException>( () => tf = new TaskFactory(TaskCreationOptions.None, TaskContinuationOptions.NotOnFaulted)); Assert.Throws<ArgumentNullException>( () => { tf.FromAsync(null, (obj) => { }, TaskCreationOptions.None); }); // testing exceptions in null endMethods Assert.Throws<ArgumentNullException>( () => { tf.FromAsync(new myAsyncResult((obj) => { }, null), null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<int>(new myAsyncResult((obj) => { }, null), null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<int>(new myAsyncResult((obj) => { }, null), null, TaskCreationOptions.None, null); }); TaskFactory<int> tfi = new TaskFactory<int>(); // Checking top-level TF<int> exception handling. Assert.Throws<ArgumentOutOfRangeException>( () => tfi = new TaskFactory<int>((TaskCreationOptions)0x40000000, TaskContinuationOptions.None)); Assert.Throws<ArgumentOutOfRangeException>( () => tfi = new TaskFactory<int>((TaskCreationOptions)0x100, TaskContinuationOptions.None)); Assert.Throws<ArgumentOutOfRangeException>( () => tfi = new TaskFactory<int>(TaskCreationOptions.None, (TaskContinuationOptions)0x40000000)); Assert.Throws<ArgumentOutOfRangeException>( () => tfi = new TaskFactory<int>(TaskCreationOptions.None, TaskContinuationOptions.NotOnFaulted)); } [Fact] public static void RunTaskFactoryFromAsyncExceptionTests() { // Checking TF special FromAsync exception handling." FakeAsyncClass fac = new FakeAsyncClass(); TaskFactory tf; tf = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.None); Assert.Throws<ArgumentOutOfRangeException>( () => { tf.FromAsync(fac.StartWrite, fac.EndWrite, null /* state */); }); Assert.Throws<ArgumentOutOfRangeException>( () => { tf.FromAsync(fac.StartWrite, fac.EndWrite, "abc", null /* state */); }); Assert.Throws<ArgumentOutOfRangeException>( () => { tf.FromAsync(fac.StartWrite, fac.EndWrite, "abc", 2, null /* state */); }); Assert.Throws<ArgumentOutOfRangeException>( () => { tf.FromAsync(fac.StartWrite, fac.EndWrite, "abc", 0, 2, null /* state */); }); // testing exceptions in null endMethods or begin method //0 parameter Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<string>(fac.StartWrite, null, (object)null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<string>(null, fac.EndRead, (object)null, TaskCreationOptions.None); }); //1 parameter Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<string, int>(fac.StartWrite, null, "arg1", (object)null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<string, string>(null, fac.EndRead, "arg1", (object)null, TaskCreationOptions.None); }); //2 parameters Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<string, int, int>(fac.StartWrite, null, "arg1", 1, (object)null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<string, string, string>(null, fac.EndRead, "arg1", "arg2", (object)null, TaskCreationOptions.None); }); //3 parameters Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<string, int, int, int>(fac.StartWrite, null, "arg1", 1, 2, (object)null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tf.FromAsync<string, string, string, string>(null, fac.EndRead, "arg1", "arg2", "arg3", (object)null, TaskCreationOptions.None); }); // Checking TF<string> special FromAsync exception handling. TaskFactory<string> tfs = new TaskFactory<string>(TaskCreationOptions.LongRunning, TaskContinuationOptions.None); char[] charbuf = new char[128]; // Test that we throw on bad default task options Assert.Throws<ArgumentOutOfRangeException>( () => { tfs.FromAsync(fac.StartRead, fac.EndRead, null); }); Assert.Throws<ArgumentOutOfRangeException>( () => { tfs.FromAsync(fac.StartRead, fac.EndRead, 64, null); }); Assert.Throws<ArgumentOutOfRangeException>( () => { tfs.FromAsync(fac.StartRead, fac.EndRead, 64, charbuf, null); }); Assert.Throws<ArgumentOutOfRangeException>( () => { tfs.FromAsync(fac.StartRead, fac.EndRead, 64, charbuf, 0, null); }); // Test that we throw on null endMethod Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync(fac.StartRead, null, null); }); Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync(fac.StartRead, null, 64, null); }); Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync(fac.StartRead, null, 64, charbuf, null); }); Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync(fac.StartRead, null, 64, charbuf, 0, null); }); Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync(null, (obj) => "", TaskCreationOptions.None); }); //test null begin or end methods with various overloads //0 parameter Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync(fac.StartWrite, null, null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync(null, fac.EndRead, null, TaskCreationOptions.None); }); //1 parameter Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync<string>(fac.StartWrite, null, "arg1", null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync<string>(null, fac.EndRead, "arg1", null, TaskCreationOptions.None); }); //2 parameters Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync<string, int>(fac.StartWrite, null, "arg1", 2, null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync<string, int>(null, fac.EndRead, "arg1", 2, null, TaskCreationOptions.None); }); //3 parameters Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync<string, int, int>(fac.StartWrite, null, "arg1", 2, 3, null, TaskCreationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { tfs.FromAsync<string, int, int>(null, fac.EndRead, "arg1", 2, 3, null, TaskCreationOptions.None); }); } #endregion #region Helper Methods // Utility method for RunTaskFactoryTests(). private static void ExerciseTaskFactory(TaskFactory tf, TaskScheduler tmDefault, TaskCreationOptions tcoDefault, CancellationToken tokenDefault, TaskContinuationOptions continuationDefault) { TaskScheduler myTM = TaskScheduler.Default; TaskCreationOptions myTCO = TaskCreationOptions.LongRunning; TaskScheduler tmObserved = null; Task t; Task<int> f; // // Helper delegates to make the code below a lot shorter // Action init = delegate { tmObserved = null; }; Action void_delegate = delegate { tmObserved = TaskScheduler.Current; }; Action<object> voidState_delegate = delegate (object o) { tmObserved = TaskScheduler.Current; }; Func<int> int_delegate = delegate { tmObserved = TaskScheduler.Current; return 10; }; Func<object, int> intState_delegate = delegate (object o) { tmObserved = TaskScheduler.Current; return 10; }; //check Factory properties Assert.Equal(tf.CreationOptions, tcoDefault); if (tf.Scheduler != null) { Assert.Equal(tmDefault, tf.Scheduler); } Assert.Equal(tokenDefault, tf.CancellationToken); Assert.Equal(continuationDefault, tf.ContinuationOptions); // // StartNew(action) // init(); t = tf.StartNew(void_delegate); t.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(t.CreationOptions, tcoDefault); // // StartNew(action, TCO) // init(); t = tf.StartNew(void_delegate, myTCO); t.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(t.CreationOptions, myTCO); // // StartNew(action, CT, TCO, scheduler) // init(); t = tf.StartNew(void_delegate, CancellationToken.None, myTCO, myTM); t.Wait(); Assert.Equal(tmObserved, myTM); Assert.Equal(t.CreationOptions, myTCO); // // StartNew(action<object>, object) // init(); t = tf.StartNew(voidState_delegate, 100); t.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(t.CreationOptions, tcoDefault); // // StartNew(action<object>, object, TCO) // init(); t = tf.StartNew(voidState_delegate, 100, myTCO); t.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(t.CreationOptions, myTCO); // // StartNew(action<object>, object, CT, TCO, scheduler) // init(); t = tf.StartNew(voidState_delegate, 100, CancellationToken.None, myTCO, myTM); t.Wait(); Assert.Equal(tmObserved, myTM); Assert.Equal(t.CreationOptions, myTCO); // // StartNew(func) // init(); f = tf.StartNew(int_delegate); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func, token) // init(); f = tf.StartNew(int_delegate, tokenDefault); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func, options) // init(); f = tf.StartNew(int_delegate, myTCO); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, myTCO); // // StartNew(func, CT, options, scheduler) // init(); f = tf.StartNew(int_delegate, CancellationToken.None, myTCO, myTM); f.Wait(); Assert.Equal(tmObserved, myTM); Assert.Equal(f.CreationOptions, myTCO); // // StartNew(func<object>, object) // init(); f = tf.StartNew(intState_delegate, 100); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func<object>, object, token) // init(); f = tf.StartNew(intState_delegate, 100, tokenDefault); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func<object>, object, options) // init(); f = tf.StartNew(intState_delegate, 100, myTCO); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, myTCO); // // StartNew(func<object>, object, CT, options, scheduler) // init(); f = tf.StartNew(intState_delegate, 100, CancellationToken.None, myTCO, myTM); f.Wait(); Assert.Equal(tmObserved, myTM); Assert.Equal(f.CreationOptions, myTCO); } // Utility method for RunTaskFactoryTests(). private static void ExerciseTaskFactoryInt(TaskFactory<int> tf, TaskScheduler tmDefault, TaskCreationOptions tcoDefault, CancellationToken tokenDefault, TaskContinuationOptions continuationDefault) { TaskScheduler myTM = TaskScheduler.Default; TaskCreationOptions myTCO = TaskCreationOptions.LongRunning; TaskScheduler tmObserved = null; Task<int> f; // Helper delegates to make the code shorter. Action init = delegate { tmObserved = null; }; Func<int> int_delegate = delegate { tmObserved = TaskScheduler.Current; return 10; }; Func<object, int> intState_delegate = delegate (object o) { tmObserved = TaskScheduler.Current; return 10; }; //check Factory properties Assert.Equal(tf.CreationOptions, tcoDefault); if (tf.Scheduler != null) { Assert.Equal(tmDefault, tf.Scheduler); } Assert.Equal(tokenDefault, tf.CancellationToken); Assert.Equal(continuationDefault, tf.ContinuationOptions); // // StartNew(func) // init(); f = tf.StartNew(int_delegate); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func, options) // init(); f = tf.StartNew(int_delegate, myTCO); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, myTCO); // // StartNew(func, CT, options, scheduler) // init(); f = tf.StartNew(int_delegate, CancellationToken.None, myTCO, myTM); f.Wait(); Assert.Equal(tmObserved, myTM); Assert.Equal(f.CreationOptions, myTCO); // // StartNew(func<object>, object) // init(); f = tf.StartNew(intState_delegate, 100); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func<object>, object, token) // init(); f = tf.StartNew(intState_delegate, 100, tokenDefault); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, tcoDefault); // // StartNew(func<object>, object, options) // init(); f = tf.StartNew(intState_delegate, 100, myTCO); f.Wait(); Assert.Equal(tmObserved, tmDefault); Assert.Equal(f.CreationOptions, myTCO); // // StartNew(func<object>, object, CT, options, scheduler) // init(); f = tf.StartNew(intState_delegate, 100, CancellationToken.None, myTCO, myTM); f.Wait(); Assert.Equal(tmObserved, myTM); Assert.Equal(f.CreationOptions, myTCO); } // Ensures that the specified action throws a AggregateException wrapping a TaskCanceledException private static void EnsureTaskCanceledExceptionThrown(Action action) { AggregateException ae = Assert.Throws<AggregateException>(action); Assert.Equal(typeof(TaskCanceledException), ae.InnerException.GetType()); } // This class is used in testing Factory tests. private class FakeAsyncClass { private List<char> _list = new List<char>(); public override string ToString() { StringBuilder sb = new StringBuilder(); lock (_list) { for (int i = 0; i < _list.Count; i++) sb.Append(_list[i]); } return sb.ToString(); } // Silly use of Write, but I wanted to test no-argument StartXXX handling. public IAsyncResult StartWrite(AsyncCallback cb, object o) { return StartWrite("", 0, 0, cb, o); } public IAsyncResult StartWrite(string s, AsyncCallback cb, object o) { return StartWrite(s, 0, s.Length, cb, o); } public IAsyncResult StartWrite(string s, int length, AsyncCallback cb, object o) { return StartWrite(s, 0, length, cb, o); } public IAsyncResult StartWrite(string s, int offset, int length, AsyncCallback cb, object o) { myAsyncResult mar = new myAsyncResult(cb, o); // Allow for exception throwing to test our handling of that. if (s == null) throw new ArgumentNullException(nameof(s)); Task t = Task.Factory.StartNew(delegate { try { lock (_list) { for (int i = 0; i < length; i++) _list.Add(s[i + offset]); } mar.Signal(); } catch (Exception e) { mar.Signal(e); } }); return mar; } public void EndWrite(IAsyncResult iar) { myAsyncResult mar = iar as myAsyncResult; mar.Wait(); if (mar.IsFaulted) throw (mar.Exception); } public IAsyncResult StartRead(AsyncCallback cb, object o) { return StartRead(128 /*=maxbytes*/, null, 0, cb, o); } public IAsyncResult StartRead(int maxBytes, AsyncCallback cb, object o) { return StartRead(maxBytes, null, 0, cb, o); } public IAsyncResult StartRead(int maxBytes, char[] buf, AsyncCallback cb, object o) { return StartRead(maxBytes, buf, 0, cb, o); } public IAsyncResult StartRead(int maxBytes, char[] buf, int offset, AsyncCallback cb, object o) { myAsyncResult mar = new myAsyncResult(cb, o); // Allow for exception throwing to test our handling of that. if (maxBytes == -1) throw new ArgumentException("Value was not valid", nameof(maxBytes)); Task t = Task.Factory.StartNew(delegate { StringBuilder sb = new StringBuilder(); int bytesRead = 0; try { lock (_list) { while ((_list.Count > 0) && (bytesRead < maxBytes)) { sb.Append(_list[0]); if (buf != null) { buf[offset] = _list[0]; offset++; } _list.RemoveAt(0); bytesRead++; } } mar.SignalState(sb.ToString()); } catch (Exception e) { mar.Signal(e); } }); return mar; } public string EndRead(IAsyncResult iar) { myAsyncResult mar = iar as myAsyncResult; if (mar.IsFaulted) throw (mar.Exception); return (string)mar.AsyncState; } public void ResetStateTo(string s) { _list.Clear(); for (int i = 0; i < s.Length; i++) _list.Add(s[i]); } } // This is an internal class used for a concrete IAsyncResult in the APM Factory tests. private class myAsyncResult : IAsyncResult { private volatile int _isCompleted; private ManualResetEvent _asyncWaitHandle; private AsyncCallback _callback; private object _asyncState; private Exception _exception; public myAsyncResult(AsyncCallback cb, object o) { _isCompleted = 0; _asyncWaitHandle = new ManualResetEvent(false); _callback = cb; _asyncState = o; _exception = null; } public bool IsCompleted { get { return (_isCompleted == 1); } } public bool CompletedSynchronously { get { return false; } } public WaitHandle AsyncWaitHandle { get { return _asyncWaitHandle; } } public object AsyncState { get { return _asyncState; } } public void Signal() { _isCompleted = 1; _asyncWaitHandle.Set(); if (_callback != null) _callback(this); } public void Signal(Exception e) { _exception = e; Signal(); } public void SignalState(object o) { _asyncState = o; Signal(); } public void Wait() { _asyncWaitHandle.WaitOne(); if (_exception != null) throw (_exception); } public bool IsFaulted { get { return ((_isCompleted == 1) && (_exception != null)); } } public Exception Exception { get { return _exception; } } } #endregion } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/Regression/JitBlue/GitHub_12398/Github_12398.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // GitHub12398: Lowering is inconsistent in checking safety of RegOptional. using System; using System.Runtime.CompilerServices; struct S0 { public sbyte F1; public sbyte F2; } class GitHub_12398 { static int Main() { int result = 100; if (TestBinary() != 0) { Console.WriteLine("Failed TestBinary"); result = -1; } if (TestCompare()) { Console.WriteLine("Failed TestCompare"); result = -1; } if (TestMul() != 1) { Console.WriteLine("Failed TestMul"); result = -1; } if (TestMulTypeSize() != 0) { Console.WriteLine ("Failed TestMulTypeSize"); result = -1; } if (result == 100) { Console.WriteLine("PASSED"); } else { Console.WriteLine("FAILED"); } return result; } [MethodImpl(MethodImplOptions.NoInlining)] static long TestBinary() { long l = 0; long result = l ^ System.Threading.Interlocked.Exchange(ref l, 1); return result; } [MethodImpl(MethodImplOptions.NoInlining)] public static bool TestCompare() { long l = 0; bool result = l > System.Threading.Interlocked.Exchange(ref l, 1); return result; } [MethodImpl(MethodImplOptions.NoInlining)] public static long TestMul() { long l = 1; long result = l * System.Threading.Interlocked.Exchange(ref l, 0); return result; } [MethodImpl(MethodImplOptions.NoInlining)] public static int TestMulTypeSize() { S0 s = new S0(); s.F2--; int i = System.Threading.Volatile.Read(ref s.F1) * 100; return i; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // GitHub12398: Lowering is inconsistent in checking safety of RegOptional. using System; using System.Runtime.CompilerServices; struct S0 { public sbyte F1; public sbyte F2; } class GitHub_12398 { static int Main() { int result = 100; if (TestBinary() != 0) { Console.WriteLine("Failed TestBinary"); result = -1; } if (TestCompare()) { Console.WriteLine("Failed TestCompare"); result = -1; } if (TestMul() != 1) { Console.WriteLine("Failed TestMul"); result = -1; } if (TestMulTypeSize() != 0) { Console.WriteLine ("Failed TestMulTypeSize"); result = -1; } if (result == 100) { Console.WriteLine("PASSED"); } else { Console.WriteLine("FAILED"); } return result; } [MethodImpl(MethodImplOptions.NoInlining)] static long TestBinary() { long l = 0; long result = l ^ System.Threading.Interlocked.Exchange(ref l, 1); return result; } [MethodImpl(MethodImplOptions.NoInlining)] public static bool TestCompare() { long l = 0; bool result = l > System.Threading.Interlocked.Exchange(ref l, 1); return result; } [MethodImpl(MethodImplOptions.NoInlining)] public static long TestMul() { long l = 1; long result = l * System.Threading.Interlocked.Exchange(ref l, 0); return result; } [MethodImpl(MethodImplOptions.NoInlining)] public static int TestMulTypeSize() { S0 s = new S0(); s.F2--; int i = System.Threading.Volatile.Read(ref s.F1) * 100; return i; } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/Loader/classloader/TypeInitialization/CctorsWithSideEffects/CctorThrowInlinedStatic.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> </PropertyGroup> <ItemGroup> <Compile Include="CctorThrowInlinedStatic.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> </PropertyGroup> <ItemGroup> <Compile Include="CctorThrowInlinedStatic.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.IO.Ports/src/System/IO/Ports/SerialErrorReceivedEventArgs.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.IO.Ports { public class SerialErrorReceivedEventArgs : EventArgs { internal SerialErrorReceivedEventArgs(SerialError eventCode) { EventType = eventCode; } public SerialError EventType { get; private set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.IO.Ports { public class SerialErrorReceivedEventArgs : EventArgs { internal SerialErrorReceivedEventArgs(SerialError eventCode) { EventType = eventCode; } public SerialError EventType { get; private set; } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/Generics/Conversions/Boxing/box_isinst_unbox.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.Runtime.CompilerServices; public static class Tests { private static int returnCode = 100; [MethodImpl(MethodImplOptions.NoInlining)] public static int BoxIsInstUnbox1<T>(T t) => t is int n ? n : -1; [MethodImpl(MethodImplOptions.NoInlining)] public static int BoxIsInstUnbox2<T>(T t) => t is string n ? n.Length : -1; [MethodImpl(MethodImplOptions.NoInlining)] public static int BoxIsInstUnbox3<T>(T t) => t is Struct1<int> n ? n.a : -1; [MethodImpl(MethodImplOptions.NoInlining)] public static int BoxIsInstUnbox4<T>(T t) => t is Struct1<IDisposable> n ? n.GetHashCode() : -1; [MethodImpl(MethodImplOptions.NoInlining)] public static int BoxIsInstUnbox5<T>(T t) => t is Class1<int> n ? n.a : -1; [MethodImpl(MethodImplOptions.NoInlining)] public static int BoxIsInstUnbox6<T>(T t) => t is RefBase n ? n.a : -1; [MethodImpl(MethodImplOptions.NoInlining)] public static int BoxIsInstUnbox7<T>(T t) => t is object[] n ? n.Length : -1; public static void Expect(this int actual, int expected, [CallerLineNumber] int line = 0) { if (expected != actual) { Console.WriteLine($"{actual} != {expected}, line {line}."); returnCode++; } } public static int Main() { BoxIsInstUnbox1<int>(1).Expect(1); BoxIsInstUnbox1<uint>(1).Expect(-1); BoxIsInstUnbox1<byte>(1).Expect(-1); BoxIsInstUnbox1<long>(1).Expect(-1); BoxIsInstUnbox1<decimal>(1).Expect(-1); BoxIsInstUnbox1<int?>(1).Expect(1); BoxIsInstUnbox1<int?>(null).Expect(-1); BoxIsInstUnbox1<uint?>(1).Expect(-1); BoxIsInstUnbox1<string>("1").Expect(-1); BoxIsInstUnbox1<string>(1.ToString()).Expect(-1); BoxIsInstUnbox1<string>(null).Expect(-1); BoxIsInstUnbox1<Struct1<int>>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Struct1<int>?>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Struct1<uint>>(new Struct1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Struct2<IDisposable>>(new Struct2<IDisposable>()).Expect(-1); BoxIsInstUnbox1<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Class1<IDisposable>>(new Class1<IDisposable> { a = 1 }).Expect(-1); BoxIsInstUnbox1<string[]>(new string[1]).Expect(-1); BoxIsInstUnbox1<object[]>(new string[1]).Expect(-1); BoxIsInstUnbox1<IEnumerable<object>>(new string[1]).Expect(-1); BoxIsInstUnbox2<int>(1).Expect(-1); BoxIsInstUnbox2<uint>(1).Expect(-1); BoxIsInstUnbox2<byte>(1).Expect(-1); BoxIsInstUnbox2<long>(1).Expect(-1); BoxIsInstUnbox2<decimal>(1).Expect(-1); BoxIsInstUnbox2<int?>(1).Expect(-1); BoxIsInstUnbox2<int?>(null).Expect(-1); BoxIsInstUnbox2<uint?>(1).Expect(-1); BoxIsInstUnbox2<string>("1").Expect(1); BoxIsInstUnbox2<string>(1.ToString()).Expect(1); BoxIsInstUnbox2<string>(null).Expect(-1); BoxIsInstUnbox2<Struct1<int>>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Struct1<int>?>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Struct1<uint>>(new Struct1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Struct2<IDisposable>>(new Struct2<IDisposable>()).Expect(-1); BoxIsInstUnbox2<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Class1<IDisposable>>(new Class1<IDisposable> { a = 1 }).Expect(-1); BoxIsInstUnbox2<string[]>(new string[1]).Expect(-1); BoxIsInstUnbox2<object[]>(new string[1]).Expect(-1); BoxIsInstUnbox2<IEnumerable<object>>(new string[1]).Expect(-1); BoxIsInstUnbox3<int>(1).Expect(-1); BoxIsInstUnbox3<uint>(1).Expect(-1); BoxIsInstUnbox3<byte>(1).Expect(-1); BoxIsInstUnbox3<long>(1).Expect(-1); BoxIsInstUnbox3<decimal>(1).Expect(-1); BoxIsInstUnbox3<int?>(1).Expect(-1); BoxIsInstUnbox3<int?>(null).Expect(-1); BoxIsInstUnbox3<uint?>(1).Expect(-1); BoxIsInstUnbox3<string>("1").Expect(-1); BoxIsInstUnbox3<string>(1.ToString()).Expect(-1); BoxIsInstUnbox3<string>(null).Expect(-1); BoxIsInstUnbox3<Struct1<int>>(new Struct1<int> { a = 1 }).Expect(1); BoxIsInstUnbox3<Struct1<int>?>(new Struct1<int> { a = 1 }).Expect(1); BoxIsInstUnbox3<Struct1<uint>>(new Struct1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox3<Struct2<IDisposable>>(new Struct2<IDisposable>()).Expect(-1); BoxIsInstUnbox3<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox3<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox3<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox3<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox3<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox3<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox3<Class1<IDisposable>>(new Class1<IDisposable> { a = 1 }).Expect(-1); BoxIsInstUnbox3<string[]>(new string[1]).Expect(-1); BoxIsInstUnbox3<object[]>(new string[1]).Expect(-1); BoxIsInstUnbox3<IEnumerable<object>>(new string[1]).Expect(-1); BoxIsInstUnbox4<int>(1).Expect(-1); BoxIsInstUnbox4<uint>(1).Expect(-1); BoxIsInstUnbox4<byte>(1).Expect(-1); BoxIsInstUnbox4<long>(1).Expect(-1); BoxIsInstUnbox4<decimal>(1).Expect(-1); BoxIsInstUnbox4<int?>(1).Expect(-1); BoxIsInstUnbox4<int?>(null).Expect(-1); BoxIsInstUnbox4<uint?>(1).Expect(-1); BoxIsInstUnbox4<string>("1").Expect(-1); BoxIsInstUnbox4<string>(1.ToString()).Expect(-1); BoxIsInstUnbox4<string>(null).Expect(-1); BoxIsInstUnbox4<Struct1<int>>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Struct1<int>?>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Struct1<uint>>(new Struct1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Struct2<IDisposable>>(new Struct2<IDisposable>()).Expect(-1); BoxIsInstUnbox4<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Class1<IDisposable>>(new Class1<IDisposable> { a = 1 }).Expect(-1); BoxIsInstUnbox4<string[]>(new string[1]).Expect(-1); BoxIsInstUnbox4<object[]>(new string[1]).Expect(-1); BoxIsInstUnbox4<IEnumerable<object>>(new string[1]).Expect(-1); BoxIsInstUnbox5<int>(1).Expect(-1); BoxIsInstUnbox5<uint>(1).Expect(-1); BoxIsInstUnbox5<byte>(1).Expect(-1); BoxIsInstUnbox5<long>(1).Expect(-1); BoxIsInstUnbox5<decimal>(1).Expect(-1); BoxIsInstUnbox5<int?>(1).Expect(-1); BoxIsInstUnbox5<int?>(null).Expect(-1); BoxIsInstUnbox5<uint?>(1).Expect(-1); BoxIsInstUnbox5<string>("1").Expect(-1); BoxIsInstUnbox5<string>(1.ToString()).Expect(-1); BoxIsInstUnbox5<string>(null).Expect(-1); BoxIsInstUnbox5<Struct1<int>>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox5<Struct1<int>?>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox5<Struct1<uint>>(new Struct1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox5<Struct2<IDisposable>>(new Struct2<IDisposable>()).Expect(-1); BoxIsInstUnbox5<Class1<int>>(new Class1<int> { a = 1 }).Expect(1); BoxIsInstUnbox5<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox5<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox5<Class1<int>>(new Class1<int> { a = 1 }).Expect(1); BoxIsInstUnbox5<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox5<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox5<Class1<IDisposable>>(new Class1<IDisposable> { a = 1 }).Expect(-1); BoxIsInstUnbox5<string[]>(new string[1]).Expect(-1); BoxIsInstUnbox5<object[]>(new string[1]).Expect(-1); BoxIsInstUnbox5<IEnumerable<object>>(new string[1]).Expect(-1); BoxIsInstUnbox6<int>(1).Expect(-1); BoxIsInstUnbox6<uint>(1).Expect(-1); BoxIsInstUnbox6<byte>(1).Expect(-1); BoxIsInstUnbox6<long>(1).Expect(-1); BoxIsInstUnbox6<decimal>(1).Expect(-1); BoxIsInstUnbox6<int?>(1).Expect(-1); BoxIsInstUnbox6<int?>(null).Expect(-1); BoxIsInstUnbox6<uint?>(1).Expect(-1); BoxIsInstUnbox6<string>("1").Expect(-1); BoxIsInstUnbox6<string>(1.ToString()).Expect(-1); BoxIsInstUnbox6<string>(null).Expect(-1); BoxIsInstUnbox6<Struct1<int>>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox6<Struct1<int>?>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox6<Struct1<uint>>(new Struct1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox6<Struct2<IDisposable>>(new Struct2<IDisposable>()).Expect(-1); BoxIsInstUnbox6<Class1<int>>(new Class1<int> { a = 1 }).Expect(1); BoxIsInstUnbox6<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(1); BoxIsInstUnbox6<Class1<string>>(new Class1<string> { a = 1 }).Expect(1); BoxIsInstUnbox6<Class1<int>>(new Class1<int> { a = 1 }).Expect(1); BoxIsInstUnbox6<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(1); BoxIsInstUnbox6<Class1<string>>(new Class1<string> { a = 1 }).Expect(1); BoxIsInstUnbox6<Class1<IDisposable>>(new Class1<IDisposable> { a = 1 }).Expect(1); BoxIsInstUnbox6<string[]>(new string[1]).Expect(-1); BoxIsInstUnbox6<object[]>(new string[1]).Expect(-1); BoxIsInstUnbox6<IEnumerable<object>>(new string[1]).Expect(-1); BoxIsInstUnbox7<int>(1).Expect(-1); BoxIsInstUnbox7<uint>(1).Expect(-1); BoxIsInstUnbox7<byte>(1).Expect(-1); BoxIsInstUnbox7<long>(1).Expect(-1); BoxIsInstUnbox7<decimal>(1).Expect(-1); BoxIsInstUnbox7<int?>(1).Expect(-1); BoxIsInstUnbox7<int?>(null).Expect(-1); BoxIsInstUnbox7<uint?>(1).Expect(-1); BoxIsInstUnbox7<string>("1").Expect(-1); BoxIsInstUnbox7<string>(1.ToString()).Expect(-1); BoxIsInstUnbox7<string>(null).Expect(-1); BoxIsInstUnbox7<Struct1<int>>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Struct1<int>?>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Struct1<uint>>(new Struct1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Struct2<IDisposable>>(new Struct2<IDisposable>()).Expect(-1); BoxIsInstUnbox7<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Class1<IDisposable>>(new Class1<IDisposable> { a = 1 }).Expect(-1); BoxIsInstUnbox7<string[]>(new string[1]).Expect(1); BoxIsInstUnbox7<object[]>(new string[1]).Expect(1); BoxIsInstUnbox7<IEnumerable<object>>(new string[1]).Expect(1); return returnCode; } } public struct Struct1<T> { public T a; } public struct Struct2<T> { public T a; } public class RefBase : IDisposable { public int a; public void Dispose() { } } public class Class1<T> : RefBase { public T b; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; public static class Tests { private static int returnCode = 100; [MethodImpl(MethodImplOptions.NoInlining)] public static int BoxIsInstUnbox1<T>(T t) => t is int n ? n : -1; [MethodImpl(MethodImplOptions.NoInlining)] public static int BoxIsInstUnbox2<T>(T t) => t is string n ? n.Length : -1; [MethodImpl(MethodImplOptions.NoInlining)] public static int BoxIsInstUnbox3<T>(T t) => t is Struct1<int> n ? n.a : -1; [MethodImpl(MethodImplOptions.NoInlining)] public static int BoxIsInstUnbox4<T>(T t) => t is Struct1<IDisposable> n ? n.GetHashCode() : -1; [MethodImpl(MethodImplOptions.NoInlining)] public static int BoxIsInstUnbox5<T>(T t) => t is Class1<int> n ? n.a : -1; [MethodImpl(MethodImplOptions.NoInlining)] public static int BoxIsInstUnbox6<T>(T t) => t is RefBase n ? n.a : -1; [MethodImpl(MethodImplOptions.NoInlining)] public static int BoxIsInstUnbox7<T>(T t) => t is object[] n ? n.Length : -1; public static void Expect(this int actual, int expected, [CallerLineNumber] int line = 0) { if (expected != actual) { Console.WriteLine($"{actual} != {expected}, line {line}."); returnCode++; } } public static int Main() { BoxIsInstUnbox1<int>(1).Expect(1); BoxIsInstUnbox1<uint>(1).Expect(-1); BoxIsInstUnbox1<byte>(1).Expect(-1); BoxIsInstUnbox1<long>(1).Expect(-1); BoxIsInstUnbox1<decimal>(1).Expect(-1); BoxIsInstUnbox1<int?>(1).Expect(1); BoxIsInstUnbox1<int?>(null).Expect(-1); BoxIsInstUnbox1<uint?>(1).Expect(-1); BoxIsInstUnbox1<string>("1").Expect(-1); BoxIsInstUnbox1<string>(1.ToString()).Expect(-1); BoxIsInstUnbox1<string>(null).Expect(-1); BoxIsInstUnbox1<Struct1<int>>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Struct1<int>?>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Struct1<uint>>(new Struct1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Struct2<IDisposable>>(new Struct2<IDisposable>()).Expect(-1); BoxIsInstUnbox1<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox1<Class1<IDisposable>>(new Class1<IDisposable> { a = 1 }).Expect(-1); BoxIsInstUnbox1<string[]>(new string[1]).Expect(-1); BoxIsInstUnbox1<object[]>(new string[1]).Expect(-1); BoxIsInstUnbox1<IEnumerable<object>>(new string[1]).Expect(-1); BoxIsInstUnbox2<int>(1).Expect(-1); BoxIsInstUnbox2<uint>(1).Expect(-1); BoxIsInstUnbox2<byte>(1).Expect(-1); BoxIsInstUnbox2<long>(1).Expect(-1); BoxIsInstUnbox2<decimal>(1).Expect(-1); BoxIsInstUnbox2<int?>(1).Expect(-1); BoxIsInstUnbox2<int?>(null).Expect(-1); BoxIsInstUnbox2<uint?>(1).Expect(-1); BoxIsInstUnbox2<string>("1").Expect(1); BoxIsInstUnbox2<string>(1.ToString()).Expect(1); BoxIsInstUnbox2<string>(null).Expect(-1); BoxIsInstUnbox2<Struct1<int>>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Struct1<int>?>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Struct1<uint>>(new Struct1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Struct2<IDisposable>>(new Struct2<IDisposable>()).Expect(-1); BoxIsInstUnbox2<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox2<Class1<IDisposable>>(new Class1<IDisposable> { a = 1 }).Expect(-1); BoxIsInstUnbox2<string[]>(new string[1]).Expect(-1); BoxIsInstUnbox2<object[]>(new string[1]).Expect(-1); BoxIsInstUnbox2<IEnumerable<object>>(new string[1]).Expect(-1); BoxIsInstUnbox3<int>(1).Expect(-1); BoxIsInstUnbox3<uint>(1).Expect(-1); BoxIsInstUnbox3<byte>(1).Expect(-1); BoxIsInstUnbox3<long>(1).Expect(-1); BoxIsInstUnbox3<decimal>(1).Expect(-1); BoxIsInstUnbox3<int?>(1).Expect(-1); BoxIsInstUnbox3<int?>(null).Expect(-1); BoxIsInstUnbox3<uint?>(1).Expect(-1); BoxIsInstUnbox3<string>("1").Expect(-1); BoxIsInstUnbox3<string>(1.ToString()).Expect(-1); BoxIsInstUnbox3<string>(null).Expect(-1); BoxIsInstUnbox3<Struct1<int>>(new Struct1<int> { a = 1 }).Expect(1); BoxIsInstUnbox3<Struct1<int>?>(new Struct1<int> { a = 1 }).Expect(1); BoxIsInstUnbox3<Struct1<uint>>(new Struct1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox3<Struct2<IDisposable>>(new Struct2<IDisposable>()).Expect(-1); BoxIsInstUnbox3<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox3<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox3<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox3<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox3<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox3<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox3<Class1<IDisposable>>(new Class1<IDisposable> { a = 1 }).Expect(-1); BoxIsInstUnbox3<string[]>(new string[1]).Expect(-1); BoxIsInstUnbox3<object[]>(new string[1]).Expect(-1); BoxIsInstUnbox3<IEnumerable<object>>(new string[1]).Expect(-1); BoxIsInstUnbox4<int>(1).Expect(-1); BoxIsInstUnbox4<uint>(1).Expect(-1); BoxIsInstUnbox4<byte>(1).Expect(-1); BoxIsInstUnbox4<long>(1).Expect(-1); BoxIsInstUnbox4<decimal>(1).Expect(-1); BoxIsInstUnbox4<int?>(1).Expect(-1); BoxIsInstUnbox4<int?>(null).Expect(-1); BoxIsInstUnbox4<uint?>(1).Expect(-1); BoxIsInstUnbox4<string>("1").Expect(-1); BoxIsInstUnbox4<string>(1.ToString()).Expect(-1); BoxIsInstUnbox4<string>(null).Expect(-1); BoxIsInstUnbox4<Struct1<int>>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Struct1<int>?>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Struct1<uint>>(new Struct1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Struct2<IDisposable>>(new Struct2<IDisposable>()).Expect(-1); BoxIsInstUnbox4<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox4<Class1<IDisposable>>(new Class1<IDisposable> { a = 1 }).Expect(-1); BoxIsInstUnbox4<string[]>(new string[1]).Expect(-1); BoxIsInstUnbox4<object[]>(new string[1]).Expect(-1); BoxIsInstUnbox4<IEnumerable<object>>(new string[1]).Expect(-1); BoxIsInstUnbox5<int>(1).Expect(-1); BoxIsInstUnbox5<uint>(1).Expect(-1); BoxIsInstUnbox5<byte>(1).Expect(-1); BoxIsInstUnbox5<long>(1).Expect(-1); BoxIsInstUnbox5<decimal>(1).Expect(-1); BoxIsInstUnbox5<int?>(1).Expect(-1); BoxIsInstUnbox5<int?>(null).Expect(-1); BoxIsInstUnbox5<uint?>(1).Expect(-1); BoxIsInstUnbox5<string>("1").Expect(-1); BoxIsInstUnbox5<string>(1.ToString()).Expect(-1); BoxIsInstUnbox5<string>(null).Expect(-1); BoxIsInstUnbox5<Struct1<int>>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox5<Struct1<int>?>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox5<Struct1<uint>>(new Struct1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox5<Struct2<IDisposable>>(new Struct2<IDisposable>()).Expect(-1); BoxIsInstUnbox5<Class1<int>>(new Class1<int> { a = 1 }).Expect(1); BoxIsInstUnbox5<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox5<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox5<Class1<int>>(new Class1<int> { a = 1 }).Expect(1); BoxIsInstUnbox5<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox5<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox5<Class1<IDisposable>>(new Class1<IDisposable> { a = 1 }).Expect(-1); BoxIsInstUnbox5<string[]>(new string[1]).Expect(-1); BoxIsInstUnbox5<object[]>(new string[1]).Expect(-1); BoxIsInstUnbox5<IEnumerable<object>>(new string[1]).Expect(-1); BoxIsInstUnbox6<int>(1).Expect(-1); BoxIsInstUnbox6<uint>(1).Expect(-1); BoxIsInstUnbox6<byte>(1).Expect(-1); BoxIsInstUnbox6<long>(1).Expect(-1); BoxIsInstUnbox6<decimal>(1).Expect(-1); BoxIsInstUnbox6<int?>(1).Expect(-1); BoxIsInstUnbox6<int?>(null).Expect(-1); BoxIsInstUnbox6<uint?>(1).Expect(-1); BoxIsInstUnbox6<string>("1").Expect(-1); BoxIsInstUnbox6<string>(1.ToString()).Expect(-1); BoxIsInstUnbox6<string>(null).Expect(-1); BoxIsInstUnbox6<Struct1<int>>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox6<Struct1<int>?>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox6<Struct1<uint>>(new Struct1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox6<Struct2<IDisposable>>(new Struct2<IDisposable>()).Expect(-1); BoxIsInstUnbox6<Class1<int>>(new Class1<int> { a = 1 }).Expect(1); BoxIsInstUnbox6<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(1); BoxIsInstUnbox6<Class1<string>>(new Class1<string> { a = 1 }).Expect(1); BoxIsInstUnbox6<Class1<int>>(new Class1<int> { a = 1 }).Expect(1); BoxIsInstUnbox6<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(1); BoxIsInstUnbox6<Class1<string>>(new Class1<string> { a = 1 }).Expect(1); BoxIsInstUnbox6<Class1<IDisposable>>(new Class1<IDisposable> { a = 1 }).Expect(1); BoxIsInstUnbox6<string[]>(new string[1]).Expect(-1); BoxIsInstUnbox6<object[]>(new string[1]).Expect(-1); BoxIsInstUnbox6<IEnumerable<object>>(new string[1]).Expect(-1); BoxIsInstUnbox7<int>(1).Expect(-1); BoxIsInstUnbox7<uint>(1).Expect(-1); BoxIsInstUnbox7<byte>(1).Expect(-1); BoxIsInstUnbox7<long>(1).Expect(-1); BoxIsInstUnbox7<decimal>(1).Expect(-1); BoxIsInstUnbox7<int?>(1).Expect(-1); BoxIsInstUnbox7<int?>(null).Expect(-1); BoxIsInstUnbox7<uint?>(1).Expect(-1); BoxIsInstUnbox7<string>("1").Expect(-1); BoxIsInstUnbox7<string>(1.ToString()).Expect(-1); BoxIsInstUnbox7<string>(null).Expect(-1); BoxIsInstUnbox7<Struct1<int>>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Struct1<int>?>(new Struct1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Struct1<uint>>(new Struct1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Struct2<IDisposable>>(new Struct2<IDisposable>()).Expect(-1); BoxIsInstUnbox7<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Class1<int>>(new Class1<int> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Class1<uint>>(new Class1<uint> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Class1<string>>(new Class1<string> { a = 1 }).Expect(-1); BoxIsInstUnbox7<Class1<IDisposable>>(new Class1<IDisposable> { a = 1 }).Expect(-1); BoxIsInstUnbox7<string[]>(new string[1]).Expect(1); BoxIsInstUnbox7<object[]>(new string[1]).Expect(1); BoxIsInstUnbox7<IEnumerable<object>>(new string[1]).Expect(1); return returnCode; } } public struct Struct1<T> { public T a; } public struct Struct2<T> { public T a; } public class RefBase : IDisposable { public int a; public void Dispose() { } } public class Class1<T> : RefBase { public T b; }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/AssemblyTableNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection.Metadata.Ecma335; using Internal.JitInterface; using Internal.NativeFormat; using Internal.Runtime; using Internal.Text; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace ILCompiler.DependencyAnalysis.ReadyToRun { public class AssemblyTableNode : HeaderTableNode { private readonly List<AssemblyHeaderNode> _assemblyHeaders; public AssemblyTableNode(TargetDetails target) : base(target) { _assemblyHeaders = new List<AssemblyHeaderNode>(); } public void Add(AssemblyHeaderNode componentAssemblyHeader) { _assemblyHeaders.Add(componentAssemblyHeader); } public override void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(nameMangler.CompilationUnitPrefix); sb.Append("__ReadyToRunAssemblyTable"); } public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly); builder.AddSymbol(this); foreach (AssemblyHeaderNode assemblyHeader in _assemblyHeaders) { // TODO: IMAGE_DATA_DIRECTORY CorHeader - no support for embedded MSIL yet builder.EmitInt(0); builder.EmitInt(0); // IMAGE_DATA_DIRECTORY ReadyToRunHeader builder.EmitReloc(assemblyHeader, RelocType.IMAGE_REL_BASED_ADDR32NB); builder.EmitReloc(assemblyHeader, RelocType.IMAGE_REL_SYMBOL_SIZE); } return builder.ToObjectData(); } public override int ClassCode => 513314416; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection.Metadata.Ecma335; using Internal.JitInterface; using Internal.NativeFormat; using Internal.Runtime; using Internal.Text; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace ILCompiler.DependencyAnalysis.ReadyToRun { public class AssemblyTableNode : HeaderTableNode { private readonly List<AssemblyHeaderNode> _assemblyHeaders; public AssemblyTableNode(TargetDetails target) : base(target) { _assemblyHeaders = new List<AssemblyHeaderNode>(); } public void Add(AssemblyHeaderNode componentAssemblyHeader) { _assemblyHeaders.Add(componentAssemblyHeader); } public override void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(nameMangler.CompilationUnitPrefix); sb.Append("__ReadyToRunAssemblyTable"); } public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly); builder.AddSymbol(this); foreach (AssemblyHeaderNode assemblyHeader in _assemblyHeaders) { // TODO: IMAGE_DATA_DIRECTORY CorHeader - no support for embedded MSIL yet builder.EmitInt(0); builder.EmitInt(0); // IMAGE_DATA_DIRECTORY ReadyToRunHeader builder.EmitReloc(assemblyHeader, RelocType.IMAGE_REL_BASED_ADDR32NB); builder.EmitReloc(assemblyHeader, RelocType.IMAGE_REL_SYMBOL_SIZE); } return builder.ToObjectData(); } public override int ClassCode => 513314416; } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/Directed/StructPromote/Unsafe/ReadStructAsAnotherType.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.ComponentModel.Primitives/tests/System/ComponentModel/EventHandlerListTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.ComponentModel.Tests { public class EventHandlerListTests { [Fact] public void AddHandler_RemoveHandler_Roundtrips() { var list = new EventHandlerList(); Action action1 = () => Assert.True(false); Action action2 = () => Assert.False(true); // Add the first delegate to the first entry. list.AddHandler("key1", action1); Assert.Same(action1, list["key1"]); Assert.Null(list["key2"]); // Add the second delegate to the second entry. list.AddHandler("key2", action2); Assert.Same(action1, list["key1"]); Assert.Same(action2, list["key2"]); // Then remove the first delegate. list.RemoveHandler("key1", action1); Assert.Null(list["key1"]); Assert.Same(action2, list["key2"]); // And remove the second delegate. list.RemoveHandler("key2", action2); Assert.Null(list["key1"]); Assert.Null(list["key2"]); } [Fact] public void AddHandler_SameKey_CombinesDelegates() { var list = new EventHandlerList(); // Create two delegates that will increase total by different amounts. int total = 0; Action a1 = () => total += 1; Action a2 = () => total += 2; // Add both delegates for the same key and make sure we get them both out of the indexer. list.AddHandler("key1", a1); list.AddHandler("key1", a2); list["key1"].DynamicInvoke(); Assert.Equal(3, total); // Remove the first delegate and make sure the second delegate can still be retrieved. list.RemoveHandler("key1", a1); list["key1"].DynamicInvoke(); Assert.Equal(5, total); // Remove a delegate that was never in the list; nop. list.RemoveHandler("key1", new Action(() => { })); list["key1"].DynamicInvoke(); Assert.Equal(7, total); // Then remove the second delegate. list.RemoveHandler("key1", a2); Assert.Null(list["key1"]); } [Fact] public void AddHandlers_ValidList_AddsDelegates() { var list1 = new EventHandlerList(); var list2 = new EventHandlerList(); int total = 0; Action a1 = () => total += 1; Action a2 = () => total += 2; // Add the delegates to separate keys in the first list list1.AddHandler("key1", a1); list1.AddHandler("key2", a2); // Then add the first list to the second list2.AddHandlers(list1); // And make sure they contain the same entries Assert.Same(list1["key1"], list2["key1"]); Assert.Same(list1["key2"], list2["key2"]); } [Fact] public void AddHandlers_NullList_ThrowsArgumentNullException() { var list = new EventHandlerList(); AssertExtensions.Throws<ArgumentNullException, NullReferenceException>(() => list.AddHandlers(null)); } [Fact] public void Dispose_ClearsList() { var list = new EventHandlerList(); // Create two different delegate instances. Action action1 = () => Assert.True(false); Action action2 = () => Assert.False(true); // The list is still usable after disposal. for (int i = 0; i < 2; i++) { // Add the delegates list.AddHandler("key1", action1); list.AddHandler("key2", action2); Assert.Same(action1, list["key1"]); Assert.Same(action2, list["key2"]); // Dispose to clear the list. list.Dispose(); Assert.Null(list["key1"]); Assert.Null(list["key2"]); } } [Fact] public void Setter_AddsOrOverwrites() { var list = new EventHandlerList(); int total = 0; Action a1 = () => total += 1; Action a2 = () => total += 2; list["key1"] = a1; Assert.Same(a1, list["key1"]); list["key2"] = a2; Assert.Same(a2, list["key2"]); list["key2"] = a1; Assert.Same(a1, list["key1"]); } [Fact] public void RemoveHandler_EmptyList_Nop() { var list = new EventHandlerList(); list.RemoveHandler("key1", new Action(() => { })); list.RemoveHandler("key1", null); list.RemoveHandler(null, null); } [Fact] public void Indexer_SetNullKey_Nop() { var list = new EventHandlerList(); Action action = () => { }; list[null] = action; Assert.Same(action, list[null]); } [Fact] public void Indexer_SetNullValue_Nop() { var list = new EventHandlerList(); list["key1"] = null; Assert.Null(list["key1"]); } [Fact] public void Indexer_GetNoSuchKey_ReturnsNull() { var list = new EventHandlerList(); Assert.Null(list["key"]); Assert.Null(list[null]); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.ComponentModel.Tests { public class EventHandlerListTests { [Fact] public void AddHandler_RemoveHandler_Roundtrips() { var list = new EventHandlerList(); Action action1 = () => Assert.True(false); Action action2 = () => Assert.False(true); // Add the first delegate to the first entry. list.AddHandler("key1", action1); Assert.Same(action1, list["key1"]); Assert.Null(list["key2"]); // Add the second delegate to the second entry. list.AddHandler("key2", action2); Assert.Same(action1, list["key1"]); Assert.Same(action2, list["key2"]); // Then remove the first delegate. list.RemoveHandler("key1", action1); Assert.Null(list["key1"]); Assert.Same(action2, list["key2"]); // And remove the second delegate. list.RemoveHandler("key2", action2); Assert.Null(list["key1"]); Assert.Null(list["key2"]); } [Fact] public void AddHandler_SameKey_CombinesDelegates() { var list = new EventHandlerList(); // Create two delegates that will increase total by different amounts. int total = 0; Action a1 = () => total += 1; Action a2 = () => total += 2; // Add both delegates for the same key and make sure we get them both out of the indexer. list.AddHandler("key1", a1); list.AddHandler("key1", a2); list["key1"].DynamicInvoke(); Assert.Equal(3, total); // Remove the first delegate and make sure the second delegate can still be retrieved. list.RemoveHandler("key1", a1); list["key1"].DynamicInvoke(); Assert.Equal(5, total); // Remove a delegate that was never in the list; nop. list.RemoveHandler("key1", new Action(() => { })); list["key1"].DynamicInvoke(); Assert.Equal(7, total); // Then remove the second delegate. list.RemoveHandler("key1", a2); Assert.Null(list["key1"]); } [Fact] public void AddHandlers_ValidList_AddsDelegates() { var list1 = new EventHandlerList(); var list2 = new EventHandlerList(); int total = 0; Action a1 = () => total += 1; Action a2 = () => total += 2; // Add the delegates to separate keys in the first list list1.AddHandler("key1", a1); list1.AddHandler("key2", a2); // Then add the first list to the second list2.AddHandlers(list1); // And make sure they contain the same entries Assert.Same(list1["key1"], list2["key1"]); Assert.Same(list1["key2"], list2["key2"]); } [Fact] public void AddHandlers_NullList_ThrowsArgumentNullException() { var list = new EventHandlerList(); AssertExtensions.Throws<ArgumentNullException, NullReferenceException>(() => list.AddHandlers(null)); } [Fact] public void Dispose_ClearsList() { var list = new EventHandlerList(); // Create two different delegate instances. Action action1 = () => Assert.True(false); Action action2 = () => Assert.False(true); // The list is still usable after disposal. for (int i = 0; i < 2; i++) { // Add the delegates list.AddHandler("key1", action1); list.AddHandler("key2", action2); Assert.Same(action1, list["key1"]); Assert.Same(action2, list["key2"]); // Dispose to clear the list. list.Dispose(); Assert.Null(list["key1"]); Assert.Null(list["key2"]); } } [Fact] public void Setter_AddsOrOverwrites() { var list = new EventHandlerList(); int total = 0; Action a1 = () => total += 1; Action a2 = () => total += 2; list["key1"] = a1; Assert.Same(a1, list["key1"]); list["key2"] = a2; Assert.Same(a2, list["key2"]); list["key2"] = a1; Assert.Same(a1, list["key1"]); } [Fact] public void RemoveHandler_EmptyList_Nop() { var list = new EventHandlerList(); list.RemoveHandler("key1", new Action(() => { })); list.RemoveHandler("key1", null); list.RemoveHandler(null, null); } [Fact] public void Indexer_SetNullKey_Nop() { var list = new EventHandlerList(); Action action = () => { }; list[null] = action; Assert.Same(action, list[null]); } [Fact] public void Indexer_SetNullValue_Nop() { var list = new EventHandlerList(); list["key1"] = null; Assert.Null(list["key1"]); } [Fact] public void Indexer_GetNoSuchKey_ReturnsNull() { var list = new EventHandlerList(); Assert.Null(list["key"]); Assert.Null(list[null]); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/BrushType.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.Drawing.Drawing2D { internal enum BrushType { SolidColor = 0, HatchFill = 1, TextureFill = 2, PathGradient = 3, LinearGradient = 4 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Drawing.Drawing2D { internal enum BrushType { SolidColor = 0, HatchFill = 1, TextureFill = 2, PathGradient = 3, LinearGradient = 4 } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/AddSaturate.Vector64.Int32.Vector64.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.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 AddSaturate_Vector64_Int32_Vector64_UInt32() { var test = new SimpleBinaryOpTest__AddSaturate_Vector64_Int32_Vector64_UInt32(); 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__AddSaturate_Vector64_Int32_Vector64_UInt32 { 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(Int32[] inArray1, UInt32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); 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<Int32, 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 Vector64<Int32> _fld1; public Vector64<UInt32> _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<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddSaturate_Vector64_Int32_Vector64_UInt32 testClass) { var result = AdvSimd.Arm64.AddSaturate(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddSaturate_Vector64_Int32_Vector64_UInt32 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<UInt32>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.AddSaturate( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((UInt32*)(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<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector64<UInt32> _clsVar2; private Vector64<Int32> _fld1; private Vector64<UInt32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddSaturate_Vector64_Int32_Vector64_UInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); } public SimpleBinaryOpTest__AddSaturate_Vector64_Int32_Vector64_UInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.AddSaturate( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<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 = AdvSimd.Arm64.AddSaturate( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((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(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.AddSaturate), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.AddSaturate), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<UInt32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.AddSaturate( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector64<UInt32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.AddSaturate( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector64((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<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.AddSaturate(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((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.AddSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddSaturate_Vector64_Int32_Vector64_UInt32(); var result = AdvSimd.Arm64.AddSaturate(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__AddSaturate_Vector64_Int32_Vector64_UInt32(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector64<UInt32>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.AddSaturate( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((UInt32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.AddSaturate(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<UInt32>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.AddSaturate( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((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 = AdvSimd.Arm64.AddSaturate(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.AddSaturate( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector64((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(Vector64<Int32> op1, Vector64<UInt32> op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, UInt32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.AddSaturate(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.AddSaturate)}<Int32>(Vector64<Int32>, Vector64<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.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 AddSaturate_Vector64_Int32_Vector64_UInt32() { var test = new SimpleBinaryOpTest__AddSaturate_Vector64_Int32_Vector64_UInt32(); 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__AddSaturate_Vector64_Int32_Vector64_UInt32 { 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(Int32[] inArray1, UInt32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); 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<Int32, 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 Vector64<Int32> _fld1; public Vector64<UInt32> _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<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddSaturate_Vector64_Int32_Vector64_UInt32 testClass) { var result = AdvSimd.Arm64.AddSaturate(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddSaturate_Vector64_Int32_Vector64_UInt32 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<UInt32>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.AddSaturate( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((UInt32*)(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<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector64<UInt32> _clsVar2; private Vector64<Int32> _fld1; private Vector64<UInt32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddSaturate_Vector64_Int32_Vector64_UInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); } public SimpleBinaryOpTest__AddSaturate_Vector64_Int32_Vector64_UInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.AddSaturate( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<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 = AdvSimd.Arm64.AddSaturate( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((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(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.AddSaturate), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.AddSaturate), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<UInt32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.AddSaturate( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector64<UInt32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.AddSaturate( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector64((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<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.AddSaturate(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((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.AddSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddSaturate_Vector64_Int32_Vector64_UInt32(); var result = AdvSimd.Arm64.AddSaturate(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__AddSaturate_Vector64_Int32_Vector64_UInt32(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector64<UInt32>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.AddSaturate( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((UInt32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.AddSaturate(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<UInt32>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.AddSaturate( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((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 = AdvSimd.Arm64.AddSaturate(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.AddSaturate( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector64((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(Vector64<Int32> op1, Vector64<UInt32> op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, UInt32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.AddSaturate(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.AddSaturate)}<Int32>(Vector64<Int32>, Vector64<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,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/SIMD/StoreElement_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="StoreElement.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="StoreElement.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/coreclr/nativeaot/System.Private.CoreLib/src/System/ArgIterator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; namespace System { [StructLayout(LayoutKind.Sequential)] public ref struct ArgIterator { public ArgIterator(RuntimeArgumentHandle arglist) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } [CLSCompliant(false)] public unsafe ArgIterator(RuntimeArgumentHandle arglist, void* ptr) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } public void End() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } public override bool Equals(object? o) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } public override int GetHashCode() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } [CLSCompliant(false)] public System.TypedReference GetNextArg() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } [CLSCompliant(false)] public System.TypedReference GetNextArg(System.RuntimeTypeHandle rth) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } public unsafe System.RuntimeTypeHandle GetNextArgType() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } public int GetRemainingCount() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; namespace System { [StructLayout(LayoutKind.Sequential)] public ref struct ArgIterator { public ArgIterator(RuntimeArgumentHandle arglist) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } [CLSCompliant(false)] public unsafe ArgIterator(RuntimeArgumentHandle arglist, void* ptr) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } public void End() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } public override bool Equals(object? o) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } public override int GetHashCode() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } [CLSCompliant(false)] public System.TypedReference GetNextArg() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } [CLSCompliant(false)] public System.TypedReference GetNextArg(System.RuntimeTypeHandle rth) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } public unsafe System.RuntimeTypeHandle GetNextArgType() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } public int GetRemainingCount() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/HardwareIntrinsics/X86/Sse1/CompareScalarUnorderedEqual.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 CompareScalarUnorderedEqualBoolean() { var test = new BooleanBinaryOpTest__CompareScalarUnorderedEqualBoolean(); 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__CompareScalarUnorderedEqualBoolean { 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__CompareScalarUnorderedEqualBoolean testClass) { var result = Sse.CompareScalarUnorderedEqual(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } public void RunStructFldScenario_Load(BooleanBinaryOpTest__CompareScalarUnorderedEqualBoolean testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareScalarUnorderedEqual( 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__CompareScalarUnorderedEqualBoolean() { 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__CompareScalarUnorderedEqualBoolean() { 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.CompareScalarUnorderedEqual( 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.CompareScalarUnorderedEqual( 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.CompareScalarUnorderedEqual( 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.CompareScalarUnorderedEqual), 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.CompareScalarUnorderedEqual), 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.CompareScalarUnorderedEqual), 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.CompareScalarUnorderedEqual( _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.CompareScalarUnorderedEqual( 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.CompareScalarUnorderedEqual(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.CompareScalarUnorderedEqual(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.CompareScalarUnorderedEqual(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new BooleanBinaryOpTest__CompareScalarUnorderedEqualBoolean(); var result = Sse.CompareScalarUnorderedEqual(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new BooleanBinaryOpTest__CompareScalarUnorderedEqualBoolean(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse.CompareScalarUnorderedEqual( 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.CompareScalarUnorderedEqual(_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.CompareScalarUnorderedEqual( 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.CompareScalarUnorderedEqual(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.CompareScalarUnorderedEqual( 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.CompareScalarUnorderedEqual)}<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 CompareScalarUnorderedEqualBoolean() { var test = new BooleanBinaryOpTest__CompareScalarUnorderedEqualBoolean(); 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__CompareScalarUnorderedEqualBoolean { 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__CompareScalarUnorderedEqualBoolean testClass) { var result = Sse.CompareScalarUnorderedEqual(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } public void RunStructFldScenario_Load(BooleanBinaryOpTest__CompareScalarUnorderedEqualBoolean testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareScalarUnorderedEqual( 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__CompareScalarUnorderedEqualBoolean() { 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__CompareScalarUnorderedEqualBoolean() { 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.CompareScalarUnorderedEqual( 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.CompareScalarUnorderedEqual( 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.CompareScalarUnorderedEqual( 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.CompareScalarUnorderedEqual), 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.CompareScalarUnorderedEqual), 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.CompareScalarUnorderedEqual), 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.CompareScalarUnorderedEqual( _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.CompareScalarUnorderedEqual( 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.CompareScalarUnorderedEqual(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.CompareScalarUnorderedEqual(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.CompareScalarUnorderedEqual(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new BooleanBinaryOpTest__CompareScalarUnorderedEqualBoolean(); var result = Sse.CompareScalarUnorderedEqual(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new BooleanBinaryOpTest__CompareScalarUnorderedEqualBoolean(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse.CompareScalarUnorderedEqual( 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.CompareScalarUnorderedEqual(_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.CompareScalarUnorderedEqual( 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.CompareScalarUnorderedEqual(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.CompareScalarUnorderedEqual( 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.CompareScalarUnorderedEqual)}<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,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Runtime/tests/System/ObsoleteAttributeTests.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.Tests { public class ObsoleteAttributeTests { [Fact] public static void Ctor_Default() { var attribute = new ObsoleteAttribute(); Assert.Null(attribute.Message); Assert.False(attribute.IsError); Assert.Null(attribute.DiagnosticId); Assert.Null(attribute.UrlFormat); } [Theory] [InlineData(null, null)] [InlineData("", "BCL0006")] [InlineData("message", "")] public void Ctor_String_Id(string message, string id) { var attribute = new ObsoleteAttribute(message) { DiagnosticId = id }; Assert.Equal(message, attribute.Message); Assert.False(attribute.IsError); Assert.Equal(id, attribute.DiagnosticId); Assert.Null(attribute.UrlFormat); } [Theory] [InlineData(null, true, "")] [InlineData("", false, null)] [InlineData("message", true, "https://aka.ms/obsolete/{0}")] public void Ctor_String_Bool_Url(string message, bool error, string url) { var attribute = new ObsoleteAttribute(message, error) { UrlFormat = url }; Assert.Equal(message, attribute.Message); Assert.Equal(error, attribute.IsError); Assert.Null(attribute.DiagnosticId); Assert.Equal(url, attribute.UrlFormat); } } }
// 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.Tests { public class ObsoleteAttributeTests { [Fact] public static void Ctor_Default() { var attribute = new ObsoleteAttribute(); Assert.Null(attribute.Message); Assert.False(attribute.IsError); Assert.Null(attribute.DiagnosticId); Assert.Null(attribute.UrlFormat); } [Theory] [InlineData(null, null)] [InlineData("", "BCL0006")] [InlineData("message", "")] public void Ctor_String_Id(string message, string id) { var attribute = new ObsoleteAttribute(message) { DiagnosticId = id }; Assert.Equal(message, attribute.Message); Assert.False(attribute.IsError); Assert.Equal(id, attribute.DiagnosticId); Assert.Null(attribute.UrlFormat); } [Theory] [InlineData(null, true, "")] [InlineData("", false, null)] [InlineData("message", true, "https://aka.ms/obsolete/{0}")] public void Ctor_String_Bool_Url(string message, bool error, string url) { var attribute = new ObsoleteAttribute(message, error) { UrlFormat = url }; Assert.Equal(message, attribute.Message); Assert.Equal(error, attribute.IsError); Assert.Null(attribute.DiagnosticId); Assert.Equal(url, attribute.UrlFormat); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/coreclr/tools/Common/TypeSystem/Common/MethodDesc.Diagnostic.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.Text; namespace Internal.TypeSystem { partial class MethodDesc { public abstract string DiagnosticName { 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.Text; namespace Internal.TypeSystem { partial class MethodDesc { public abstract string DiagnosticName { get; } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/HardwareIntrinsics/General/Vector256/CreateElement.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 CreateElementSByte() { var test = new VectorCreate__CreateElementSByte(); // 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__CreateElementSByte { 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[] values = new SByte[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetSByte(); } Vector256<SByte> result = 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], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]); ValidateResult(result, values); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Type[] operandTypes = new Type[ElementCount]; SByte[] values = new SByte[ElementCount]; for (int i = 0; i < ElementCount; i++) { operandTypes[i] = typeof(SByte); values[i] = TestLibrary.Generator.GetSByte(); } object result = typeof(Vector256) .GetMethod(nameof(Vector256.Create), operandTypes) .Invoke(null, new object[] { 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], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31] }); ValidateResult((Vector256<SByte>)(result), values); } private void ValidateResult(Vector256<SByte> result, SByte[] expectedValues, [CallerMemberName] string method = "") { SByte[] resultElements = new SByte[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref resultElements[0]), result); ValidateResult(resultElements, expectedValues, method); } private void ValidateResult(SByte[] resultElements, SByte[] expectedValues, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != expectedValues[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256.Create(SByte): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", expectedValues)})"); 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 CreateElementSByte() { var test = new VectorCreate__CreateElementSByte(); // 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__CreateElementSByte { 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[] values = new SByte[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetSByte(); } Vector256<SByte> result = 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], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]); ValidateResult(result, values); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Type[] operandTypes = new Type[ElementCount]; SByte[] values = new SByte[ElementCount]; for (int i = 0; i < ElementCount; i++) { operandTypes[i] = typeof(SByte); values[i] = TestLibrary.Generator.GetSByte(); } object result = typeof(Vector256) .GetMethod(nameof(Vector256.Create), operandTypes) .Invoke(null, new object[] { 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], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31] }); ValidateResult((Vector256<SByte>)(result), values); } private void ValidateResult(Vector256<SByte> result, SByte[] expectedValues, [CallerMemberName] string method = "") { SByte[] resultElements = new SByte[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref resultElements[0]), result); ValidateResult(resultElements, expectedValues, method); } private void ValidateResult(SByte[] resultElements, SByte[] expectedValues, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != expectedValues[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256.Create(SByte): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", expectedValues)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.CodeDom/tests/System/CodeDom/CodeTypeDeclarationTests.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.Linq; using System.Reflection; using Xunit; namespace System.CodeDom.Tests { public class CodeTypeDeclarationTests : CodeTypeMemberTestBase<CodeTypeDeclaration> { [Fact] public void Ctor_Default() { var declaration = new CodeTypeDeclaration(); Assert.Empty(declaration.Name); Assert.True(declaration.IsClass); Assert.False(declaration.IsStruct); Assert.False(declaration.IsEnum); Assert.False(declaration.IsInterface); Assert.False(declaration.IsPartial); } [Theory] [MemberData(nameof(String_TestData))] public void Ctor_String(string name) { var declaration = new CodeTypeDeclaration(name); Assert.Equal(name ?? string.Empty, declaration.Name); } [Theory] [InlineData(true)] [InlineData(false)] public void IsClass_Set_Get_ReturnsTrue(bool value) { var declaration = new CodeTypeDeclaration(); declaration.IsClass = value; Assert.True(declaration.IsClass); Assert.False(declaration.IsStruct); Assert.False(declaration.IsEnum); Assert.False(declaration.IsInterface); } [Fact] public void IsClass_SetTrue_WasStruct_ReturnsTrue() { var declaration = new CodeTypeDeclaration() { IsStruct = true }; declaration.IsClass = true; Assert.False(declaration.IsStruct); Assert.False(declaration.IsEnum); Assert.False(declaration.IsInterface); } [Theory] [InlineData(true)] [InlineData(false)] public void IsStruct_Set_Get_ReturnsExpected(bool value) { var declaration = new CodeTypeDeclaration(); declaration.IsStruct = value; Assert.Equal(value, declaration.IsStruct); Assert.Equal(!value, declaration.IsClass); Assert.False(declaration.IsEnum); Assert.False(declaration.IsInterface); } [Theory] [InlineData(true)] [InlineData(false)] public void IsEnum_Set_Get_ReturnsExpected(bool value) { var declaration = new CodeTypeDeclaration(); declaration.IsEnum = value; Assert.Equal(value, declaration.IsEnum); Assert.Equal(!value, declaration.IsClass); Assert.False(declaration.IsStruct); Assert.False(declaration.IsInterface); } [Theory] [InlineData(true)] [InlineData(false)] public void IsInterface_Set_Get_ReturnsExpected(bool value) { var declaration = new CodeTypeDeclaration(); declaration.IsInterface = value; Assert.Equal(value, declaration.IsInterface); Assert.Equal(!value, declaration.IsClass); Assert.False(declaration.IsStruct); Assert.False(declaration.IsEnum); } [Theory] [InlineData(true)] [InlineData(false)] public void IsPartial_Set_Get_ReturnsExpected(bool value) { var declaration = new CodeTypeDeclaration(); declaration.IsPartial = value; Assert.Equal(value, declaration.IsPartial); } [Theory] [InlineData(TypeAttributes.Class - 1)] [InlineData(TypeAttributes.Class)] [InlineData(TypeAttributes.NotPublic | TypeAttributes.Public)] [InlineData((TypeAttributes)int.MaxValue)] public void TypeAttributes_Set_Get_ReturnExpected(TypeAttributes value) { var declaration = new CodeTypeDeclaration(); declaration.TypeAttributes = value; Assert.Equal(value, declaration.TypeAttributes); } [Fact] public void BaseTypes_AddMultiple_ReturnsExpected() { var declaration = new CodeTypeDeclaration(); CodeTypeReference type1 = new CodeTypeReference(typeof(int)); declaration.BaseTypes.Add(type1); Assert.Equal(new CodeTypeReference[] { type1 }, declaration.BaseTypes.Cast<CodeTypeReference>()); CodeTypeReference type2 = new CodeTypeReference(typeof(char)); declaration.BaseTypes.Add(type2); Assert.Equal(new CodeTypeReference[] { type1, type2 }, declaration.BaseTypes.Cast<CodeTypeReference>()); } [Fact] public void BaseTypes_Get_CallsPopulateBaseTypesOnce() { var declaration = new CodeTypeDeclaration(); bool calledPopulateBaseTypes = false; declaration.PopulateBaseTypes += (object sender, EventArgs args) => { calledPopulateBaseTypes = true; Assert.Same(declaration, sender); Assert.Equal(EventArgs.Empty, args); }; declaration.BaseTypes.Add(new CodeTypeReference(typeof(int))); Assert.True(calledPopulateBaseTypes); // Only calls PopulateBaseTypes once calledPopulateBaseTypes = false; declaration.BaseTypes.Add(new CodeTypeReference(typeof(char))); Assert.False(calledPopulateBaseTypes); } [Fact] public void Members_AddMultiple_ReturnsExpected() { var declaration = new CodeTypeDeclaration(); CodeTypeMember member1 = new CodeMemberField("Type", "Name1"); declaration.Members.Add(member1); Assert.Equal(new CodeTypeMember[] { member1 }, declaration.Members.Cast<CodeTypeMember>()); CodeTypeMember member2 = new CodeMemberField("Type", "Name1"); declaration.Members.Add(member2); Assert.Equal(new CodeTypeMember[] { member1, member2 }, declaration.Members.Cast<CodeTypeMember>()); } [Fact] public void Members_Get_CallsPopulateMembersOnce() { var declaration = new CodeTypeDeclaration(); bool calledPopulateMembers = false; declaration.PopulateMembers += (object sender, EventArgs args) => { calledPopulateMembers = true; Assert.Same(declaration, sender); Assert.Equal(EventArgs.Empty, args); }; declaration.Members.Add(new CodeMemberField("Type", "Name1")); Assert.True(calledPopulateMembers); // Only calls PopulateMembers once calledPopulateMembers = false; declaration.Members.Add(new CodeMemberField("Type", "Name2")); Assert.False(calledPopulateMembers); } [Fact] public void TypeParameters_AddMultiple_ReturnsExpected() { var declaration = new CodeTypeDeclaration(); CodeTypeParameter parameter1 = new CodeTypeParameter("Name1"); declaration.TypeParameters.Add(parameter1); Assert.Equal(new CodeTypeParameter[] { parameter1 }, declaration.TypeParameters.Cast<CodeTypeParameter>()); CodeTypeParameter parameter2 = new CodeTypeParameter("Name2"); declaration.TypeParameters.Add(parameter2); Assert.Equal(new CodeTypeParameter[] { parameter1, parameter2 }, declaration.TypeParameters.Cast<CodeTypeParameter>()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Linq; using System.Reflection; using Xunit; namespace System.CodeDom.Tests { public class CodeTypeDeclarationTests : CodeTypeMemberTestBase<CodeTypeDeclaration> { [Fact] public void Ctor_Default() { var declaration = new CodeTypeDeclaration(); Assert.Empty(declaration.Name); Assert.True(declaration.IsClass); Assert.False(declaration.IsStruct); Assert.False(declaration.IsEnum); Assert.False(declaration.IsInterface); Assert.False(declaration.IsPartial); } [Theory] [MemberData(nameof(String_TestData))] public void Ctor_String(string name) { var declaration = new CodeTypeDeclaration(name); Assert.Equal(name ?? string.Empty, declaration.Name); } [Theory] [InlineData(true)] [InlineData(false)] public void IsClass_Set_Get_ReturnsTrue(bool value) { var declaration = new CodeTypeDeclaration(); declaration.IsClass = value; Assert.True(declaration.IsClass); Assert.False(declaration.IsStruct); Assert.False(declaration.IsEnum); Assert.False(declaration.IsInterface); } [Fact] public void IsClass_SetTrue_WasStruct_ReturnsTrue() { var declaration = new CodeTypeDeclaration() { IsStruct = true }; declaration.IsClass = true; Assert.False(declaration.IsStruct); Assert.False(declaration.IsEnum); Assert.False(declaration.IsInterface); } [Theory] [InlineData(true)] [InlineData(false)] public void IsStruct_Set_Get_ReturnsExpected(bool value) { var declaration = new CodeTypeDeclaration(); declaration.IsStruct = value; Assert.Equal(value, declaration.IsStruct); Assert.Equal(!value, declaration.IsClass); Assert.False(declaration.IsEnum); Assert.False(declaration.IsInterface); } [Theory] [InlineData(true)] [InlineData(false)] public void IsEnum_Set_Get_ReturnsExpected(bool value) { var declaration = new CodeTypeDeclaration(); declaration.IsEnum = value; Assert.Equal(value, declaration.IsEnum); Assert.Equal(!value, declaration.IsClass); Assert.False(declaration.IsStruct); Assert.False(declaration.IsInterface); } [Theory] [InlineData(true)] [InlineData(false)] public void IsInterface_Set_Get_ReturnsExpected(bool value) { var declaration = new CodeTypeDeclaration(); declaration.IsInterface = value; Assert.Equal(value, declaration.IsInterface); Assert.Equal(!value, declaration.IsClass); Assert.False(declaration.IsStruct); Assert.False(declaration.IsEnum); } [Theory] [InlineData(true)] [InlineData(false)] public void IsPartial_Set_Get_ReturnsExpected(bool value) { var declaration = new CodeTypeDeclaration(); declaration.IsPartial = value; Assert.Equal(value, declaration.IsPartial); } [Theory] [InlineData(TypeAttributes.Class - 1)] [InlineData(TypeAttributes.Class)] [InlineData(TypeAttributes.NotPublic | TypeAttributes.Public)] [InlineData((TypeAttributes)int.MaxValue)] public void TypeAttributes_Set_Get_ReturnExpected(TypeAttributes value) { var declaration = new CodeTypeDeclaration(); declaration.TypeAttributes = value; Assert.Equal(value, declaration.TypeAttributes); } [Fact] public void BaseTypes_AddMultiple_ReturnsExpected() { var declaration = new CodeTypeDeclaration(); CodeTypeReference type1 = new CodeTypeReference(typeof(int)); declaration.BaseTypes.Add(type1); Assert.Equal(new CodeTypeReference[] { type1 }, declaration.BaseTypes.Cast<CodeTypeReference>()); CodeTypeReference type2 = new CodeTypeReference(typeof(char)); declaration.BaseTypes.Add(type2); Assert.Equal(new CodeTypeReference[] { type1, type2 }, declaration.BaseTypes.Cast<CodeTypeReference>()); } [Fact] public void BaseTypes_Get_CallsPopulateBaseTypesOnce() { var declaration = new CodeTypeDeclaration(); bool calledPopulateBaseTypes = false; declaration.PopulateBaseTypes += (object sender, EventArgs args) => { calledPopulateBaseTypes = true; Assert.Same(declaration, sender); Assert.Equal(EventArgs.Empty, args); }; declaration.BaseTypes.Add(new CodeTypeReference(typeof(int))); Assert.True(calledPopulateBaseTypes); // Only calls PopulateBaseTypes once calledPopulateBaseTypes = false; declaration.BaseTypes.Add(new CodeTypeReference(typeof(char))); Assert.False(calledPopulateBaseTypes); } [Fact] public void Members_AddMultiple_ReturnsExpected() { var declaration = new CodeTypeDeclaration(); CodeTypeMember member1 = new CodeMemberField("Type", "Name1"); declaration.Members.Add(member1); Assert.Equal(new CodeTypeMember[] { member1 }, declaration.Members.Cast<CodeTypeMember>()); CodeTypeMember member2 = new CodeMemberField("Type", "Name1"); declaration.Members.Add(member2); Assert.Equal(new CodeTypeMember[] { member1, member2 }, declaration.Members.Cast<CodeTypeMember>()); } [Fact] public void Members_Get_CallsPopulateMembersOnce() { var declaration = new CodeTypeDeclaration(); bool calledPopulateMembers = false; declaration.PopulateMembers += (object sender, EventArgs args) => { calledPopulateMembers = true; Assert.Same(declaration, sender); Assert.Equal(EventArgs.Empty, args); }; declaration.Members.Add(new CodeMemberField("Type", "Name1")); Assert.True(calledPopulateMembers); // Only calls PopulateMembers once calledPopulateMembers = false; declaration.Members.Add(new CodeMemberField("Type", "Name2")); Assert.False(calledPopulateMembers); } [Fact] public void TypeParameters_AddMultiple_ReturnsExpected() { var declaration = new CodeTypeDeclaration(); CodeTypeParameter parameter1 = new CodeTypeParameter("Name1"); declaration.TypeParameters.Add(parameter1); Assert.Equal(new CodeTypeParameter[] { parameter1 }, declaration.TypeParameters.Cast<CodeTypeParameter>()); CodeTypeParameter parameter2 = new CodeTypeParameter("Name2"); declaration.TypeParameters.Add(parameter2); Assert.Equal(new CodeTypeParameter[] { parameter1, parameter2 }, declaration.TypeParameters.Cast<CodeTypeParameter>()); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/HardwareIntrinsics/General/Vector256/GreaterThanAll.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 GreaterThanAllInt64() { var test = new VectorBooleanBinaryOpTest__GreaterThanAllInt64(); // 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 VectorBooleanBinaryOpTest__GreaterThanAllInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int64[] inArray1, Int64[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); 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<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 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<Int64> _fld1; public Vector256<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<Vector256<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__GreaterThanAllInt64 testClass) { var result = Vector256.GreaterThanAll(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector256<Int64> _clsVar1; private static Vector256<Int64> _clsVar2; private Vector256<Int64> _fld1; private Vector256<Int64> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__GreaterThanAllInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); } public VectorBooleanBinaryOpTest__GreaterThanAllInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<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, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.GreaterThanAll( Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_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.GreaterThanAll), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.GreaterThanAll), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int64)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.GreaterThanAll( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr); var result = Vector256.GreaterThanAll(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__GreaterThanAllInt64(); var result = Vector256.GreaterThanAll(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.GreaterThanAll(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.GreaterThanAll(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<Int64> op1, Vector256<Int64> op2, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int64[] left, Int64[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= (left[i] > right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.GreaterThanAll)}<Int64>(Vector256<Int64>, Vector256<Int64>): {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 GreaterThanAllInt64() { var test = new VectorBooleanBinaryOpTest__GreaterThanAllInt64(); // 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 VectorBooleanBinaryOpTest__GreaterThanAllInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int64[] inArray1, Int64[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); 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<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 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<Int64> _fld1; public Vector256<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<Vector256<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__GreaterThanAllInt64 testClass) { var result = Vector256.GreaterThanAll(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector256<Int64> _clsVar1; private static Vector256<Int64> _clsVar2; private Vector256<Int64> _fld1; private Vector256<Int64> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__GreaterThanAllInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); } public VectorBooleanBinaryOpTest__GreaterThanAllInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<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, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.GreaterThanAll( Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_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.GreaterThanAll), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.GreaterThanAll), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int64)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.GreaterThanAll( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr); var result = Vector256.GreaterThanAll(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__GreaterThanAllInt64(); var result = Vector256.GreaterThanAll(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.GreaterThanAll(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.GreaterThanAll(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<Int64> op1, Vector256<Int64> op2, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int64[] left, Int64[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= (left[i] > right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.GreaterThanAll)}<Int64>(Vector256<Int64>, Vector256<Int64>): {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,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CustomConverterTests/CustomConverterTests.ReadAhead.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class CustomConverterTests { private static void VerifyClassWithStringProperties(ClassWithStringProperties obj, int stringSize) { // The 10 properties will cause buffer boundary cases where the converter requires read-ahead. Assert.Equal(new string('0', stringSize), obj.MyString0); Assert.Equal(new string('1', stringSize), obj.MyString1); Assert.Equal(new string('2', stringSize), obj.MyString2); Assert.Equal(new string('3', stringSize), obj.MyString3); Assert.Equal(new string('4', stringSize), obj.MyString4); Assert.Equal(new string('5', stringSize), obj.MyString5); Assert.Equal(new string('6', stringSize), obj.MyString6); Assert.Equal(new string('7', stringSize), obj.MyString7); Assert.Equal(new string('8', stringSize), obj.MyString8); Assert.Equal(new string('9', stringSize), obj.MyString9); } private static void VerifyExtensionDataStringProperties(ClassWithExtensionData obj, int stringSize) { // The 10 properties will cause buffer boundary cases where the converter requires read-ahead. Assert.Equal(new string('0', stringSize), ((JsonElement)obj.MyOverflow["MyString0"]).ToString()); Assert.Equal(new string('1', stringSize), ((JsonElement)obj.MyOverflow["MyString1"]).ToString()); Assert.Equal(new string('2', stringSize), ((JsonElement)obj.MyOverflow["MyString2"]).ToString()); Assert.Equal(new string('3', stringSize), ((JsonElement)obj.MyOverflow["MyString3"]).ToString()); Assert.Equal(new string('4', stringSize), ((JsonElement)obj.MyOverflow["MyString4"]).ToString()); Assert.Equal(new string('5', stringSize), ((JsonElement)obj.MyOverflow["MyString5"]).ToString()); Assert.Equal(new string('6', stringSize), ((JsonElement)obj.MyOverflow["MyString6"]).ToString()); Assert.Equal(new string('7', stringSize), ((JsonElement)obj.MyOverflow["MyString7"]).ToString()); Assert.Equal(new string('8', stringSize), ((JsonElement)obj.MyOverflow["MyString8"]).ToString()); Assert.Equal(new string('9', stringSize), ((JsonElement)obj.MyOverflow["MyString9"]).ToString()); } private static string CreateTestStringProperty(int stringSize) { StringBuilder builder = new StringBuilder(); builder.Append("{"); for (int i = 0; i <= 9; i++) { builder.Append(@"""MyString"); builder.Append(i.ToString()); builder.Append(@""":"); AppendTestString(i, stringSize, builder); if (i != 9) { builder.Append(@","); } } builder.Append("}"); return builder.ToString(); } private static void AppendTestString(int i, int stringSize, StringBuilder builder) { builder.Append(@""""); builder.Append(new string(i.ToString()[0], stringSize)); builder.Append(@""""); } [Theory, InlineData(1), InlineData(10), InlineData(100), InlineData(1000), InlineData(10000), InlineData(25000)] public static void ReadAheadFromRoot(int stringSize) { string json = CreateTestStringProperty(stringSize); var options = new JsonSerializerOptions(); options.Converters.Add(new ClassWithStringPropertyConverter()); // Ensure buffer size is small as possible for read-ahead. options.DefaultBufferSize = 1; byte[] data = Encoding.UTF8.GetBytes(json); { MemoryStream stream = new MemoryStream(data); ClassWithStringProperties obj = JsonSerializer.DeserializeAsync<ClassWithStringProperties>(stream, options).Result; VerifyClassWithStringProperties(obj, stringSize); string jsonSerialized = JsonSerializer.Serialize(obj, options); Assert.Equal(json, jsonSerialized); } { // Verify extension data works with read-ahead. Extension data stored on JsonElement which has a custom converter. MemoryStream stream = new MemoryStream(data); ClassWithExtensionData obj = JsonSerializer.DeserializeAsync<ClassWithExtensionData>(stream, options).Result; VerifyExtensionDataStringProperties(obj, stringSize); string jsonSerialized = JsonSerializer.Serialize(obj, options); Assert.Equal(json, jsonSerialized); } } [Theory, InlineData(1), InlineData(10), InlineData(100), InlineData(1000), InlineData(10000)] public static void ReadAheadFromProperties(int stringSize) { string jsonProperties = CreateTestStringProperty(stringSize); StringBuilder builder = new StringBuilder(); builder.Append("{"); builder.Append(@"""Property1"":"); builder.Append(jsonProperties); builder.Append(@",""Property2"":"); builder.Append(jsonProperties); builder.Append(@",""Property3"":"); builder.Append(jsonProperties); builder.Append("}"); string json = builder.ToString(); var options = new JsonSerializerOptions(); options.Converters.Add(new ClassWithStringPropertyConverter()); // Ensure buffer size is small as possible for read-ahead. options.DefaultBufferSize = 1; byte[] data = Encoding.UTF8.GetBytes(json); { MemoryStream stream = new MemoryStream(data); ClassWithNoConverter obj = JsonSerializer.DeserializeAsync<ClassWithNoConverter>(stream, options).Result; VerifyClassWithStringProperties(obj.Property1, stringSize); VerifyClassWithStringProperties(obj.Property2, stringSize); VerifyClassWithStringProperties(obj.Property3, stringSize); string jsonSerialized = JsonSerializer.Serialize(obj, options); Assert.Equal(json, jsonSerialized); } { // Verify extension data works with read-ahead. Extension data stored on JsonElement which has a custom converter. MemoryStream stream = new MemoryStream(data); ClassWithExtensionData obj = JsonSerializer.DeserializeAsync<ClassWithExtensionData>(stream, options).Result; Assert.NotNull(obj.MyOverflow["Property1"]); Assert.NotNull(obj.MyOverflow["Property2"]); Assert.NotNull(obj.MyOverflow["Property3"]); string jsonSerialized = JsonSerializer.Serialize(obj, options); Assert.Equal(json, jsonSerialized); } } [Theory, InlineData(1), InlineData(10), InlineData(100), InlineData(1000), InlineData(10000)] public static void ReadAheadFromArray(int stringSize) { StringBuilder builder = new StringBuilder("["); for (int i = 0; i < 10; i++) { AppendTestString(i, stringSize, builder); if (i != 9) { builder.Append(@","); } } builder.Append(@"]"); string json = builder.ToString(); var options = new JsonSerializerOptions(); // No customer converters registered; the built-in string converter converter will be used. // Ensure buffer size is small as possible for read-ahead. options.DefaultBufferSize = 1; byte[] data = Encoding.UTF8.GetBytes(json); MemoryStream stream = new MemoryStream(data); string[] arr = JsonSerializer.DeserializeAsync<string[]>(stream, options).Result; for (int i = 0; i < 10; i++) { Assert.Equal(new string(i.ToString()[0], stringSize), arr[i]); } string jsonSerialized = JsonSerializer.Serialize(arr, options); Assert.Equal(json, jsonSerialized); } private class ClassWithStringProperties { public string MyString0 { get; set; } public string MyString1 { get; set; } public string MyString2 { get; set; } public string MyString3 { get; set; } public string MyString4 { get; set; } public string MyString5 { get; set; } public string MyString6 { get; set; } public string MyString7 { get; set; } public string MyString8 { get; set; } public string MyString9 { get; set; } } private class ClassWithExtensionData { [JsonExtensionData] public Dictionary<string, object> MyOverflow { get; set; } } /// <summary> /// Class without a converter that has properties with a custom converter. /// </summary> private class ClassWithNoConverter { public ClassWithStringProperties Property1 { get; set; } public ClassWithStringProperties Property2 { get; set; } public ClassWithStringProperties Property3 { get; set; } } /// <summary> /// Converter for POCO type with 10 string properties. /// </summary> private class ClassWithStringPropertyConverter : JsonConverter<ClassWithStringProperties> { public override ClassWithStringProperties Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.StartObject) { throw new JsonException(); } ClassWithStringProperties obj = new ClassWithStringProperties(); for (int i = 0; i <= 9; i++) { reader.Read(); if (reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } string propertyName = reader.GetString(); reader.Read(); string val = reader.GetString(); switch (propertyName) { case "MyString0": obj.MyString0 = val; break; case "MyString1": obj.MyString1 = val; break; case "MyString2": obj.MyString2 = val; break; case "MyString3": obj.MyString3 = val; break; case "MyString4": obj.MyString4 = val; break; case "MyString5": obj.MyString5 = val; break; case "MyString6": obj.MyString6 = val; break; case "MyString7": obj.MyString7 = val; break; case "MyString8": obj.MyString8 = val; break; case "MyString9": obj.MyString9 = val; break; default: throw new JsonException(); } } reader.Read(); if (reader.TokenType != JsonTokenType.EndObject) { throw new JsonException(); } return obj; } public override void Write(Utf8JsonWriter writer, ClassWithStringProperties value, JsonSerializerOptions options) { writer.WriteStartObject(); writer.WriteString("MyString0", value.MyString0); writer.WriteString("MyString1", value.MyString1); writer.WriteString("MyString2", value.MyString2); writer.WriteString("MyString3", value.MyString3); writer.WriteString("MyString4", value.MyString4); writer.WriteString("MyString5", value.MyString5); writer.WriteString("MyString6", value.MyString6); writer.WriteString("MyString7", value.MyString7); writer.WriteString("MyString8", value.MyString8); writer.WriteString("MyString9", value.MyString9); writer.WriteEndObject(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class CustomConverterTests { private static void VerifyClassWithStringProperties(ClassWithStringProperties obj, int stringSize) { // The 10 properties will cause buffer boundary cases where the converter requires read-ahead. Assert.Equal(new string('0', stringSize), obj.MyString0); Assert.Equal(new string('1', stringSize), obj.MyString1); Assert.Equal(new string('2', stringSize), obj.MyString2); Assert.Equal(new string('3', stringSize), obj.MyString3); Assert.Equal(new string('4', stringSize), obj.MyString4); Assert.Equal(new string('5', stringSize), obj.MyString5); Assert.Equal(new string('6', stringSize), obj.MyString6); Assert.Equal(new string('7', stringSize), obj.MyString7); Assert.Equal(new string('8', stringSize), obj.MyString8); Assert.Equal(new string('9', stringSize), obj.MyString9); } private static void VerifyExtensionDataStringProperties(ClassWithExtensionData obj, int stringSize) { // The 10 properties will cause buffer boundary cases where the converter requires read-ahead. Assert.Equal(new string('0', stringSize), ((JsonElement)obj.MyOverflow["MyString0"]).ToString()); Assert.Equal(new string('1', stringSize), ((JsonElement)obj.MyOverflow["MyString1"]).ToString()); Assert.Equal(new string('2', stringSize), ((JsonElement)obj.MyOverflow["MyString2"]).ToString()); Assert.Equal(new string('3', stringSize), ((JsonElement)obj.MyOverflow["MyString3"]).ToString()); Assert.Equal(new string('4', stringSize), ((JsonElement)obj.MyOverflow["MyString4"]).ToString()); Assert.Equal(new string('5', stringSize), ((JsonElement)obj.MyOverflow["MyString5"]).ToString()); Assert.Equal(new string('6', stringSize), ((JsonElement)obj.MyOverflow["MyString6"]).ToString()); Assert.Equal(new string('7', stringSize), ((JsonElement)obj.MyOverflow["MyString7"]).ToString()); Assert.Equal(new string('8', stringSize), ((JsonElement)obj.MyOverflow["MyString8"]).ToString()); Assert.Equal(new string('9', stringSize), ((JsonElement)obj.MyOverflow["MyString9"]).ToString()); } private static string CreateTestStringProperty(int stringSize) { StringBuilder builder = new StringBuilder(); builder.Append("{"); for (int i = 0; i <= 9; i++) { builder.Append(@"""MyString"); builder.Append(i.ToString()); builder.Append(@""":"); AppendTestString(i, stringSize, builder); if (i != 9) { builder.Append(@","); } } builder.Append("}"); return builder.ToString(); } private static void AppendTestString(int i, int stringSize, StringBuilder builder) { builder.Append(@""""); builder.Append(new string(i.ToString()[0], stringSize)); builder.Append(@""""); } [Theory, InlineData(1), InlineData(10), InlineData(100), InlineData(1000), InlineData(10000), InlineData(25000)] public static void ReadAheadFromRoot(int stringSize) { string json = CreateTestStringProperty(stringSize); var options = new JsonSerializerOptions(); options.Converters.Add(new ClassWithStringPropertyConverter()); // Ensure buffer size is small as possible for read-ahead. options.DefaultBufferSize = 1; byte[] data = Encoding.UTF8.GetBytes(json); { MemoryStream stream = new MemoryStream(data); ClassWithStringProperties obj = JsonSerializer.DeserializeAsync<ClassWithStringProperties>(stream, options).Result; VerifyClassWithStringProperties(obj, stringSize); string jsonSerialized = JsonSerializer.Serialize(obj, options); Assert.Equal(json, jsonSerialized); } { // Verify extension data works with read-ahead. Extension data stored on JsonElement which has a custom converter. MemoryStream stream = new MemoryStream(data); ClassWithExtensionData obj = JsonSerializer.DeserializeAsync<ClassWithExtensionData>(stream, options).Result; VerifyExtensionDataStringProperties(obj, stringSize); string jsonSerialized = JsonSerializer.Serialize(obj, options); Assert.Equal(json, jsonSerialized); } } [Theory, InlineData(1), InlineData(10), InlineData(100), InlineData(1000), InlineData(10000)] public static void ReadAheadFromProperties(int stringSize) { string jsonProperties = CreateTestStringProperty(stringSize); StringBuilder builder = new StringBuilder(); builder.Append("{"); builder.Append(@"""Property1"":"); builder.Append(jsonProperties); builder.Append(@",""Property2"":"); builder.Append(jsonProperties); builder.Append(@",""Property3"":"); builder.Append(jsonProperties); builder.Append("}"); string json = builder.ToString(); var options = new JsonSerializerOptions(); options.Converters.Add(new ClassWithStringPropertyConverter()); // Ensure buffer size is small as possible for read-ahead. options.DefaultBufferSize = 1; byte[] data = Encoding.UTF8.GetBytes(json); { MemoryStream stream = new MemoryStream(data); ClassWithNoConverter obj = JsonSerializer.DeserializeAsync<ClassWithNoConverter>(stream, options).Result; VerifyClassWithStringProperties(obj.Property1, stringSize); VerifyClassWithStringProperties(obj.Property2, stringSize); VerifyClassWithStringProperties(obj.Property3, stringSize); string jsonSerialized = JsonSerializer.Serialize(obj, options); Assert.Equal(json, jsonSerialized); } { // Verify extension data works with read-ahead. Extension data stored on JsonElement which has a custom converter. MemoryStream stream = new MemoryStream(data); ClassWithExtensionData obj = JsonSerializer.DeserializeAsync<ClassWithExtensionData>(stream, options).Result; Assert.NotNull(obj.MyOverflow["Property1"]); Assert.NotNull(obj.MyOverflow["Property2"]); Assert.NotNull(obj.MyOverflow["Property3"]); string jsonSerialized = JsonSerializer.Serialize(obj, options); Assert.Equal(json, jsonSerialized); } } [Theory, InlineData(1), InlineData(10), InlineData(100), InlineData(1000), InlineData(10000)] public static void ReadAheadFromArray(int stringSize) { StringBuilder builder = new StringBuilder("["); for (int i = 0; i < 10; i++) { AppendTestString(i, stringSize, builder); if (i != 9) { builder.Append(@","); } } builder.Append(@"]"); string json = builder.ToString(); var options = new JsonSerializerOptions(); // No customer converters registered; the built-in string converter converter will be used. // Ensure buffer size is small as possible for read-ahead. options.DefaultBufferSize = 1; byte[] data = Encoding.UTF8.GetBytes(json); MemoryStream stream = new MemoryStream(data); string[] arr = JsonSerializer.DeserializeAsync<string[]>(stream, options).Result; for (int i = 0; i < 10; i++) { Assert.Equal(new string(i.ToString()[0], stringSize), arr[i]); } string jsonSerialized = JsonSerializer.Serialize(arr, options); Assert.Equal(json, jsonSerialized); } private class ClassWithStringProperties { public string MyString0 { get; set; } public string MyString1 { get; set; } public string MyString2 { get; set; } public string MyString3 { get; set; } public string MyString4 { get; set; } public string MyString5 { get; set; } public string MyString6 { get; set; } public string MyString7 { get; set; } public string MyString8 { get; set; } public string MyString9 { get; set; } } private class ClassWithExtensionData { [JsonExtensionData] public Dictionary<string, object> MyOverflow { get; set; } } /// <summary> /// Class without a converter that has properties with a custom converter. /// </summary> private class ClassWithNoConverter { public ClassWithStringProperties Property1 { get; set; } public ClassWithStringProperties Property2 { get; set; } public ClassWithStringProperties Property3 { get; set; } } /// <summary> /// Converter for POCO type with 10 string properties. /// </summary> private class ClassWithStringPropertyConverter : JsonConverter<ClassWithStringProperties> { public override ClassWithStringProperties Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.StartObject) { throw new JsonException(); } ClassWithStringProperties obj = new ClassWithStringProperties(); for (int i = 0; i <= 9; i++) { reader.Read(); if (reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } string propertyName = reader.GetString(); reader.Read(); string val = reader.GetString(); switch (propertyName) { case "MyString0": obj.MyString0 = val; break; case "MyString1": obj.MyString1 = val; break; case "MyString2": obj.MyString2 = val; break; case "MyString3": obj.MyString3 = val; break; case "MyString4": obj.MyString4 = val; break; case "MyString5": obj.MyString5 = val; break; case "MyString6": obj.MyString6 = val; break; case "MyString7": obj.MyString7 = val; break; case "MyString8": obj.MyString8 = val; break; case "MyString9": obj.MyString9 = val; break; default: throw new JsonException(); } } reader.Read(); if (reader.TokenType != JsonTokenType.EndObject) { throw new JsonException(); } return obj; } public override void Write(Utf8JsonWriter writer, ClassWithStringProperties value, JsonSerializerOptions options) { writer.WriteStartObject(); writer.WriteString("MyString0", value.MyString0); writer.WriteString("MyString1", value.MyString1); writer.WriteString("MyString2", value.MyString2); writer.WriteString("MyString3", value.MyString3); writer.WriteString("MyString4", value.MyString4); writer.WriteString("MyString5", value.MyString5); writer.WriteString("MyString6", value.MyString6); writer.WriteString("MyString7", value.MyString7); writer.WriteString("MyString8", value.MyString8); writer.WriteString("MyString9", value.MyString9); writer.WriteEndObject(); } } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/HardwareIntrinsics/General/Vector64_1/ToVector128.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\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 ToVector128Int32() { var test = new VectorExtend__ToVector128Int32(); // 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__ToVector128Int32 { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Int32[] values = new Int32[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetInt32(); } Vector64<Int32> value = Vector64.Create(values[0], values[1]); Vector128<Int32> result = value.ToVector128(); ValidateResult(result, values, isUnsafe: false); Vector128<Int32> unsafeResult = value.ToVector128Unsafe(); ValidateResult(unsafeResult, values, isUnsafe: true); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Int32[] values = new Int32[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetInt32(); } Vector64<Int32> value = Vector64.Create(values[0], values[1]); object result = typeof(Vector64) .GetMethod(nameof(Vector64.ToVector128)) .MakeGenericMethod(typeof(Int32)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<Int32>)(result), values, isUnsafe: false); object unsafeResult = typeof(Vector64) .GetMethod(nameof(Vector64.ToVector128)) .MakeGenericMethod(typeof(Int32)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<Int32>)(unsafeResult), values, isUnsafe: true); } private void ValidateResult(Vector128<Int32> result, Int32[] values, bool isUnsafe, [CallerMemberName] string method = "") { Int32[] resultElements = new Int32[ElementCount * 2]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref resultElements[0]), result); ValidateResult(resultElements, values, isUnsafe, method); } private void ValidateResult(Int32[] result, Int32[] 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<Int32>.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 ToVector128Int32() { var test = new VectorExtend__ToVector128Int32(); // 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__ToVector128Int32 { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Int32[] values = new Int32[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetInt32(); } Vector64<Int32> value = Vector64.Create(values[0], values[1]); Vector128<Int32> result = value.ToVector128(); ValidateResult(result, values, isUnsafe: false); Vector128<Int32> unsafeResult = value.ToVector128Unsafe(); ValidateResult(unsafeResult, values, isUnsafe: true); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Int32[] values = new Int32[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetInt32(); } Vector64<Int32> value = Vector64.Create(values[0], values[1]); object result = typeof(Vector64) .GetMethod(nameof(Vector64.ToVector128)) .MakeGenericMethod(typeof(Int32)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<Int32>)(result), values, isUnsafe: false); object unsafeResult = typeof(Vector64) .GetMethod(nameof(Vector64.ToVector128)) .MakeGenericMethod(typeof(Int32)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<Int32>)(unsafeResult), values, isUnsafe: true); } private void ValidateResult(Vector128<Int32> result, Int32[] values, bool isUnsafe, [CallerMemberName] string method = "") { Int32[] resultElements = new Int32[ElementCount * 2]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref resultElements[0]), result); ValidateResult(resultElements, values, isUnsafe, method); } private void ValidateResult(Int32[] result, Int32[] 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<Int32>.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,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/HardwareIntrinsics/General/Vector64_1/op_Equality.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_EqualityInt64() { var test = new VectorBooleanBinaryOpTest__op_EqualityInt64(); // 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 VectorBooleanBinaryOpTest__op_EqualityInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int64[] inArray1, Int64[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); 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<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 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 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(VectorBooleanBinaryOpTest__op_EqualityInt64 testClass) { var result = _fld1 == _fld2; testClass.ValidateResult(_fld1, _fld2, result); } } 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 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 VectorBooleanBinaryOpTest__op_EqualityInt64() { 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 VectorBooleanBinaryOpTest__op_EqualityInt64() { 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, 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); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector64<Int64>).GetMethod("op_Equality", new Type[] { typeof(Vector64<Int64>), typeof(Vector64<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = _clsVar1 == _clsVar2; ValidateResult(_clsVar1, _clsVar2, result); } 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; ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__op_EqualityInt64(); var result = test._fld1 == test._fld2; ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = _fld1 == _fld2; ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = 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(Vector64<Int64> op1, Vector64<Int64> op2, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; 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>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int64[] left, Int64[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= (left[i] == right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.op_Equality<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: ({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_EqualityInt64() { var test = new VectorBooleanBinaryOpTest__op_EqualityInt64(); // 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 VectorBooleanBinaryOpTest__op_EqualityInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int64[] inArray1, Int64[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); 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<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 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 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(VectorBooleanBinaryOpTest__op_EqualityInt64 testClass) { var result = _fld1 == _fld2; testClass.ValidateResult(_fld1, _fld2, result); } } 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 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 VectorBooleanBinaryOpTest__op_EqualityInt64() { 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 VectorBooleanBinaryOpTest__op_EqualityInt64() { 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, 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); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector64<Int64>).GetMethod("op_Equality", new Type[] { typeof(Vector64<Int64>), typeof(Vector64<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = _clsVar1 == _clsVar2; ValidateResult(_clsVar1, _clsVar2, result); } 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; ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__op_EqualityInt64(); var result = test._fld1 == test._fld2; ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = _fld1 == _fld2; ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = 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(Vector64<Int64> op1, Vector64<Int64> op2, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; 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>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int64[] left, Int64[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= (left[i] == right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.op_Equality<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: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Net.Primitives/tests/PalTests/System.Net.Primitives.Pal.Tests.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <StringResourcesPath>../../src/Resources/Strings.resx</StringResourcesPath> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-Browser</TargetFrameworks> <EnableLibraryImportGenerator>true</EnableLibraryImportGenerator> </PropertyGroup> <PropertyGroup> <!-- SYSTEM_NET_PRIMITIVES_DLL is required to allow source-level code sharing for types defined within the System.Net.Internals namespace. --> <DefineConstants>$(DefineConstants);SYSTEM_NET_PRIMITIVES_DLL</DefineConstants> </PropertyGroup> <!-- Do not reference these assemblies from the TargetingPack since we are building part of the source code for tests. --> <ItemGroup> <DefaultReferenceExclusion Include="System.Net.Primitives" /> </ItemGroup> <ItemGroup> <Compile Include="..\..\src\System\Net\Sockets\AddressFamily.cs" Link="ProductionCode\System\Net\Sockets\AddressFamily.cs" /> <Compile Include="..\..\src\System\Net\Sockets\SocketError.cs" Link="ProductionCode\System\Net\Sockets\SocketError.cs" /> <Compile Include="..\..\src\System\Net\IPAddress.cs" Link="ProductionCode\System\Net\IPAddress.cs" /> <Compile Include="..\..\src\System\Net\IPAddressParser.cs" Link="ProductionCode\System\Net\IPAddressParser.cs" /> <Compile Include="$(CommonPath)System\Net\IPv4AddressHelper.Common.cs" Link="ProductionCode\System\Net\IPv4AddressHelper.Common.cs" /> <Compile Include="$(CommonPath)System\Net\IPv6AddressHelper.Common.cs" Link="ProductionCode\System\Net\IPv6AddressHelper.Common.cs" /> <Compile Include="..\..\src\System\Net\IPEndPoint.cs" Link="ProductionCode\System\Net\IPEndPoint.cs" /> <Compile Include="$(CommonPath)System\Net\SocketAddress.cs" Link="Common\System\Net\SocketAddress.cs" /> <Compile Include="..\..\src\System\Net\EndPoint.cs" Link="ProductionCode\System\Net\EndPoint.cs" /> <Compile Include="$(CommonPath)System\Text\StringBuilderCache.cs" Link="ProductionCode\Common\System\Text\StringBuilderCache.cs" /> <Compile Include="$(CommonPath)System\HexConverter.cs" Link="Common\System\HexConverter.cs" /> </ItemGroup> <ItemGroup> <Compile Include="HostInformationPalTest.cs" /> <Compile Include="SocketAddressPalTest.cs" /> <Compile Include="Fakes\NetEventSource.cs" /> <Compile Include="..\..\src\System\Net\SocketException.cs" Link="ProductionCode\System\Net\SocketException.cs" /> <Compile Include="$(CommonPath)System\Net\InternalException.cs" Link="ProductionCode\Common\System\Net\InternalException.cs" /> <Compile Include="$(CommonPath)System\Net\IPAddressParserStatics.cs" Link="ProductionCode\Common\System\Net\IPAddressParserStatics.cs" /> <Compile Include="$(CommonPath)System\Net\TcpValidationHelpers.cs" Link="ProductionCode\Common\System\Net\TcpValidationHelpers.cs" /> <Compile Include="$(CommonPath)System\NotImplemented.cs" Link="ProductionCode\Common\System\NotImplemented.cs" /> <Compile Include="$(CommonPath)Interop\Windows\WinSock\Interop.ErrorCodes.cs" Link="ProductionCode\Common\Interop\Windows\WinSock\Interop.ErrorCodes.cs" /> </ItemGroup> <ItemGroup Condition=" '$(TargetPlatformIdentifier)' == 'windows' "> <Compile Include="..\..\src\System\Net\SocketException.Windows.cs" Link="ProductionCode\System\Net\SocketException.Windows.cs" /> <Compile Include="$(CommonPath)System\Net\SocketAddressPal.Windows.cs" Link="Common\System\Net\SocketAddressPal.Windows.cs" /> <Compile Include="$(CommonPath)System\Net\NetworkInformation\HostInformationPal.Windows.cs" Link="Common\System\Net\NetworkInformation\HostInformationPal.Windows.cs" /> <Compile Include="$(CommonPath)Interop\Windows\IpHlpApi\Interop.ErrorCodes.cs" Link="Common\Interop\Windows\IpHlpApi\Interop.ErrorCodes.cs" /> <Compile Include="$(CommonPath)Interop\Windows\IpHlpApi\Interop.FIXED_INFO.cs" Link="Common\Interop\Windows\IpHlpApi\Interop.FIXED_INFO.cs" /> <Compile Include="$(CommonPath)Interop\Windows\IpHlpApi\Interop.GetNetworkParams.cs" Link="Common\Interop\Windows\IpHlpApi\Interop.GetNetworkParams.cs" /> <Compile Include="$(CommonPath)Interop\Windows\IpHlpApi\Interop.IP_ADDR_STRING.cs" Link="Common\Interop\Windows\IpHlpApi\Interop.IP_ADDR_STRING.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs" Link="ProductionCode\Common\Interop\Windows\Interop.Libraries.cs" /> <Compile Include="$(CommonPath)Interop\Windows\NtDll\Interop.NtStatus.cs" Link="ProductionCode\Common\Interop\Windows\NtDll\Interop.NtStatus.cs" /> <Compile Include="$(CommonPath)System\Net\NetworkInformation\InterfaceInfoPal.Windows.cs" Link="ProductionCode\System\Net\NetworkInformation\InterfaceInfoPal.Windows.cs" /> <Compile Include="$(CommonPath)Interop\Windows\IpHlpApi\Interop.if_nametoindex.cs" Link="ProductionCode\Common\Interop\Windows\IpHlpApi\Interop.if_nametoindex.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Unix' or '$(TargetPlatformIdentifier)' == 'Browser'"> <Compile Include="..\..\src\System\Net\SocketException.Unix.cs" Link="ProductionCode\System\Net\SocketException.Unix.cs" /> <Compile Include="$(CommonPath)System\Net\SocketAddressPal.Unix.cs" Link="Common\System\Net\SocketAddressPal.Unix.cs" /> <Compile Include="$(CommonPath)System\Net\Sockets\SocketErrorPal.Unix.cs" Link="Common\System\Net\Sockets\SocketErrorPal.Unix.cs" /> <Compile Include="$(CommonPath)Interop\Interop.CheckedAccess.cs" Link="ProductionCode\Common\Interop\Interop.CheckedAccess.cs" /> <Compile Include="$(CommonPath)Interop\Unix\Interop.Errors.cs" Link="ProductionCode\Interop\Unix\Interop.Errors.cs" /> <Compile Include="$(CommonPath)Interop\Unix\Interop.Libraries.cs" Link="ProductionCode\Common\Interop\Unix\Interop.Libraries.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.IPAddress.cs" Link="ProductionCode\Common\Interop\Unix\System.Native\Interop.IPAddress.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.SocketAddress.cs" Link="ProductionCode\Common\Interop\Unix\System.Native\Interop.SocketAddress.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Unix'"> <Compile Include="$(CommonPath)System\Net\NetworkInformation\HostInformationPal.Unix.cs" Link="Common\System\Net\NetworkInformation\HostInformationPal.Unix.cs" /> <Compile Include="$(CommonPath)System\Net\NetworkInformation\InterfaceInfoPal.Unix.cs" Link="Common\System\Net\NetworkInformation\InterfaceInfoPal.Unix.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.GetDomainName.cs" Link="Common\Interop\Unix\System.Native\Interop.GetDomainName.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.GetHostName.cs" Link="Common\Interop\Unix\System.Native\Interop.GetHostName.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.GetNameInfo.cs" Link="Common\Interop\Unix\System.Native\Interop.GetNameInfo.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.HostEntry.cs" Link="Common\Interop\Unix\System.Native\Interop.HostEntry.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.InterfaceNameToIndex.cs" Link="Common\Interop\Unix\System.Native\Interop.InterfaceNameToIndex.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Browser'"> <Compile Include="$(CommonPath)System\Net\NetworkInformation\HostInformationPal.Browser.cs" Link="Common\System\Net\NetworkInformation\HostInformationPal.Browser.cs" /> <Compile Include="$(CommonPath)System\Net\NetworkInformation\InterfaceInfoPal.Browser.cs" Link="ProductionCode\Common\System\Net\NetworkInformation\InterfaceInfoPal.Browser.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <StringResourcesPath>../../src/Resources/Strings.resx</StringResourcesPath> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-Browser</TargetFrameworks> <EnableLibraryImportGenerator>true</EnableLibraryImportGenerator> </PropertyGroup> <PropertyGroup> <!-- SYSTEM_NET_PRIMITIVES_DLL is required to allow source-level code sharing for types defined within the System.Net.Internals namespace. --> <DefineConstants>$(DefineConstants);SYSTEM_NET_PRIMITIVES_DLL</DefineConstants> </PropertyGroup> <!-- Do not reference these assemblies from the TargetingPack since we are building part of the source code for tests. --> <ItemGroup> <DefaultReferenceExclusion Include="System.Net.Primitives" /> </ItemGroup> <ItemGroup> <Compile Include="..\..\src\System\Net\Sockets\AddressFamily.cs" Link="ProductionCode\System\Net\Sockets\AddressFamily.cs" /> <Compile Include="..\..\src\System\Net\Sockets\SocketError.cs" Link="ProductionCode\System\Net\Sockets\SocketError.cs" /> <Compile Include="..\..\src\System\Net\IPAddress.cs" Link="ProductionCode\System\Net\IPAddress.cs" /> <Compile Include="..\..\src\System\Net\IPAddressParser.cs" Link="ProductionCode\System\Net\IPAddressParser.cs" /> <Compile Include="$(CommonPath)System\Net\IPv4AddressHelper.Common.cs" Link="ProductionCode\System\Net\IPv4AddressHelper.Common.cs" /> <Compile Include="$(CommonPath)System\Net\IPv6AddressHelper.Common.cs" Link="ProductionCode\System\Net\IPv6AddressHelper.Common.cs" /> <Compile Include="..\..\src\System\Net\IPEndPoint.cs" Link="ProductionCode\System\Net\IPEndPoint.cs" /> <Compile Include="$(CommonPath)System\Net\SocketAddress.cs" Link="Common\System\Net\SocketAddress.cs" /> <Compile Include="..\..\src\System\Net\EndPoint.cs" Link="ProductionCode\System\Net\EndPoint.cs" /> <Compile Include="$(CommonPath)System\Text\StringBuilderCache.cs" Link="ProductionCode\Common\System\Text\StringBuilderCache.cs" /> <Compile Include="$(CommonPath)System\HexConverter.cs" Link="Common\System\HexConverter.cs" /> </ItemGroup> <ItemGroup> <Compile Include="HostInformationPalTest.cs" /> <Compile Include="SocketAddressPalTest.cs" /> <Compile Include="Fakes\NetEventSource.cs" /> <Compile Include="..\..\src\System\Net\SocketException.cs" Link="ProductionCode\System\Net\SocketException.cs" /> <Compile Include="$(CommonPath)System\Net\InternalException.cs" Link="ProductionCode\Common\System\Net\InternalException.cs" /> <Compile Include="$(CommonPath)System\Net\IPAddressParserStatics.cs" Link="ProductionCode\Common\System\Net\IPAddressParserStatics.cs" /> <Compile Include="$(CommonPath)System\Net\TcpValidationHelpers.cs" Link="ProductionCode\Common\System\Net\TcpValidationHelpers.cs" /> <Compile Include="$(CommonPath)System\NotImplemented.cs" Link="ProductionCode\Common\System\NotImplemented.cs" /> <Compile Include="$(CommonPath)Interop\Windows\WinSock\Interop.ErrorCodes.cs" Link="ProductionCode\Common\Interop\Windows\WinSock\Interop.ErrorCodes.cs" /> </ItemGroup> <ItemGroup Condition=" '$(TargetPlatformIdentifier)' == 'windows' "> <Compile Include="..\..\src\System\Net\SocketException.Windows.cs" Link="ProductionCode\System\Net\SocketException.Windows.cs" /> <Compile Include="$(CommonPath)System\Net\SocketAddressPal.Windows.cs" Link="Common\System\Net\SocketAddressPal.Windows.cs" /> <Compile Include="$(CommonPath)System\Net\NetworkInformation\HostInformationPal.Windows.cs" Link="Common\System\Net\NetworkInformation\HostInformationPal.Windows.cs" /> <Compile Include="$(CommonPath)Interop\Windows\IpHlpApi\Interop.ErrorCodes.cs" Link="Common\Interop\Windows\IpHlpApi\Interop.ErrorCodes.cs" /> <Compile Include="$(CommonPath)Interop\Windows\IpHlpApi\Interop.FIXED_INFO.cs" Link="Common\Interop\Windows\IpHlpApi\Interop.FIXED_INFO.cs" /> <Compile Include="$(CommonPath)Interop\Windows\IpHlpApi\Interop.GetNetworkParams.cs" Link="Common\Interop\Windows\IpHlpApi\Interop.GetNetworkParams.cs" /> <Compile Include="$(CommonPath)Interop\Windows\IpHlpApi\Interop.IP_ADDR_STRING.cs" Link="Common\Interop\Windows\IpHlpApi\Interop.IP_ADDR_STRING.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs" Link="ProductionCode\Common\Interop\Windows\Interop.Libraries.cs" /> <Compile Include="$(CommonPath)Interop\Windows\NtDll\Interop.NtStatus.cs" Link="ProductionCode\Common\Interop\Windows\NtDll\Interop.NtStatus.cs" /> <Compile Include="$(CommonPath)System\Net\NetworkInformation\InterfaceInfoPal.Windows.cs" Link="ProductionCode\System\Net\NetworkInformation\InterfaceInfoPal.Windows.cs" /> <Compile Include="$(CommonPath)Interop\Windows\IpHlpApi\Interop.if_nametoindex.cs" Link="ProductionCode\Common\Interop\Windows\IpHlpApi\Interop.if_nametoindex.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Unix' or '$(TargetPlatformIdentifier)' == 'Browser'"> <Compile Include="..\..\src\System\Net\SocketException.Unix.cs" Link="ProductionCode\System\Net\SocketException.Unix.cs" /> <Compile Include="$(CommonPath)System\Net\SocketAddressPal.Unix.cs" Link="Common\System\Net\SocketAddressPal.Unix.cs" /> <Compile Include="$(CommonPath)System\Net\Sockets\SocketErrorPal.Unix.cs" Link="Common\System\Net\Sockets\SocketErrorPal.Unix.cs" /> <Compile Include="$(CommonPath)Interop\Interop.CheckedAccess.cs" Link="ProductionCode\Common\Interop\Interop.CheckedAccess.cs" /> <Compile Include="$(CommonPath)Interop\Unix\Interop.Errors.cs" Link="ProductionCode\Interop\Unix\Interop.Errors.cs" /> <Compile Include="$(CommonPath)Interop\Unix\Interop.Libraries.cs" Link="ProductionCode\Common\Interop\Unix\Interop.Libraries.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.IPAddress.cs" Link="ProductionCode\Common\Interop\Unix\System.Native\Interop.IPAddress.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.SocketAddress.cs" Link="ProductionCode\Common\Interop\Unix\System.Native\Interop.SocketAddress.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Unix'"> <Compile Include="$(CommonPath)System\Net\NetworkInformation\HostInformationPal.Unix.cs" Link="Common\System\Net\NetworkInformation\HostInformationPal.Unix.cs" /> <Compile Include="$(CommonPath)System\Net\NetworkInformation\InterfaceInfoPal.Unix.cs" Link="Common\System\Net\NetworkInformation\InterfaceInfoPal.Unix.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.GetDomainName.cs" Link="Common\Interop\Unix\System.Native\Interop.GetDomainName.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.GetHostName.cs" Link="Common\Interop\Unix\System.Native\Interop.GetHostName.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.GetNameInfo.cs" Link="Common\Interop\Unix\System.Native\Interop.GetNameInfo.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.HostEntry.cs" Link="Common\Interop\Unix\System.Native\Interop.HostEntry.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.InterfaceNameToIndex.cs" Link="Common\Interop\Unix\System.Native\Interop.InterfaceNameToIndex.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Browser'"> <Compile Include="$(CommonPath)System\Net\NetworkInformation\HostInformationPal.Browser.cs" Link="Common\System\Net\NetworkInformation\HostInformationPal.Browser.cs" /> <Compile Include="$(CommonPath)System\Net\NetworkInformation\InterfaceInfoPal.Browser.cs" Link="ProductionCode\Common\System\Net\NetworkInformation\InterfaceInfoPal.Browser.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ReverseElement8.Vector64.UInt16.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.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 ReverseElement8_Vector64_UInt16() { var test = new SimpleUnaryOpTest__ReverseElement8_Vector64_UInt16(); 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__ReverseElement8_Vector64_UInt16 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); 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<UInt16, 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<UInt16> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__ReverseElement8_Vector64_UInt16 testClass) { var result = AdvSimd.ReverseElement8(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__ReverseElement8_Vector64_UInt16 testClass) { fixed (Vector64<UInt16>* pFld1 = &_fld1) { var result = AdvSimd.ReverseElement8( AdvSimd.LoadVector64((UInt16*)(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<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static Vector64<UInt16> _clsVar1; private Vector64<UInt16> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__ReverseElement8_Vector64_UInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); } public SimpleUnaryOpTest__ReverseElement8_Vector64_UInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, new UInt16[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.ReverseElement8( Unsafe.Read<Vector64<UInt16>>(_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.ReverseElement8( AdvSimd.LoadVector64((UInt16*)(_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.ReverseElement8), new Type[] { typeof(Vector64<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ReverseElement8), new Type[] { typeof(Vector64<UInt16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ReverseElement8( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<UInt16>* pClsVar1 = &_clsVar1) { var result = AdvSimd.ReverseElement8( AdvSimd.LoadVector64((UInt16*)(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<UInt16>>(_dataTable.inArray1Ptr); var result = AdvSimd.ReverseElement8(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)); var result = AdvSimd.ReverseElement8(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__ReverseElement8_Vector64_UInt16(); var result = AdvSimd.ReverseElement8(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__ReverseElement8_Vector64_UInt16(); fixed (Vector64<UInt16>* pFld1 = &test._fld1) { var result = AdvSimd.ReverseElement8( AdvSimd.LoadVector64((UInt16*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ReverseElement8(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<UInt16>* pFld1 = &_fld1) { var result = AdvSimd.ReverseElement8( AdvSimd.LoadVector64((UInt16*)(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.ReverseElement8(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.ReverseElement8( AdvSimd.LoadVector64((UInt16*)(&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<UInt16> op1, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ReverseElement8(firstOp[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ReverseElement8)}<UInt16>(Vector64<UInt16>): {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 ReverseElement8_Vector64_UInt16() { var test = new SimpleUnaryOpTest__ReverseElement8_Vector64_UInt16(); 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__ReverseElement8_Vector64_UInt16 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); 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<UInt16, 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<UInt16> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__ReverseElement8_Vector64_UInt16 testClass) { var result = AdvSimd.ReverseElement8(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__ReverseElement8_Vector64_UInt16 testClass) { fixed (Vector64<UInt16>* pFld1 = &_fld1) { var result = AdvSimd.ReverseElement8( AdvSimd.LoadVector64((UInt16*)(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<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static Vector64<UInt16> _clsVar1; private Vector64<UInt16> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__ReverseElement8_Vector64_UInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); } public SimpleUnaryOpTest__ReverseElement8_Vector64_UInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, new UInt16[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.ReverseElement8( Unsafe.Read<Vector64<UInt16>>(_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.ReverseElement8( AdvSimd.LoadVector64((UInt16*)(_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.ReverseElement8), new Type[] { typeof(Vector64<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ReverseElement8), new Type[] { typeof(Vector64<UInt16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ReverseElement8( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<UInt16>* pClsVar1 = &_clsVar1) { var result = AdvSimd.ReverseElement8( AdvSimd.LoadVector64((UInt16*)(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<UInt16>>(_dataTable.inArray1Ptr); var result = AdvSimd.ReverseElement8(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)); var result = AdvSimd.ReverseElement8(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__ReverseElement8_Vector64_UInt16(); var result = AdvSimd.ReverseElement8(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__ReverseElement8_Vector64_UInt16(); fixed (Vector64<UInt16>* pFld1 = &test._fld1) { var result = AdvSimd.ReverseElement8( AdvSimd.LoadVector64((UInt16*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ReverseElement8(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<UInt16>* pFld1 = &_fld1) { var result = AdvSimd.ReverseElement8( AdvSimd.LoadVector64((UInt16*)(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.ReverseElement8(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.ReverseElement8( AdvSimd.LoadVector64((UInt16*)(&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<UInt16> op1, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ReverseElement8(firstOp[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ReverseElement8)}<UInt16>(Vector64<UInt16>): {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,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/TransposeOdd.Vector128.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.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 TransposeOdd_Vector128_UInt64() { var test = new SimpleBinaryOpTest__TransposeOdd_Vector128_UInt64(); 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__TransposeOdd_Vector128_UInt64 { 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(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); 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<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, 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<UInt64> _fld1; public Vector128<UInt64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__TransposeOdd_Vector128_UInt64 testClass) { var result = AdvSimd.Arm64.TransposeOdd(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__TransposeOdd_Vector128_UInt64 testClass) { fixed (Vector128<UInt64>* pFld1 = &_fld1) fixed (Vector128<UInt64>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.TransposeOdd( AdvSimd.LoadVector128((UInt64*)(pFld1)), AdvSimd.LoadVector128((UInt64*)(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<UInt64>>() / sizeof(UInt64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data2 = new UInt64[Op2ElementCount]; private static Vector128<UInt64> _clsVar1; private static Vector128<UInt64> _clsVar2; private Vector128<UInt64> _fld1; private Vector128<UInt64> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__TransposeOdd_Vector128_UInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); } public SimpleBinaryOpTest__TransposeOdd_Vector128_UInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.TransposeOdd( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.TransposeOdd( AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.TransposeOdd), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.TransposeOdd), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.TransposeOdd( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.TransposeOdd( AdvSimd.LoadVector128((UInt64*)(pClsVar1)), AdvSimd.LoadVector128((UInt64*)(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<UInt64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.TransposeOdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.TransposeOdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__TransposeOdd_Vector128_UInt64(); var result = AdvSimd.Arm64.TransposeOdd(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__TransposeOdd_Vector128_UInt64(); fixed (Vector128<UInt64>* pFld1 = &test._fld1) fixed (Vector128<UInt64>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.TransposeOdd( AdvSimd.LoadVector128((UInt64*)(pFld1)), AdvSimd.LoadVector128((UInt64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.TransposeOdd(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt64>* pFld1 = &_fld1) fixed (Vector128<UInt64>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.TransposeOdd( AdvSimd.LoadVector128((UInt64*)(pFld1)), AdvSimd.LoadVector128((UInt64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.TransposeOdd(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.TransposeOdd( AdvSimd.LoadVector128((UInt64*)(&test._fld1)), AdvSimd.LoadVector128((UInt64*)(&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<UInt64> op1, Vector128<UInt64> op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; int index = 0; int half = RetElementCount / 2; for (var i = 0; i < RetElementCount; i+=2, index++) { if (result[index] != left[i+1] || result[++index] != right[i+1]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.TransposeOdd)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {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 TransposeOdd_Vector128_UInt64() { var test = new SimpleBinaryOpTest__TransposeOdd_Vector128_UInt64(); 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__TransposeOdd_Vector128_UInt64 { 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(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); 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<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, 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<UInt64> _fld1; public Vector128<UInt64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__TransposeOdd_Vector128_UInt64 testClass) { var result = AdvSimd.Arm64.TransposeOdd(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__TransposeOdd_Vector128_UInt64 testClass) { fixed (Vector128<UInt64>* pFld1 = &_fld1) fixed (Vector128<UInt64>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.TransposeOdd( AdvSimd.LoadVector128((UInt64*)(pFld1)), AdvSimd.LoadVector128((UInt64*)(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<UInt64>>() / sizeof(UInt64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data2 = new UInt64[Op2ElementCount]; private static Vector128<UInt64> _clsVar1; private static Vector128<UInt64> _clsVar2; private Vector128<UInt64> _fld1; private Vector128<UInt64> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__TransposeOdd_Vector128_UInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); } public SimpleBinaryOpTest__TransposeOdd_Vector128_UInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.TransposeOdd( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.TransposeOdd( AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.TransposeOdd), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.TransposeOdd), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.TransposeOdd( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.TransposeOdd( AdvSimd.LoadVector128((UInt64*)(pClsVar1)), AdvSimd.LoadVector128((UInt64*)(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<UInt64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.TransposeOdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.TransposeOdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__TransposeOdd_Vector128_UInt64(); var result = AdvSimd.Arm64.TransposeOdd(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__TransposeOdd_Vector128_UInt64(); fixed (Vector128<UInt64>* pFld1 = &test._fld1) fixed (Vector128<UInt64>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.TransposeOdd( AdvSimd.LoadVector128((UInt64*)(pFld1)), AdvSimd.LoadVector128((UInt64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.TransposeOdd(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt64>* pFld1 = &_fld1) fixed (Vector128<UInt64>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.TransposeOdd( AdvSimd.LoadVector128((UInt64*)(pFld1)), AdvSimd.LoadVector128((UInt64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.TransposeOdd(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.TransposeOdd( AdvSimd.LoadVector128((UInt64*)(&test._fld1)), AdvSimd.LoadVector128((UInt64*)(&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<UInt64> op1, Vector128<UInt64> op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; int index = 0; int half = RetElementCount / 2; for (var i = 0; i < RetElementCount; i+=2, index++) { if (result[index] != left[i+1] || result[++index] != right[i+1]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.TransposeOdd)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {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,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/CodeGenBringUpTests/DblAvg6_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="DblAvg6.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="DblAvg6.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/Directed/shift/int32_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="int32.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="int32.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Security.Permissions/src/System/Security/Policy/AllMembershipCondition.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Policy { public sealed partial class AllMembershipCondition : ISecurityEncodable, ISecurityPolicyEncodable, IMembershipCondition { public AllMembershipCondition() { } public bool Check(Evidence evidence) { return false; } public IMembershipCondition Copy() { return default(IMembershipCondition); } public override bool Equals(object o) => base.Equals(o); public void FromXml(SecurityElement e) { } public void FromXml(SecurityElement e, PolicyLevel level) { } public override int GetHashCode() => base.GetHashCode(); public override string ToString() => base.ToString(); public SecurityElement ToXml() { return default(SecurityElement); } public SecurityElement ToXml(PolicyLevel level) { return default(SecurityElement); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Policy { public sealed partial class AllMembershipCondition : ISecurityEncodable, ISecurityPolicyEncodable, IMembershipCondition { public AllMembershipCondition() { } public bool Check(Evidence evidence) { return false; } public IMembershipCondition Copy() { return default(IMembershipCondition); } public override bool Equals(object o) => base.Equals(o); public void FromXml(SecurityElement e) { } public void FromXml(SecurityElement e, PolicyLevel level) { } public override int GetHashCode() => base.GetHashCode(); public override string ToString() => base.ToString(); public SecurityElement ToXml() { return default(SecurityElement); } public SecurityElement ToXml(PolicyLevel level) { return default(SecurityElement); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/Regression/clr-x64-JIT/v4.0/devdiv374539/DevDiv_374539.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.Runtime.CompilerServices; using System.Runtime.InteropServices; internal class Test_DevDiv_374539 { [DllImport("kernel32.dll")] private extern static IntPtr GetModuleHandle(string lpModuleName); [DllImport("kernel32.dll")] private extern static IntPtr VirtualAlloc(IntPtr lpAddress, IntPtr dwSize, int flAllocationType, int flProtect); private static void EatAddressSpace() { IntPtr clrDllHandle = GetModuleHandle("clr.dll"); long clrDll = (long)clrDllHandle; for (long i = clrDll - 0x300000000; i < clrDll + 0x300000000; i += 0x10000) { } } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A1() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A2() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A3() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A4() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A5() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A6() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A7() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A8() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A9() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A10() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B1() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B2() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B3() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B4() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B5() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B6() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B7() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B8() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B9() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B10() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C1() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C2() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C3() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C4() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C5() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C6() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C7() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C8() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C9() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C10() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D1() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D2() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D3() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D4() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D5() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D6() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D7() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D8() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D9() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D10() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void Dummy() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void GenericRecursion<T, U>(int level) { if (level == 0) return; level--; GenericRecursion<KeyValuePair<T, U>, U>(level); GenericRecursion<KeyValuePair<U, T>, U>(level); GenericRecursion<T, KeyValuePair<T, U>>(level); GenericRecursion<T, KeyValuePair<U, T>>(level); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); } private static int Main() { try { Console.WriteLine("Eating address space"); EatAddressSpace(); Console.WriteLine("Eating code heap"); GenericRecursion<int, uint>(5); A1(); A2(); A3(); A4(); A5(); A6(); A7(); A8(); A9(); A10(); B1(); B2(); B3(); B4(); B5(); B6(); B7(); B8(); B9(); B10(); C1(); C2(); C3(); C4(); C5(); C6(); C7(); C8(); C9(); C10(); D1(); D2(); D3(); D4(); D5(); D6(); D7(); D8(); D9(); D10(); A1(); A2(); A3(); A4(); A5(); A6(); A7(); A8(); A9(); A10(); B1(); B2(); B3(); B4(); B5(); B6(); B7(); B8(); B9(); B10(); C1(); C2(); C3(); C4(); C5(); C6(); C7(); C8(); C9(); C10(); D1(); D2(); D3(); D4(); D5(); D6(); D7(); D8(); D9(); D10(); Console.WriteLine("Done"); return 100; } catch (Exception e) { Console.WriteLine(e); return 101; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; internal class Test_DevDiv_374539 { [DllImport("kernel32.dll")] private extern static IntPtr GetModuleHandle(string lpModuleName); [DllImport("kernel32.dll")] private extern static IntPtr VirtualAlloc(IntPtr lpAddress, IntPtr dwSize, int flAllocationType, int flProtect); private static void EatAddressSpace() { IntPtr clrDllHandle = GetModuleHandle("clr.dll"); long clrDll = (long)clrDllHandle; for (long i = clrDll - 0x300000000; i < clrDll + 0x300000000; i += 0x10000) { } } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A1() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A2() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A3() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A4() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A5() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A6() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A7() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A8() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A9() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void A10() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B1() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B2() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B3() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B4() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B5() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B6() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B7() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B8() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B9() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void B10() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C1() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C2() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C3() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C4() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C5() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C6() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C7() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C8() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C9() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void C10() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D1() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D2() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D3() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D4() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D5() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D6() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D7() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D8() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D9() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void D10() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void Dummy() { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void GenericRecursion<T, U>(int level) { if (level == 0) return; level--; GenericRecursion<KeyValuePair<T, U>, U>(level); GenericRecursion<KeyValuePair<U, T>, U>(level); GenericRecursion<T, KeyValuePair<T, U>>(level); GenericRecursion<T, KeyValuePair<U, T>>(level); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); } private static int Main() { try { Console.WriteLine("Eating address space"); EatAddressSpace(); Console.WriteLine("Eating code heap"); GenericRecursion<int, uint>(5); A1(); A2(); A3(); A4(); A5(); A6(); A7(); A8(); A9(); A10(); B1(); B2(); B3(); B4(); B5(); B6(); B7(); B8(); B9(); B10(); C1(); C2(); C3(); C4(); C5(); C6(); C7(); C8(); C9(); C10(); D1(); D2(); D3(); D4(); D5(); D6(); D7(); D8(); D9(); D10(); A1(); A2(); A3(); A4(); A5(); A6(); A7(); A8(); A9(); A10(); B1(); B2(); B3(); B4(); B5(); B6(); B7(); B8(); B9(); B10(); C1(); C2(); C3(); C4(); C5(); C6(); C7(); C8(); C9(); C10(); D1(); D2(); D3(); D4(); D5(); D6(); D7(); D8(); D9(); D10(); Console.WriteLine("Done"); return 100; } catch (Exception e) { Console.WriteLine(e); return 101; } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/Common/src/Interop/Unix/System.Native/Interop.PosixSignal.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Sys { [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetPosixSignalHandler")] [SuppressGCTransition] internal static unsafe partial void SetPosixSignalHandler(delegate* unmanaged<int, PosixSignal, int> handler); [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_EnablePosixSignalHandling", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool EnablePosixSignalHandling(int signal); [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_DisablePosixSignalHandling")] internal static partial void DisablePosixSignalHandling(int signal); [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_HandleNonCanceledPosixSignal")] internal static partial void HandleNonCanceledPosixSignal(int signal); [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetPlatformSignalNumber")] [SuppressGCTransition] internal static partial int GetPlatformSignalNumber(PosixSignal signal); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Sys { [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetPosixSignalHandler")] [SuppressGCTransition] internal static unsafe partial void SetPosixSignalHandler(delegate* unmanaged<int, PosixSignal, int> handler); [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_EnablePosixSignalHandling", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool EnablePosixSignalHandling(int signal); [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_DisablePosixSignalHandling")] internal static partial void DisablePosixSignalHandling(int signal); [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_HandleNonCanceledPosixSignal")] internal static partial void HandleNonCanceledPosixSignal(int signal); [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetPlatformSignalNumber")] [SuppressGCTransition] internal static partial int GetPlatformSignalNumber(PosixSignal signal); } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/ZipLow.Vector64.Int16.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 ZipLow_Vector64_Int16() { var test = new SimpleBinaryOpTest__ZipLow_Vector64_Int16(); 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__ZipLow_Vector64_Int16 { 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(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); 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<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, 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<Int16> _fld1; public Vector64<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__ZipLow_Vector64_Int16 testClass) { var result = AdvSimd.Arm64.ZipLow(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ZipLow_Vector64_Int16 testClass) { fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(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<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector64<Int16> _clsVar1; private static Vector64<Int16> _clsVar2; private Vector64<Int16> _fld1; private Vector64<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__ZipLow_Vector64_Int16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); } public SimpleBinaryOpTest__ZipLow_Vector64_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.ZipLow( Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ZipLow), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ZipLow), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.ZipLow( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int16>* pClsVar1 = &_clsVar1) fixed (Vector64<Int16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector64((Int16*)(pClsVar1)), AdvSimd.LoadVector64((Int16*)(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<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.ZipLow(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((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.ZipLow(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ZipLow_Vector64_Int16(); var result = AdvSimd.Arm64.ZipLow(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__ZipLow_Vector64_Int16(); fixed (Vector64<Int16>* pFld1 = &test._fld1) fixed (Vector64<Int16>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.ZipLow(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ZipLow(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector64((Int16*)(&test._fld1)), AdvSimd.LoadVector64((Int16*)(&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<Int16> op1, Vector64<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; int index = 0; int half = RetElementCount / 2; for (var i = 0; i < RetElementCount; i+=2, index++) { if (result[i] != left[index] || result[i+1] != right[index]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ZipLow)}<Int16>(Vector64<Int16>, Vector64<Int16>): {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 ZipLow_Vector64_Int16() { var test = new SimpleBinaryOpTest__ZipLow_Vector64_Int16(); 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__ZipLow_Vector64_Int16 { 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(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); 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<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, 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<Int16> _fld1; public Vector64<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__ZipLow_Vector64_Int16 testClass) { var result = AdvSimd.Arm64.ZipLow(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ZipLow_Vector64_Int16 testClass) { fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(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<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector64<Int16> _clsVar1; private static Vector64<Int16> _clsVar2; private Vector64<Int16> _fld1; private Vector64<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__ZipLow_Vector64_Int16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); } public SimpleBinaryOpTest__ZipLow_Vector64_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.ZipLow( Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ZipLow), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ZipLow), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.ZipLow( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int16>* pClsVar1 = &_clsVar1) fixed (Vector64<Int16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector64((Int16*)(pClsVar1)), AdvSimd.LoadVector64((Int16*)(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<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.ZipLow(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((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.ZipLow(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ZipLow_Vector64_Int16(); var result = AdvSimd.Arm64.ZipLow(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__ZipLow_Vector64_Int16(); fixed (Vector64<Int16>* pFld1 = &test._fld1) fixed (Vector64<Int16>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.ZipLow(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ZipLow(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector64((Int16*)(&test._fld1)), AdvSimd.LoadVector64((Int16*)(&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<Int16> op1, Vector64<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; int index = 0; int half = RetElementCount / 2; for (var i = 0; i < RetElementCount; i+=2, index++) { if (result[i] != left[index] || result[i+1] != right[index]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ZipLow)}<Int16>(Vector64<Int16>, Vector64<Int16>): {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,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/Methodical/MDArray/basics/structarr.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //Simple arithmatic manipulation of one 2D array elements using System; public struct ArrayStruct { public double[,] a2d; public double[,,] a3d; public ArrayStruct(int size) { a2d = new double[size, size]; a3d = new double[size, size, size]; } } public class struct1 { public static Random rand; public const int DefaultSeed = 20010415; public static int size; public static ArrayStruct ima; public static double GenerateDbl() { int e; int op1 = (int)((float)rand.Next() / Int32.MaxValue * 2); if (op1 == 0) e = -rand.Next(0, 14); else e = +rand.Next(0, 14); return Math.Pow(2, e); } public static void Init2DMatrix(out double[,] m, out double[][] refm) { int i, j; i = 0; double temp; m = new double[size, size]; refm = new double[size][]; for (int k = 0; k < refm.Length; k++) refm[k] = new double[size]; while (i < size) { j = 0; while (j < size) { temp = GenerateDbl(); m[i, j] = temp - 60; refm[i][j] = temp - 60; j++; } i++; } } public static void Process2DArray(ref double[,] a2d) { for (int i = 10; i < size + 10; i++) for (int j = 0; j < size; j++) { a2d[i - 10, j] += a2d[0, j] + a2d[1, j]; a2d[i - 10, j] += 10; a2d[i - 10, j] *= a2d[i - 10, j] + a2d[2, j]; a2d[i - 10, j] -= a2d[i - 10, j] * a2d[3, j]; if ((a2d[i - 10, j] + a2d[4, j]) != 0) a2d[i - 10, j] /= a2d[i - 10, j] + a2d[4, j]; else a2d[i - 10, j] += a2d[i - 10, j] * a2d[4, j]; for (int k = 5; k < size; k++) a2d[i - 10, j] += a2d[k, j]; } } public static void ProcessJagged2DArray(ref double[][] a2d) { for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) { a2d[i][j] += a2d[0][j] + a2d[1][j]; a2d[i][j] += 10; a2d[i][j] *= a2d[i][j] + a2d[2][j]; a2d[i][j] -= a2d[i][j] * a2d[3][j]; if ((a2d[i][j] + a2d[4][j]) != 0) a2d[i][j] /= a2d[i][j] + a2d[4][j]; else a2d[i][j] += a2d[i][j] * a2d[4][j]; for (int k = 5; k < size; k++) a2d[i][j] += a2d[k][j]; } } public static void Init3DMatrix(double[,,] m, double[][] refm) { int i, j; i = 0; double temp; while (i < size) { j = 0; while (j < size) { temp = GenerateDbl(); m[i, 0, j] = temp - 60; refm[i][j] = temp - 60; j++; } i++; } } public static void Process3DArray(double[,,] a3d) { for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) { a3d[i, 0, j] += a3d[0, 0, j] + a3d[1, 0, j]; a3d[i, 0, j] *= a3d[i, 0, j] + a3d[2, 0, j]; a3d[i, 0, j] -= a3d[i, 0, j] * a3d[3, 0, j]; if ((a3d[i, 0, j] + a3d[4, 0, j]) != 0) a3d[i, 0, j] /= a3d[i, 0, j] + a3d[4, 0, j]; else a3d[i, 0, j] += a3d[i, 0, j] * a3d[4, 0, j]; for (int k = 5; k < size; k++) a3d[i, 0, j] += a3d[k, 0, j]; } } public static void ProcessJagged3DArray(double[][] a3d) { for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) { a3d[i][j] += a3d[0][j] + a3d[1][j]; a3d[i][j] *= a3d[i][j] + a3d[2][j]; a3d[i][j] -= a3d[i][j] * a3d[3][j]; if ((a3d[i][j] + a3d[4][j]) != 0) a3d[i][j] /= a3d[i][j] + a3d[4][j]; else a3d[i][j] += a3d[i][j] * a3d[4][j]; for (int k = 5; k < size; k++) a3d[i][j] += a3d[k][j]; } } public static int Main() { bool pass = false; int seed = Environment.GetEnvironmentVariable("CORECLR_SEED") switch { string seedStr when seedStr.Equals("random", StringComparison.OrdinalIgnoreCase) => new Random().Next(), string seedStr when int.TryParse(seedStr, out int envSeed) => envSeed, _ => DefaultSeed }; rand = new Random(seed); size = rand.Next(5, 10); Console.WriteLine(); Console.WriteLine("2D Array"); Console.WriteLine("Random seed: {0}; set environment variable CORECLR_SEED to this value to reproduce", seed); Console.WriteLine("Element manipulation of {0} by {0} matrices with different arithmatic operations", size); Console.WriteLine("Matrix is member of struct, element stores random double"); Console.WriteLine("array set/get, ref/out param are used"); ima = new ArrayStruct(size); double[][] refa2d = new double[size][]; Init2DMatrix(out ima.a2d, out refa2d); int m = 0; int n; while (m < size) { n = 0; while (n < size) { Process2DArray(ref ima.a2d); ProcessJagged2DArray(ref refa2d); n++; } m++; } for (int i = 0; i < size; i++) { pass = true; for (int j = 0; j < size; j++) if (ima.a2d[i, j] != refa2d[i][j]) if (!Double.IsNaN(ima.a2d[i, j]) || !Double.IsNaN(refa2d[i][j])) { Console.WriteLine("i={0}, j={1}, ima.a2d[i,j] {2}!=refa2d[i][j] {3}", i, j, ima.a2d[i, j], refa2d[i][j]); pass = false; } } if (pass) { try { ima.a2d[size, size] = 5; pass = false; } catch (IndexOutOfRangeException) { } } Console.WriteLine(); Console.WriteLine("3D Array"); Console.WriteLine("Element manipulation of 3D matrice with different arithmatic operations, size is {0}", size); Console.WriteLine("Matrix is member of struct, element stores random double"); ima = new ArrayStruct(size); double[][] refa3d = new double[size][]; for (int k = 0; k < refa3d.Length; k++) refa3d[k] = new double[size]; Init3DMatrix(ima.a3d, refa3d); m = 0; n = 0; while (m < size) { n = 0; while (n < size) { Process3DArray(ima.a3d); ProcessJagged3DArray(refa3d); n++; } m++; } for (int i = 0; i < size; i++) { pass = true; for (int j = 0; j < size; j++) if (ima.a3d[i, 0, j] != refa3d[i][j]) if (!Double.IsNaN(ima.a3d[i, 0, j]) || !Double.IsNaN(refa3d[i][j])) { Console.WriteLine("i={0}, j={1}, ima.a3d[i,0,j] {2}!=refa3d[i][j] {3}", i, j, ima.a3d[i, 0, j], refa3d[i][j]); pass = false; } } if (pass) { try { ima.a3d[size, size, size] = 5; pass = false; } catch (IndexOutOfRangeException) { } } Console.WriteLine(); if (pass) { Console.WriteLine("PASSED"); return 100; } else { Console.WriteLine("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. //Simple arithmatic manipulation of one 2D array elements using System; public struct ArrayStruct { public double[,] a2d; public double[,,] a3d; public ArrayStruct(int size) { a2d = new double[size, size]; a3d = new double[size, size, size]; } } public class struct1 { public static Random rand; public const int DefaultSeed = 20010415; public static int size; public static ArrayStruct ima; public static double GenerateDbl() { int e; int op1 = (int)((float)rand.Next() / Int32.MaxValue * 2); if (op1 == 0) e = -rand.Next(0, 14); else e = +rand.Next(0, 14); return Math.Pow(2, e); } public static void Init2DMatrix(out double[,] m, out double[][] refm) { int i, j; i = 0; double temp; m = new double[size, size]; refm = new double[size][]; for (int k = 0; k < refm.Length; k++) refm[k] = new double[size]; while (i < size) { j = 0; while (j < size) { temp = GenerateDbl(); m[i, j] = temp - 60; refm[i][j] = temp - 60; j++; } i++; } } public static void Process2DArray(ref double[,] a2d) { for (int i = 10; i < size + 10; i++) for (int j = 0; j < size; j++) { a2d[i - 10, j] += a2d[0, j] + a2d[1, j]; a2d[i - 10, j] += 10; a2d[i - 10, j] *= a2d[i - 10, j] + a2d[2, j]; a2d[i - 10, j] -= a2d[i - 10, j] * a2d[3, j]; if ((a2d[i - 10, j] + a2d[4, j]) != 0) a2d[i - 10, j] /= a2d[i - 10, j] + a2d[4, j]; else a2d[i - 10, j] += a2d[i - 10, j] * a2d[4, j]; for (int k = 5; k < size; k++) a2d[i - 10, j] += a2d[k, j]; } } public static void ProcessJagged2DArray(ref double[][] a2d) { for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) { a2d[i][j] += a2d[0][j] + a2d[1][j]; a2d[i][j] += 10; a2d[i][j] *= a2d[i][j] + a2d[2][j]; a2d[i][j] -= a2d[i][j] * a2d[3][j]; if ((a2d[i][j] + a2d[4][j]) != 0) a2d[i][j] /= a2d[i][j] + a2d[4][j]; else a2d[i][j] += a2d[i][j] * a2d[4][j]; for (int k = 5; k < size; k++) a2d[i][j] += a2d[k][j]; } } public static void Init3DMatrix(double[,,] m, double[][] refm) { int i, j; i = 0; double temp; while (i < size) { j = 0; while (j < size) { temp = GenerateDbl(); m[i, 0, j] = temp - 60; refm[i][j] = temp - 60; j++; } i++; } } public static void Process3DArray(double[,,] a3d) { for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) { a3d[i, 0, j] += a3d[0, 0, j] + a3d[1, 0, j]; a3d[i, 0, j] *= a3d[i, 0, j] + a3d[2, 0, j]; a3d[i, 0, j] -= a3d[i, 0, j] * a3d[3, 0, j]; if ((a3d[i, 0, j] + a3d[4, 0, j]) != 0) a3d[i, 0, j] /= a3d[i, 0, j] + a3d[4, 0, j]; else a3d[i, 0, j] += a3d[i, 0, j] * a3d[4, 0, j]; for (int k = 5; k < size; k++) a3d[i, 0, j] += a3d[k, 0, j]; } } public static void ProcessJagged3DArray(double[][] a3d) { for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) { a3d[i][j] += a3d[0][j] + a3d[1][j]; a3d[i][j] *= a3d[i][j] + a3d[2][j]; a3d[i][j] -= a3d[i][j] * a3d[3][j]; if ((a3d[i][j] + a3d[4][j]) != 0) a3d[i][j] /= a3d[i][j] + a3d[4][j]; else a3d[i][j] += a3d[i][j] * a3d[4][j]; for (int k = 5; k < size; k++) a3d[i][j] += a3d[k][j]; } } public static int Main() { bool pass = false; int seed = Environment.GetEnvironmentVariable("CORECLR_SEED") switch { string seedStr when seedStr.Equals("random", StringComparison.OrdinalIgnoreCase) => new Random().Next(), string seedStr when int.TryParse(seedStr, out int envSeed) => envSeed, _ => DefaultSeed }; rand = new Random(seed); size = rand.Next(5, 10); Console.WriteLine(); Console.WriteLine("2D Array"); Console.WriteLine("Random seed: {0}; set environment variable CORECLR_SEED to this value to reproduce", seed); Console.WriteLine("Element manipulation of {0} by {0} matrices with different arithmatic operations", size); Console.WriteLine("Matrix is member of struct, element stores random double"); Console.WriteLine("array set/get, ref/out param are used"); ima = new ArrayStruct(size); double[][] refa2d = new double[size][]; Init2DMatrix(out ima.a2d, out refa2d); int m = 0; int n; while (m < size) { n = 0; while (n < size) { Process2DArray(ref ima.a2d); ProcessJagged2DArray(ref refa2d); n++; } m++; } for (int i = 0; i < size; i++) { pass = true; for (int j = 0; j < size; j++) if (ima.a2d[i, j] != refa2d[i][j]) if (!Double.IsNaN(ima.a2d[i, j]) || !Double.IsNaN(refa2d[i][j])) { Console.WriteLine("i={0}, j={1}, ima.a2d[i,j] {2}!=refa2d[i][j] {3}", i, j, ima.a2d[i, j], refa2d[i][j]); pass = false; } } if (pass) { try { ima.a2d[size, size] = 5; pass = false; } catch (IndexOutOfRangeException) { } } Console.WriteLine(); Console.WriteLine("3D Array"); Console.WriteLine("Element manipulation of 3D matrice with different arithmatic operations, size is {0}", size); Console.WriteLine("Matrix is member of struct, element stores random double"); ima = new ArrayStruct(size); double[][] refa3d = new double[size][]; for (int k = 0; k < refa3d.Length; k++) refa3d[k] = new double[size]; Init3DMatrix(ima.a3d, refa3d); m = 0; n = 0; while (m < size) { n = 0; while (n < size) { Process3DArray(ima.a3d); ProcessJagged3DArray(refa3d); n++; } m++; } for (int i = 0; i < size; i++) { pass = true; for (int j = 0; j < size; j++) if (ima.a3d[i, 0, j] != refa3d[i][j]) if (!Double.IsNaN(ima.a3d[i, 0, j]) || !Double.IsNaN(refa3d[i][j])) { Console.WriteLine("i={0}, j={1}, ima.a3d[i,0,j] {2}!=refa3d[i][j] {3}", i, j, ima.a3d[i, 0, j], refa3d[i][j]); pass = false; } } if (pass) { try { ima.a3d[size, size, size] = 5; pass = false; } catch (IndexOutOfRangeException) { } } Console.WriteLine(); if (pass) { Console.WriteLine("PASSED"); return 100; } else { Console.WriteLine("FAILED"); return 1; } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/Common/src/Interop/Windows/Interop.OBJECT_ATTRIBUTES.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; internal static partial class Interop { /// <summary> /// <a href="https://msdn.microsoft.com/en-us/library/windows/hardware/ff557749.aspx">OBJECT_ATTRIBUTES</a> structure. /// The OBJECT_ATTRIBUTES structure specifies attributes that can be applied to objects or object handles by routines /// that create objects and/or return handles to objects. /// </summary> internal unsafe struct OBJECT_ATTRIBUTES { public uint Length; /// <summary> /// Optional handle to root object directory for the given ObjectName. /// Can be a file system directory or object manager directory. /// </summary> public IntPtr RootDirectory; /// <summary> /// Name of the object. Must be fully qualified if RootDirectory isn't set. /// Otherwise is relative to RootDirectory. /// </summary> public UNICODE_STRING* ObjectName; public ObjectAttributes Attributes; /// <summary> /// If null, object will receive default security settings. /// </summary> public void* SecurityDescriptor; /// <summary> /// Optional quality of service to be applied to the object. Used to indicate /// security impersonation level and context tracking mode (dynamic or static). /// </summary> public SECURITY_QUALITY_OF_SERVICE* SecurityQualityOfService; /// <summary> /// Equivalent of InitializeObjectAttributes macro with the exception that you can directly set SQOS. /// </summary> public unsafe OBJECT_ATTRIBUTES(UNICODE_STRING* objectName, ObjectAttributes attributes, IntPtr rootDirectory, SECURITY_QUALITY_OF_SERVICE* securityQualityOfService = null) { Length = (uint)sizeof(OBJECT_ATTRIBUTES); RootDirectory = rootDirectory; ObjectName = objectName; Attributes = attributes; SecurityDescriptor = null; SecurityQualityOfService = securityQualityOfService; } } [Flags] public enum ObjectAttributes : uint { // https://msdn.microsoft.com/en-us/library/windows/hardware/ff564586.aspx // https://msdn.microsoft.com/en-us/library/windows/hardware/ff547804.aspx /// <summary> /// This handle can be inherited by child processes of the current process. /// </summary> OBJ_INHERIT = 0x00000002, /// <summary> /// This flag only applies to objects that are named within the object manager. /// By default, such objects are deleted when all open handles to them are closed. /// If this flag is specified, the object is not deleted when all open handles are closed. /// </summary> OBJ_PERMANENT = 0x00000010, /// <summary> /// Only a single handle can be open for this object. /// </summary> OBJ_EXCLUSIVE = 0x00000020, /// <summary> /// Lookups for this object should be case insensitive. /// </summary> OBJ_CASE_INSENSITIVE = 0x00000040, /// <summary> /// Create on existing object should open, not fail with STATUS_OBJECT_NAME_COLLISION. /// </summary> OBJ_OPENIF = 0x00000080, /// <summary> /// Open the symbolic link, not its target. /// </summary> OBJ_OPENLINK = 0x00000100, // Only accessible from kernel mode // OBJ_KERNEL_HANDLE // Access checks enforced, even in kernel mode // OBJ_FORCE_ACCESS_CHECK // OBJ_VALID_ATTRIBUTES = 0x000001F2 } }
// 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; internal static partial class Interop { /// <summary> /// <a href="https://msdn.microsoft.com/en-us/library/windows/hardware/ff557749.aspx">OBJECT_ATTRIBUTES</a> structure. /// The OBJECT_ATTRIBUTES structure specifies attributes that can be applied to objects or object handles by routines /// that create objects and/or return handles to objects. /// </summary> internal unsafe struct OBJECT_ATTRIBUTES { public uint Length; /// <summary> /// Optional handle to root object directory for the given ObjectName. /// Can be a file system directory or object manager directory. /// </summary> public IntPtr RootDirectory; /// <summary> /// Name of the object. Must be fully qualified if RootDirectory isn't set. /// Otherwise is relative to RootDirectory. /// </summary> public UNICODE_STRING* ObjectName; public ObjectAttributes Attributes; /// <summary> /// If null, object will receive default security settings. /// </summary> public void* SecurityDescriptor; /// <summary> /// Optional quality of service to be applied to the object. Used to indicate /// security impersonation level and context tracking mode (dynamic or static). /// </summary> public SECURITY_QUALITY_OF_SERVICE* SecurityQualityOfService; /// <summary> /// Equivalent of InitializeObjectAttributes macro with the exception that you can directly set SQOS. /// </summary> public unsafe OBJECT_ATTRIBUTES(UNICODE_STRING* objectName, ObjectAttributes attributes, IntPtr rootDirectory, SECURITY_QUALITY_OF_SERVICE* securityQualityOfService = null) { Length = (uint)sizeof(OBJECT_ATTRIBUTES); RootDirectory = rootDirectory; ObjectName = objectName; Attributes = attributes; SecurityDescriptor = null; SecurityQualityOfService = securityQualityOfService; } } [Flags] public enum ObjectAttributes : uint { // https://msdn.microsoft.com/en-us/library/windows/hardware/ff564586.aspx // https://msdn.microsoft.com/en-us/library/windows/hardware/ff547804.aspx /// <summary> /// This handle can be inherited by child processes of the current process. /// </summary> OBJ_INHERIT = 0x00000002, /// <summary> /// This flag only applies to objects that are named within the object manager. /// By default, such objects are deleted when all open handles to them are closed. /// If this flag is specified, the object is not deleted when all open handles are closed. /// </summary> OBJ_PERMANENT = 0x00000010, /// <summary> /// Only a single handle can be open for this object. /// </summary> OBJ_EXCLUSIVE = 0x00000020, /// <summary> /// Lookups for this object should be case insensitive. /// </summary> OBJ_CASE_INSENSITIVE = 0x00000040, /// <summary> /// Create on existing object should open, not fail with STATUS_OBJECT_NAME_COLLISION. /// </summary> OBJ_OPENIF = 0x00000080, /// <summary> /// Open the symbolic link, not its target. /// </summary> OBJ_OPENLINK = 0x00000100, // Only accessible from kernel mode // OBJ_KERNEL_HANDLE // Access checks enforced, even in kernel mode // OBJ_FORCE_ACCESS_CHECK // OBJ_VALID_ATTRIBUTES = 0x000001F2 } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/Interop/ArrayMarshalling/BoolArray/MarshalBoolArrayTest.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="MarshalBoolArrayTest.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="$(TestSourceDir)Common/CoreCLRTestLibrary/CoreCLRTestLibrary.csproj" /> <CMakeProjectReference Include="CMakeLists.txt" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="MarshalBoolArrayTest.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="$(TestSourceDir)Common/CoreCLRTestLibrary/CoreCLRTestLibrary.csproj" /> <CMakeProjectReference Include="CMakeLists.txt" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashAlgorithmNames.Apple.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using PAL_HashAlgorithm = Interop.AppleCrypto.PAL_HashAlgorithm; namespace System.Security.Cryptography { internal static partial class HashAlgorithmNames { internal static PAL_HashAlgorithm HashAlgorithmToPal(string hashAlgorithmId) => hashAlgorithmId switch { HashAlgorithmNames.MD5 => PAL_HashAlgorithm.Md5, HashAlgorithmNames.SHA1 => PAL_HashAlgorithm.Sha1, HashAlgorithmNames.SHA256 => PAL_HashAlgorithm.Sha256, HashAlgorithmNames.SHA384 => PAL_HashAlgorithm.Sha384, HashAlgorithmNames.SHA512 => PAL_HashAlgorithm.Sha512, _ => throw new CryptographicException(SR.Format(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithmId)) }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using PAL_HashAlgorithm = Interop.AppleCrypto.PAL_HashAlgorithm; namespace System.Security.Cryptography { internal static partial class HashAlgorithmNames { internal static PAL_HashAlgorithm HashAlgorithmToPal(string hashAlgorithmId) => hashAlgorithmId switch { HashAlgorithmNames.MD5 => PAL_HashAlgorithm.Md5, HashAlgorithmNames.SHA1 => PAL_HashAlgorithm.Sha1, HashAlgorithmNames.SHA256 => PAL_HashAlgorithm.Sha256, HashAlgorithmNames.SHA384 => PAL_HashAlgorithm.Sha384, HashAlgorithmNames.SHA512 => PAL_HashAlgorithm.Sha512, _ => throw new CryptographicException(SR.Format(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithmId)) }; } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Utils/ExceptionAggregator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ExceptionAggregator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections.Generic; using System.Threading; namespace System.Linq.Parallel { internal static class ExceptionAggregator { /// <summary> /// WrapEnumerable.ExceptionAggregator wraps the enumerable with another enumerator that will /// catch exceptions, and wrap each with an AggregateException. /// /// If PLINQ decides to execute a query sequentially, we will reuse LINQ-to-objects /// implementations for the different operators. However, we still need to throw /// AggregateException in the cases when parallel execution would have thrown an /// AggregateException. Thus, we introduce a wrapper enumerator that catches exceptions /// and wraps them with an AggregateException. /// </summary> internal static IEnumerable<TElement> WrapEnumerable<TElement>(IEnumerable<TElement> source, CancellationState cancellationState) { using (IEnumerator<TElement> enumerator = source.GetEnumerator()) { while (true) { TElement elem = default(TElement)!; try { if (!enumerator.MoveNext()) { yield break; } elem = enumerator.Current; } catch (Exception ex) { ThrowOCEorAggregateException(ex, cancellationState); } yield return elem; } } } /// <summary> /// A variant of WrapEnumerable that accepts a QueryOperatorEnumerator{,} instead of an IEnumerable{}. /// The code duplication is necessary to avoid extra virtual method calls that would otherwise be needed to /// convert the QueryOperatorEnumerator{,} to an IEnumerator{}. /// </summary> internal static IEnumerable<TElement> WrapQueryEnumerator<TElement, TIgnoreKey>(QueryOperatorEnumerator<TElement, TIgnoreKey> source, CancellationState cancellationState) { TElement elem = default(TElement)!; TIgnoreKey ignoreKey = default(TIgnoreKey)!; try { while (true) { try { if (!source.MoveNext(ref elem!, ref ignoreKey)) { yield break; } } catch (Exception ex) { ThrowOCEorAggregateException(ex, cancellationState); } yield return elem; } } finally { source.Dispose(); } } /// <summary> /// Accepts an exception, wraps it as if it was crossing the parallel->sequential boundary, and throws the /// wrapped exception. In sequential fallback cases, we use this method to throw exceptions that are consistent /// with exceptions thrown by PLINQ when the query is executed by worker tasks. /// /// The exception will be wrapped into an AggregateException, except for the case when the query is being /// legitimately cancelled, in which case we will propagate the CancellationException with the appropriate /// token. /// </summary> internal static void ThrowOCEorAggregateException(Exception ex, CancellationState cancellationState) { if (ThrowAnOCE(ex, cancellationState)) { CancellationState.ThrowWithStandardMessageIfCanceled( cancellationState.ExternalCancellationToken); } else { throw new AggregateException(ex); } } /// <summary> /// Wraps a function with a try/catch that morphs all exceptions into AggregateException. /// </summary> /// <typeparam name="T">The input argument type.</typeparam> /// <typeparam name="U">The return value type.</typeparam> /// <param name="f">A function to use internally.</param> /// <param name="cancellationState">The cancellation state to use.</param> /// <returns>A new function containing exception wrapping logic.</returns> internal static Func<T, U> WrapFunc<T, U>(Func<T, U> f, CancellationState cancellationState) { return t => { U retval = default(U)!; try { retval = f(t); } catch (Exception ex) { ThrowOCEorAggregateException(ex, cancellationState); } return retval; }; } // return: true ==> throw an OCE(externalCT) // false ==> thrown an AggregateException(ex). private static bool ThrowAnOCE(Exception ex, CancellationState cancellationState) { // if the query has been canceled and the exception represents this, we want to throw OCE // but otherwise we want to throw an AggregateException to mimic normal Plinq operation // See QueryTaskGroupState.WaitAll for the main plinq exception handling logic. // check for co-operative cancellation. if (ex is OperationCanceledException cancelEx) { if (cancelEx.CancellationToken == cancellationState.ExternalCancellationToken && cancellationState.ExternalCancellationToken.IsCancellationRequested) { return true; // let the OCE(extCT) be rethrown. } // check for external cancellation which triggered the mergedToken. if (cancelEx.CancellationToken == cancellationState.MergedCancellationToken && cancellationState.MergedCancellationToken.IsCancellationRequested && cancellationState.ExternalCancellationToken.IsCancellationRequested) { return true; // convert internal cancellation back to OCE(extCT). } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ExceptionAggregator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections.Generic; using System.Threading; namespace System.Linq.Parallel { internal static class ExceptionAggregator { /// <summary> /// WrapEnumerable.ExceptionAggregator wraps the enumerable with another enumerator that will /// catch exceptions, and wrap each with an AggregateException. /// /// If PLINQ decides to execute a query sequentially, we will reuse LINQ-to-objects /// implementations for the different operators. However, we still need to throw /// AggregateException in the cases when parallel execution would have thrown an /// AggregateException. Thus, we introduce a wrapper enumerator that catches exceptions /// and wraps them with an AggregateException. /// </summary> internal static IEnumerable<TElement> WrapEnumerable<TElement>(IEnumerable<TElement> source, CancellationState cancellationState) { using (IEnumerator<TElement> enumerator = source.GetEnumerator()) { while (true) { TElement elem = default(TElement)!; try { if (!enumerator.MoveNext()) { yield break; } elem = enumerator.Current; } catch (Exception ex) { ThrowOCEorAggregateException(ex, cancellationState); } yield return elem; } } } /// <summary> /// A variant of WrapEnumerable that accepts a QueryOperatorEnumerator{,} instead of an IEnumerable{}. /// The code duplication is necessary to avoid extra virtual method calls that would otherwise be needed to /// convert the QueryOperatorEnumerator{,} to an IEnumerator{}. /// </summary> internal static IEnumerable<TElement> WrapQueryEnumerator<TElement, TIgnoreKey>(QueryOperatorEnumerator<TElement, TIgnoreKey> source, CancellationState cancellationState) { TElement elem = default(TElement)!; TIgnoreKey ignoreKey = default(TIgnoreKey)!; try { while (true) { try { if (!source.MoveNext(ref elem!, ref ignoreKey)) { yield break; } } catch (Exception ex) { ThrowOCEorAggregateException(ex, cancellationState); } yield return elem; } } finally { source.Dispose(); } } /// <summary> /// Accepts an exception, wraps it as if it was crossing the parallel->sequential boundary, and throws the /// wrapped exception. In sequential fallback cases, we use this method to throw exceptions that are consistent /// with exceptions thrown by PLINQ when the query is executed by worker tasks. /// /// The exception will be wrapped into an AggregateException, except for the case when the query is being /// legitimately cancelled, in which case we will propagate the CancellationException with the appropriate /// token. /// </summary> internal static void ThrowOCEorAggregateException(Exception ex, CancellationState cancellationState) { if (ThrowAnOCE(ex, cancellationState)) { CancellationState.ThrowWithStandardMessageIfCanceled( cancellationState.ExternalCancellationToken); } else { throw new AggregateException(ex); } } /// <summary> /// Wraps a function with a try/catch that morphs all exceptions into AggregateException. /// </summary> /// <typeparam name="T">The input argument type.</typeparam> /// <typeparam name="U">The return value type.</typeparam> /// <param name="f">A function to use internally.</param> /// <param name="cancellationState">The cancellation state to use.</param> /// <returns>A new function containing exception wrapping logic.</returns> internal static Func<T, U> WrapFunc<T, U>(Func<T, U> f, CancellationState cancellationState) { return t => { U retval = default(U)!; try { retval = f(t); } catch (Exception ex) { ThrowOCEorAggregateException(ex, cancellationState); } return retval; }; } // return: true ==> throw an OCE(externalCT) // false ==> thrown an AggregateException(ex). private static bool ThrowAnOCE(Exception ex, CancellationState cancellationState) { // if the query has been canceled and the exception represents this, we want to throw OCE // but otherwise we want to throw an AggregateException to mimic normal Plinq operation // See QueryTaskGroupState.WaitAll for the main plinq exception handling logic. // check for co-operative cancellation. if (ex is OperationCanceledException cancelEx) { if (cancelEx.CancellationToken == cancellationState.ExternalCancellationToken && cancellationState.ExternalCancellationToken.IsCancellationRequested) { return true; // let the OCE(extCT) be rethrown. } // check for external cancellation which triggered the mergedToken. if (cancelEx.CancellationToken == cancellationState.MergedCancellationToken && cancellationState.MergedCancellationToken.IsCancellationRequested && cancellationState.ExternalCancellationToken.IsCancellationRequested) { return true; // convert internal cancellation back to OCE(extCT). } } return false; } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TplEventSource.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; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace System.Threading.Tasks { /// <summary>Provides an event source for tracing TPL information.</summary> [EventSource( Name = "System.Threading.Tasks.TplEventSource", Guid = "2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5", LocalizationResources = #if CORECLR "System.Private.CoreLib.Strings" #else null #endif )] [EventSourceAutoGenerate] internal sealed partial class TplEventSource : EventSource { #if !ES_BUILD_STANDALONE private const string EventSourceSuppressMessage = "Parameters to this method are primitive and are trimmer safe"; #endif /// Used to determine if tasks should generate Activity IDs for themselves internal bool TasksSetActivityIds; // This keyword is set internal bool Debug; private bool DebugActivityId; private const int DefaultAppDomainID = 1; /// <summary> /// Get callbacks when the ETW sends us commands` /// </summary> protected override void OnEventCommand(EventCommandEventArgs command) { if (IsEnabled(EventLevel.Informational, Keywords.TasksFlowActivityIds)) ActivityTracker.Instance.Enable(); else TasksSetActivityIds = IsEnabled(EventLevel.Informational, Keywords.TasksSetActivityIds); Debug = IsEnabled(EventLevel.Informational, Keywords.Debug); DebugActivityId = IsEnabled(EventLevel.Informational, Keywords.DebugActivityId); } /// <summary> /// Defines the singleton instance for the TPL ETW provider. /// </summary> public static readonly TplEventSource Log = new TplEventSource(); // Parameterized constructor to block initialization and ensure the EventSourceGenerator is creating the default constructor // as you can't make a constructor partial. private TplEventSource(int _) { } /// <summary>Configured behavior of a task wait operation.</summary> public enum TaskWaitBehavior : int { /// <summary>A synchronous wait.</summary> Synchronous = 1, /// <summary>An asynchronous await.</summary> Asynchronous = 2 } /// <summary>ETW tasks that have start/stop events.</summary> public static class Tasks // this name is important for EventSource { /// <summary>A parallel loop.</summary> public const EventTask Loop = (EventTask)1; /// <summary>A parallel invoke.</summary> public const EventTask Invoke = (EventTask)2; /// <summary>Executing a Task.</summary> public const EventTask TaskExecute = (EventTask)3; /// <summary>Waiting on a Task.</summary> public const EventTask TaskWait = (EventTask)4; /// <summary>A fork/join task within a loop or invoke.</summary> public const EventTask ForkJoin = (EventTask)5; /// <summary>A task is scheduled to execute.</summary> public const EventTask TaskScheduled = (EventTask)6; /// <summary>An await task continuation is scheduled to execute.</summary> public const EventTask AwaitTaskContinuationScheduled = (EventTask)7; /// <summary>AsyncCausalityFunctionality.</summary> public const EventTask TraceOperation = (EventTask)8; public const EventTask TraceSynchronousWork = (EventTask)9; } public static class Keywords // this name is important for EventSource { /// <summary> /// Only the most basic information about the workings of the task library /// This sets activity IDS and logs when tasks are schedules (or waits begin) /// But are otherwise silent /// </summary> public const EventKeywords TaskTransfer = (EventKeywords)1; /// <summary> /// TaskTranser events plus events when tasks start and stop /// </summary> public const EventKeywords Tasks = (EventKeywords)2; /// <summary> /// Events associted with the higher level parallel APIs /// </summary> public const EventKeywords Parallel = (EventKeywords)4; /// <summary> /// These are relatively verbose events that effectively just redirect /// the windows AsyncCausalityTracer to ETW /// </summary> public const EventKeywords AsyncCausalityOperation = (EventKeywords)8; public const EventKeywords AsyncCausalityRelation = (EventKeywords)0x10; public const EventKeywords AsyncCausalitySynchronousWork = (EventKeywords)0x20; /// <summary> /// Emit the stops as well as the schedule/start events /// </summary> public const EventKeywords TaskStops = (EventKeywords)0x40; /// <summary> /// TasksFlowActivityIds indicate that activity ID flow from one task /// to any task created by it. /// </summary> public const EventKeywords TasksFlowActivityIds = (EventKeywords)0x80; /// <summary> /// Events related to the happenings of async methods. /// </summary> public const EventKeywords AsyncMethod = (EventKeywords)0x100; /// <summary> /// TasksSetActivityIds will cause the task operations to set Activity Ids /// This option is incompatible with TasksFlowActivityIds flow is ignored /// if that keyword is set. This option is likely to be removed in the future /// </summary> public const EventKeywords TasksSetActivityIds = (EventKeywords)0x10000; /// <summary> /// Relatively Verbose logging meant for debugging the Task library itself. Will probably be removed in the future /// </summary> public const EventKeywords Debug = (EventKeywords)0x20000; /// <summary> /// Relatively Verbose logging meant for debugging the Task library itself. Will probably be removed in the future /// </summary> public const EventKeywords DebugActivityId = (EventKeywords)0x40000; } //----------------------------------------------------------------------------------- // // TPL Event IDs (must be unique) // /// <summary>A task is scheduled to a task scheduler.</summary> private const int TASKSCHEDULED_ID = 7; /// <summary>A task is about to execute.</summary> private const int TASKSTARTED_ID = 8; /// <summary>A task has finished executing.</summary> private const int TASKCOMPLETED_ID = 9; /// <summary>A wait on a task is beginning.</summary> private const int TASKWAITBEGIN_ID = 10; /// <summary>A wait on a task is ending.</summary> private const int TASKWAITEND_ID = 11; /// <summary>A continuation of a task is scheduled.</summary> private const int AWAITTASKCONTINUATIONSCHEDULED_ID = 12; /// <summary>A continuation of a taskWaitEnd is complete </summary> private const int TASKWAITCONTINUATIONCOMPLETE_ID = 13; /// <summary>A continuation of a taskWaitEnd is complete </summary> private const int TASKWAITCONTINUATIONSTARTED_ID = 19; private const int TRACEOPERATIONSTART_ID = 14; private const int TRACEOPERATIONSTOP_ID = 15; private const int TRACEOPERATIONRELATION_ID = 16; private const int TRACESYNCHRONOUSWORKSTART_ID = 17; private const int TRACESYNCHRONOUSWORKSTOP_ID = 18; //----------------------------------------------------------------------------------- // // Task Events // // These are all verbose events, so we need to call IsEnabled(EventLevel.Verbose, ALL_KEYWORDS) // call. However since the IsEnabled(l,k) call is more expensive than IsEnabled(), we only want // to incur this cost when instrumentation is enabled. So the Task codepaths that call these // event functions still do the check for IsEnabled() #region TaskScheduled /// <summary> /// Fired when a task is queued to a TaskScheduler. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> /// <param name="CreatingTaskID">The task ID</param> /// <param name="TaskCreationOptions">The options used to create the task.</param> /// <param name="appDomain">The ID for the current AppDomain.</param> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif [Event(TASKSCHEDULED_ID, Task = Tasks.TaskScheduled, Version = 1, Opcode = EventOpcode.Send, Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer | Keywords.Tasks)] public void TaskScheduled( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID, int CreatingTaskID, int TaskCreationOptions, int appDomain = DefaultAppDomainID) { // IsEnabled() call is an inlined quick check that makes this very fast when provider is off if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer | Keywords.Tasks)) { unsafe { EventData* eventPayload = stackalloc EventData[6]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID)); eventPayload[0].Reserved = 0; eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID)); eventPayload[1].Reserved = 0; eventPayload[2].Size = sizeof(int); eventPayload[2].DataPointer = ((IntPtr)(&TaskID)); eventPayload[2].Reserved = 0; eventPayload[3].Size = sizeof(int); eventPayload[3].DataPointer = ((IntPtr)(&CreatingTaskID)); eventPayload[3].Reserved = 0; eventPayload[4].Size = sizeof(int); eventPayload[4].DataPointer = ((IntPtr)(&TaskCreationOptions)); eventPayload[4].Reserved = 0; eventPayload[5].Size = sizeof(int); eventPayload[5].DataPointer = ((IntPtr)(&appDomain)); eventPayload[5].Reserved = 0; if (TasksSetActivityIds) { Guid childActivityId = CreateGuidForTaskID(TaskID); WriteEventWithRelatedActivityIdCore(TASKSCHEDULED_ID, &childActivityId, 6, eventPayload); } else WriteEventCore(TASKSCHEDULED_ID, 6, eventPayload); } } } #endregion #region TaskStarted /// <summary> /// Fired just before a task actually starts executing. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> [Event(TASKSTARTED_ID, Level = EventLevel.Informational, Keywords = Keywords.Tasks)] public void TaskStarted( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID) { if (IsEnabled(EventLevel.Informational, Keywords.Tasks)) WriteEvent(TASKSTARTED_ID, OriginatingTaskSchedulerID, OriginatingTaskID, TaskID); } #endregion #region TaskCompleted /// <summary> /// Fired right after a task finished executing. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> /// <param name="IsExceptional">Whether the task completed due to an error.</param> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif [Event(TASKCOMPLETED_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.TaskStops)] public void TaskCompleted( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID, bool IsExceptional) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.Tasks)) { unsafe { EventData* eventPayload = stackalloc EventData[4]; int isExceptionalInt = IsExceptional ? 1 : 0; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID)); eventPayload[0].Reserved = 0; eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID)); eventPayload[1].Reserved = 0; eventPayload[2].Size = sizeof(int); eventPayload[2].DataPointer = ((IntPtr)(&TaskID)); eventPayload[2].Reserved = 0; eventPayload[3].Size = sizeof(int); eventPayload[3].DataPointer = ((IntPtr)(&isExceptionalInt)); eventPayload[3].Reserved = 0; WriteEventCore(TASKCOMPLETED_ID, 4, eventPayload); } } } #endregion #region TaskWaitBegin /// <summary> /// Fired when starting to wait for a taks's completion explicitly or implicitly. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> /// <param name="Behavior">Configured behavior for the wait.</param> /// <param name="ContinueWithTaskID"> /// If known, if 'TaskID' has a 'continueWith' task, mention give its ID here. /// 0 means unknown. This allows better visualization of the common sequential chaining case. /// </param> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif [Event(TASKWAITBEGIN_ID, Version = 3, Task = TplEventSource.Tasks.TaskWait, Opcode = EventOpcode.Send, Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer | Keywords.Tasks)] public void TaskWaitBegin( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID, TaskWaitBehavior Behavior, int ContinueWithTaskID) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer | Keywords.Tasks)) { unsafe { EventData* eventPayload = stackalloc EventData[5]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID)); eventPayload[0].Reserved = 0; eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID)); eventPayload[1].Reserved = 0; eventPayload[2].Size = sizeof(int); eventPayload[2].DataPointer = ((IntPtr)(&TaskID)); eventPayload[2].Reserved = 0; eventPayload[3].Size = sizeof(int); eventPayload[3].DataPointer = ((IntPtr)(&Behavior)); eventPayload[3].Reserved = 0; eventPayload[4].Size = sizeof(int); eventPayload[4].DataPointer = ((IntPtr)(&ContinueWithTaskID)); eventPayload[4].Reserved = 0; if (TasksSetActivityIds) { Guid childActivityId = CreateGuidForTaskID(TaskID); WriteEventWithRelatedActivityIdCore(TASKWAITBEGIN_ID, &childActivityId, 5, eventPayload); } else { WriteEventCore(TASKWAITBEGIN_ID, 5, eventPayload); } } } } #endregion /// <summary> /// Fired when the wait for a tasks completion returns. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> [Event(TASKWAITEND_ID, Level = EventLevel.Verbose, Keywords = Keywords.Tasks)] public void TaskWaitEnd( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID) { // Log an event if indicated. if (IsEnabled() && IsEnabled(EventLevel.Verbose, Keywords.Tasks)) WriteEvent(TASKWAITEND_ID, OriginatingTaskSchedulerID, OriginatingTaskID, TaskID); } /// <summary> /// Fired when the work (method) associated with a TaskWaitEnd completes /// </summary> /// <param name="TaskID">The task ID.</param> [Event(TASKWAITCONTINUATIONCOMPLETE_ID, Level = EventLevel.Verbose, Keywords = Keywords.TaskStops)] public void TaskWaitContinuationComplete(int TaskID) { // Log an event if indicated. if (IsEnabled() && IsEnabled(EventLevel.Verbose, Keywords.TaskStops)) WriteEvent(TASKWAITCONTINUATIONCOMPLETE_ID, TaskID); } /// <summary> /// Fired when the work (method) associated with a TaskWaitEnd completes /// </summary> /// <param name="TaskID">The task ID.</param> [Event(TASKWAITCONTINUATIONSTARTED_ID, Level = EventLevel.Verbose, Keywords = Keywords.Tasks)] public void TaskWaitContinuationStarted(int TaskID) { // Log an event if indicated. if (IsEnabled() && IsEnabled(EventLevel.Verbose, Keywords.Tasks)) WriteEvent(TASKWAITCONTINUATIONSTARTED_ID, TaskID); } /// <summary> /// Fired when the an asynchronous continuation for a task is scheduled /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="ContinueWithTaskId">The ID of the continuation object.</param> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif [Event(AWAITTASKCONTINUATIONSCHEDULED_ID, Task = Tasks.AwaitTaskContinuationScheduled, Opcode = EventOpcode.Send, Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer | Keywords.Tasks)] public void AwaitTaskContinuationScheduled( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int ContinueWithTaskId) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer | Keywords.Tasks)) { unsafe { EventData* eventPayload = stackalloc EventData[3]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID)); eventPayload[0].Reserved = 0; eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID)); eventPayload[1].Reserved = 0; eventPayload[2].Size = sizeof(int); eventPayload[2].DataPointer = ((IntPtr)(&ContinueWithTaskId)); eventPayload[2].Reserved = 0; if (TasksSetActivityIds) { Guid continuationActivityId = CreateGuidForTaskID(ContinueWithTaskId); WriteEventWithRelatedActivityIdCore(AWAITTASKCONTINUATIONSCHEDULED_ID, &continuationActivityId, 3, eventPayload); } else WriteEventCore(AWAITTASKCONTINUATIONSCHEDULED_ID, 3, eventPayload); } } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif [Event(TRACEOPERATIONSTART_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)] public void TraceOperationBegin(int TaskID, string OperationName, long RelatedContext) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityOperation)) { unsafe { fixed (char* operationNamePtr = OperationName) { EventData* eventPayload = stackalloc EventData[3]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr)(&TaskID)); eventPayload[0].Reserved = 0; eventPayload[1].Size = ((OperationName.Length + 1) * 2); eventPayload[1].DataPointer = ((IntPtr)operationNamePtr); eventPayload[1].Reserved = 0; eventPayload[2].Size = sizeof(long); eventPayload[2].DataPointer = ((IntPtr)(&RelatedContext)); eventPayload[2].Reserved = 0; WriteEventCore(TRACEOPERATIONSTART_ID, 3, eventPayload); } } } } [Event(TRACEOPERATIONRELATION_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityRelation)] public void TraceOperationRelation(int TaskID, CausalityRelation Relation) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityRelation)) WriteEvent(TRACEOPERATIONRELATION_ID, TaskID, (int)Relation); // optimized overload for this exists } [Event(TRACEOPERATIONSTOP_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)] public void TraceOperationEnd(int TaskID, AsyncCausalityStatus Status) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityOperation)) WriteEvent(TRACEOPERATIONSTOP_ID, TaskID, (int)Status); // optimized overload for this exists } [Event(TRACESYNCHRONOUSWORKSTART_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)] public void TraceSynchronousWorkBegin(int TaskID, CausalitySynchronousWork Work) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalitySynchronousWork)) WriteEvent(TRACESYNCHRONOUSWORKSTART_ID, TaskID, (int)Work); // optimized overload for this exists } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif [Event(TRACESYNCHRONOUSWORKSTOP_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)] public void TraceSynchronousWorkEnd(CausalitySynchronousWork Work) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalitySynchronousWork)) { unsafe { EventData* eventPayload = stackalloc EventData[1]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr)(&Work)); eventPayload[0].Reserved = 0; WriteEventCore(TRACESYNCHRONOUSWORKSTOP_ID, 1, eventPayload); } } } [NonEvent] public unsafe void RunningContinuation(int TaskID, object Object) { RunningContinuation(TaskID, (long)*((void**)Unsafe.AsPointer(ref Object))); } [Event(20, Keywords = Keywords.Debug)] private void RunningContinuation(int TaskID, long Object) { if (Debug) WriteEvent(20, TaskID, Object); } [NonEvent] public unsafe void RunningContinuationList(int TaskID, int Index, object Object) { RunningContinuationList(TaskID, Index, (long)*((void**)Unsafe.AsPointer(ref Object))); } [Event(21, Keywords = Keywords.Debug)] public void RunningContinuationList(int TaskID, int Index, long Object) { if (Debug) WriteEvent(21, TaskID, Index, Object); } [Event(23, Keywords = Keywords.Debug)] public void DebugFacilityMessage(string Facility, string Message) { WriteEvent(23, Facility, Message); } [Event(24, Keywords = Keywords.Debug)] public void DebugFacilityMessage1(string Facility, string Message, string Value1) { WriteEvent(24, Facility, Message, Value1); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = "Guid parameter is safe with WriteEvent")] [Event(25, Keywords = Keywords.DebugActivityId)] public void SetActivityId(Guid NewId) { if (DebugActivityId) WriteEvent(25, NewId); } [Event(26, Keywords = Keywords.Debug)] public void NewID(int TaskID) { if (Debug) WriteEvent(26, TaskID); } [NonEvent] public void IncompleteAsyncMethod(IAsyncStateMachineBox stateMachineBox) { System.Diagnostics.Debug.Assert(stateMachineBox != null); if (IsEnabled() && IsEnabled(EventLevel.Warning, Keywords.AsyncMethod)) { IAsyncStateMachine stateMachine = stateMachineBox.GetStateMachineObject(); if (stateMachine != null) { string description = AsyncMethodBuilderCore.GetAsyncStateMachineDescription(stateMachine); IncompleteAsyncMethod(description); } } } [Event(27, Level = EventLevel.Warning, Keywords = Keywords.AsyncMethod)] private void IncompleteAsyncMethod(string stateMachineDescription) => WriteEvent(27, stateMachineDescription); /// <summary> /// Activity IDs are GUIDS but task IDS are integers (and are not unique across appdomains /// This routine creates a process wide unique GUID given a task ID /// </summary> internal static Guid CreateGuidForTaskID(int taskID) { // The thread pool generated a process wide unique GUID from a task GUID by // using the taskGuid, the appdomain ID, and 8 bytes of 'randomization' chosen by // using the last 8 bytes as the provider GUID for this provider. // These were generated by CreateGuid, and are reasonably random (and thus unlikely to collide int pid = Environment.ProcessId; return new Guid(taskID, (short)DefaultAppDomainID, (short)(DefaultAppDomainID >> 16), (byte)pid, (byte)(pid >> 8), (byte)(pid >> 16), (byte)(pid >> 24), 0xff, 0xdc, 0xd7, 0xb5); } } }
// 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; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace System.Threading.Tasks { /// <summary>Provides an event source for tracing TPL information.</summary> [EventSource( Name = "System.Threading.Tasks.TplEventSource", Guid = "2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5", LocalizationResources = #if CORECLR "System.Private.CoreLib.Strings" #else null #endif )] [EventSourceAutoGenerate] internal sealed partial class TplEventSource : EventSource { #if !ES_BUILD_STANDALONE private const string EventSourceSuppressMessage = "Parameters to this method are primitive and are trimmer safe"; #endif /// Used to determine if tasks should generate Activity IDs for themselves internal bool TasksSetActivityIds; // This keyword is set internal bool Debug; private bool DebugActivityId; private const int DefaultAppDomainID = 1; /// <summary> /// Get callbacks when the ETW sends us commands` /// </summary> protected override void OnEventCommand(EventCommandEventArgs command) { if (IsEnabled(EventLevel.Informational, Keywords.TasksFlowActivityIds)) ActivityTracker.Instance.Enable(); else TasksSetActivityIds = IsEnabled(EventLevel.Informational, Keywords.TasksSetActivityIds); Debug = IsEnabled(EventLevel.Informational, Keywords.Debug); DebugActivityId = IsEnabled(EventLevel.Informational, Keywords.DebugActivityId); } /// <summary> /// Defines the singleton instance for the TPL ETW provider. /// </summary> public static readonly TplEventSource Log = new TplEventSource(); // Parameterized constructor to block initialization and ensure the EventSourceGenerator is creating the default constructor // as you can't make a constructor partial. private TplEventSource(int _) { } /// <summary>Configured behavior of a task wait operation.</summary> public enum TaskWaitBehavior : int { /// <summary>A synchronous wait.</summary> Synchronous = 1, /// <summary>An asynchronous await.</summary> Asynchronous = 2 } /// <summary>ETW tasks that have start/stop events.</summary> public static class Tasks // this name is important for EventSource { /// <summary>A parallel loop.</summary> public const EventTask Loop = (EventTask)1; /// <summary>A parallel invoke.</summary> public const EventTask Invoke = (EventTask)2; /// <summary>Executing a Task.</summary> public const EventTask TaskExecute = (EventTask)3; /// <summary>Waiting on a Task.</summary> public const EventTask TaskWait = (EventTask)4; /// <summary>A fork/join task within a loop or invoke.</summary> public const EventTask ForkJoin = (EventTask)5; /// <summary>A task is scheduled to execute.</summary> public const EventTask TaskScheduled = (EventTask)6; /// <summary>An await task continuation is scheduled to execute.</summary> public const EventTask AwaitTaskContinuationScheduled = (EventTask)7; /// <summary>AsyncCausalityFunctionality.</summary> public const EventTask TraceOperation = (EventTask)8; public const EventTask TraceSynchronousWork = (EventTask)9; } public static class Keywords // this name is important for EventSource { /// <summary> /// Only the most basic information about the workings of the task library /// This sets activity IDS and logs when tasks are schedules (or waits begin) /// But are otherwise silent /// </summary> public const EventKeywords TaskTransfer = (EventKeywords)1; /// <summary> /// TaskTranser events plus events when tasks start and stop /// </summary> public const EventKeywords Tasks = (EventKeywords)2; /// <summary> /// Events associted with the higher level parallel APIs /// </summary> public const EventKeywords Parallel = (EventKeywords)4; /// <summary> /// These are relatively verbose events that effectively just redirect /// the windows AsyncCausalityTracer to ETW /// </summary> public const EventKeywords AsyncCausalityOperation = (EventKeywords)8; public const EventKeywords AsyncCausalityRelation = (EventKeywords)0x10; public const EventKeywords AsyncCausalitySynchronousWork = (EventKeywords)0x20; /// <summary> /// Emit the stops as well as the schedule/start events /// </summary> public const EventKeywords TaskStops = (EventKeywords)0x40; /// <summary> /// TasksFlowActivityIds indicate that activity ID flow from one task /// to any task created by it. /// </summary> public const EventKeywords TasksFlowActivityIds = (EventKeywords)0x80; /// <summary> /// Events related to the happenings of async methods. /// </summary> public const EventKeywords AsyncMethod = (EventKeywords)0x100; /// <summary> /// TasksSetActivityIds will cause the task operations to set Activity Ids /// This option is incompatible with TasksFlowActivityIds flow is ignored /// if that keyword is set. This option is likely to be removed in the future /// </summary> public const EventKeywords TasksSetActivityIds = (EventKeywords)0x10000; /// <summary> /// Relatively Verbose logging meant for debugging the Task library itself. Will probably be removed in the future /// </summary> public const EventKeywords Debug = (EventKeywords)0x20000; /// <summary> /// Relatively Verbose logging meant for debugging the Task library itself. Will probably be removed in the future /// </summary> public const EventKeywords DebugActivityId = (EventKeywords)0x40000; } //----------------------------------------------------------------------------------- // // TPL Event IDs (must be unique) // /// <summary>A task is scheduled to a task scheduler.</summary> private const int TASKSCHEDULED_ID = 7; /// <summary>A task is about to execute.</summary> private const int TASKSTARTED_ID = 8; /// <summary>A task has finished executing.</summary> private const int TASKCOMPLETED_ID = 9; /// <summary>A wait on a task is beginning.</summary> private const int TASKWAITBEGIN_ID = 10; /// <summary>A wait on a task is ending.</summary> private const int TASKWAITEND_ID = 11; /// <summary>A continuation of a task is scheduled.</summary> private const int AWAITTASKCONTINUATIONSCHEDULED_ID = 12; /// <summary>A continuation of a taskWaitEnd is complete </summary> private const int TASKWAITCONTINUATIONCOMPLETE_ID = 13; /// <summary>A continuation of a taskWaitEnd is complete </summary> private const int TASKWAITCONTINUATIONSTARTED_ID = 19; private const int TRACEOPERATIONSTART_ID = 14; private const int TRACEOPERATIONSTOP_ID = 15; private const int TRACEOPERATIONRELATION_ID = 16; private const int TRACESYNCHRONOUSWORKSTART_ID = 17; private const int TRACESYNCHRONOUSWORKSTOP_ID = 18; //----------------------------------------------------------------------------------- // // Task Events // // These are all verbose events, so we need to call IsEnabled(EventLevel.Verbose, ALL_KEYWORDS) // call. However since the IsEnabled(l,k) call is more expensive than IsEnabled(), we only want // to incur this cost when instrumentation is enabled. So the Task codepaths that call these // event functions still do the check for IsEnabled() #region TaskScheduled /// <summary> /// Fired when a task is queued to a TaskScheduler. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> /// <param name="CreatingTaskID">The task ID</param> /// <param name="TaskCreationOptions">The options used to create the task.</param> /// <param name="appDomain">The ID for the current AppDomain.</param> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif [Event(TASKSCHEDULED_ID, Task = Tasks.TaskScheduled, Version = 1, Opcode = EventOpcode.Send, Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer | Keywords.Tasks)] public void TaskScheduled( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID, int CreatingTaskID, int TaskCreationOptions, int appDomain = DefaultAppDomainID) { // IsEnabled() call is an inlined quick check that makes this very fast when provider is off if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer | Keywords.Tasks)) { unsafe { EventData* eventPayload = stackalloc EventData[6]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID)); eventPayload[0].Reserved = 0; eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID)); eventPayload[1].Reserved = 0; eventPayload[2].Size = sizeof(int); eventPayload[2].DataPointer = ((IntPtr)(&TaskID)); eventPayload[2].Reserved = 0; eventPayload[3].Size = sizeof(int); eventPayload[3].DataPointer = ((IntPtr)(&CreatingTaskID)); eventPayload[3].Reserved = 0; eventPayload[4].Size = sizeof(int); eventPayload[4].DataPointer = ((IntPtr)(&TaskCreationOptions)); eventPayload[4].Reserved = 0; eventPayload[5].Size = sizeof(int); eventPayload[5].DataPointer = ((IntPtr)(&appDomain)); eventPayload[5].Reserved = 0; if (TasksSetActivityIds) { Guid childActivityId = CreateGuidForTaskID(TaskID); WriteEventWithRelatedActivityIdCore(TASKSCHEDULED_ID, &childActivityId, 6, eventPayload); } else WriteEventCore(TASKSCHEDULED_ID, 6, eventPayload); } } } #endregion #region TaskStarted /// <summary> /// Fired just before a task actually starts executing. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> [Event(TASKSTARTED_ID, Level = EventLevel.Informational, Keywords = Keywords.Tasks)] public void TaskStarted( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID) { if (IsEnabled(EventLevel.Informational, Keywords.Tasks)) WriteEvent(TASKSTARTED_ID, OriginatingTaskSchedulerID, OriginatingTaskID, TaskID); } #endregion #region TaskCompleted /// <summary> /// Fired right after a task finished executing. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> /// <param name="IsExceptional">Whether the task completed due to an error.</param> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif [Event(TASKCOMPLETED_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.TaskStops)] public void TaskCompleted( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID, bool IsExceptional) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.Tasks)) { unsafe { EventData* eventPayload = stackalloc EventData[4]; int isExceptionalInt = IsExceptional ? 1 : 0; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID)); eventPayload[0].Reserved = 0; eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID)); eventPayload[1].Reserved = 0; eventPayload[2].Size = sizeof(int); eventPayload[2].DataPointer = ((IntPtr)(&TaskID)); eventPayload[2].Reserved = 0; eventPayload[3].Size = sizeof(int); eventPayload[3].DataPointer = ((IntPtr)(&isExceptionalInt)); eventPayload[3].Reserved = 0; WriteEventCore(TASKCOMPLETED_ID, 4, eventPayload); } } } #endregion #region TaskWaitBegin /// <summary> /// Fired when starting to wait for a taks's completion explicitly or implicitly. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> /// <param name="Behavior">Configured behavior for the wait.</param> /// <param name="ContinueWithTaskID"> /// If known, if 'TaskID' has a 'continueWith' task, mention give its ID here. /// 0 means unknown. This allows better visualization of the common sequential chaining case. /// </param> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif [Event(TASKWAITBEGIN_ID, Version = 3, Task = TplEventSource.Tasks.TaskWait, Opcode = EventOpcode.Send, Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer | Keywords.Tasks)] public void TaskWaitBegin( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID, TaskWaitBehavior Behavior, int ContinueWithTaskID) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer | Keywords.Tasks)) { unsafe { EventData* eventPayload = stackalloc EventData[5]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID)); eventPayload[0].Reserved = 0; eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID)); eventPayload[1].Reserved = 0; eventPayload[2].Size = sizeof(int); eventPayload[2].DataPointer = ((IntPtr)(&TaskID)); eventPayload[2].Reserved = 0; eventPayload[3].Size = sizeof(int); eventPayload[3].DataPointer = ((IntPtr)(&Behavior)); eventPayload[3].Reserved = 0; eventPayload[4].Size = sizeof(int); eventPayload[4].DataPointer = ((IntPtr)(&ContinueWithTaskID)); eventPayload[4].Reserved = 0; if (TasksSetActivityIds) { Guid childActivityId = CreateGuidForTaskID(TaskID); WriteEventWithRelatedActivityIdCore(TASKWAITBEGIN_ID, &childActivityId, 5, eventPayload); } else { WriteEventCore(TASKWAITBEGIN_ID, 5, eventPayload); } } } } #endregion /// <summary> /// Fired when the wait for a tasks completion returns. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> [Event(TASKWAITEND_ID, Level = EventLevel.Verbose, Keywords = Keywords.Tasks)] public void TaskWaitEnd( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID) { // Log an event if indicated. if (IsEnabled() && IsEnabled(EventLevel.Verbose, Keywords.Tasks)) WriteEvent(TASKWAITEND_ID, OriginatingTaskSchedulerID, OriginatingTaskID, TaskID); } /// <summary> /// Fired when the work (method) associated with a TaskWaitEnd completes /// </summary> /// <param name="TaskID">The task ID.</param> [Event(TASKWAITCONTINUATIONCOMPLETE_ID, Level = EventLevel.Verbose, Keywords = Keywords.TaskStops)] public void TaskWaitContinuationComplete(int TaskID) { // Log an event if indicated. if (IsEnabled() && IsEnabled(EventLevel.Verbose, Keywords.TaskStops)) WriteEvent(TASKWAITCONTINUATIONCOMPLETE_ID, TaskID); } /// <summary> /// Fired when the work (method) associated with a TaskWaitEnd completes /// </summary> /// <param name="TaskID">The task ID.</param> [Event(TASKWAITCONTINUATIONSTARTED_ID, Level = EventLevel.Verbose, Keywords = Keywords.Tasks)] public void TaskWaitContinuationStarted(int TaskID) { // Log an event if indicated. if (IsEnabled() && IsEnabled(EventLevel.Verbose, Keywords.Tasks)) WriteEvent(TASKWAITCONTINUATIONSTARTED_ID, TaskID); } /// <summary> /// Fired when the an asynchronous continuation for a task is scheduled /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="ContinueWithTaskId">The ID of the continuation object.</param> #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif [Event(AWAITTASKCONTINUATIONSCHEDULED_ID, Task = Tasks.AwaitTaskContinuationScheduled, Opcode = EventOpcode.Send, Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer | Keywords.Tasks)] public void AwaitTaskContinuationScheduled( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int ContinueWithTaskId) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer | Keywords.Tasks)) { unsafe { EventData* eventPayload = stackalloc EventData[3]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID)); eventPayload[0].Reserved = 0; eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID)); eventPayload[1].Reserved = 0; eventPayload[2].Size = sizeof(int); eventPayload[2].DataPointer = ((IntPtr)(&ContinueWithTaskId)); eventPayload[2].Reserved = 0; if (TasksSetActivityIds) { Guid continuationActivityId = CreateGuidForTaskID(ContinueWithTaskId); WriteEventWithRelatedActivityIdCore(AWAITTASKCONTINUATIONSCHEDULED_ID, &continuationActivityId, 3, eventPayload); } else WriteEventCore(AWAITTASKCONTINUATIONSCHEDULED_ID, 3, eventPayload); } } } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif [Event(TRACEOPERATIONSTART_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)] public void TraceOperationBegin(int TaskID, string OperationName, long RelatedContext) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityOperation)) { unsafe { fixed (char* operationNamePtr = OperationName) { EventData* eventPayload = stackalloc EventData[3]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr)(&TaskID)); eventPayload[0].Reserved = 0; eventPayload[1].Size = ((OperationName.Length + 1) * 2); eventPayload[1].DataPointer = ((IntPtr)operationNamePtr); eventPayload[1].Reserved = 0; eventPayload[2].Size = sizeof(long); eventPayload[2].DataPointer = ((IntPtr)(&RelatedContext)); eventPayload[2].Reserved = 0; WriteEventCore(TRACEOPERATIONSTART_ID, 3, eventPayload); } } } } [Event(TRACEOPERATIONRELATION_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityRelation)] public void TraceOperationRelation(int TaskID, CausalityRelation Relation) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityRelation)) WriteEvent(TRACEOPERATIONRELATION_ID, TaskID, (int)Relation); // optimized overload for this exists } [Event(TRACEOPERATIONSTOP_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)] public void TraceOperationEnd(int TaskID, AsyncCausalityStatus Status) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityOperation)) WriteEvent(TRACEOPERATIONSTOP_ID, TaskID, (int)Status); // optimized overload for this exists } [Event(TRACESYNCHRONOUSWORKSTART_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)] public void TraceSynchronousWorkBegin(int TaskID, CausalitySynchronousWork Work) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalitySynchronousWork)) WriteEvent(TRACESYNCHRONOUSWORKSTART_ID, TaskID, (int)Work); // optimized overload for this exists } #if !ES_BUILD_STANDALONE [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] #endif [Event(TRACESYNCHRONOUSWORKSTOP_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)] public void TraceSynchronousWorkEnd(CausalitySynchronousWork Work) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalitySynchronousWork)) { unsafe { EventData* eventPayload = stackalloc EventData[1]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr)(&Work)); eventPayload[0].Reserved = 0; WriteEventCore(TRACESYNCHRONOUSWORKSTOP_ID, 1, eventPayload); } } } [NonEvent] public unsafe void RunningContinuation(int TaskID, object Object) { RunningContinuation(TaskID, (long)*((void**)Unsafe.AsPointer(ref Object))); } [Event(20, Keywords = Keywords.Debug)] private void RunningContinuation(int TaskID, long Object) { if (Debug) WriteEvent(20, TaskID, Object); } [NonEvent] public unsafe void RunningContinuationList(int TaskID, int Index, object Object) { RunningContinuationList(TaskID, Index, (long)*((void**)Unsafe.AsPointer(ref Object))); } [Event(21, Keywords = Keywords.Debug)] public void RunningContinuationList(int TaskID, int Index, long Object) { if (Debug) WriteEvent(21, TaskID, Index, Object); } [Event(23, Keywords = Keywords.Debug)] public void DebugFacilityMessage(string Facility, string Message) { WriteEvent(23, Facility, Message); } [Event(24, Keywords = Keywords.Debug)] public void DebugFacilityMessage1(string Facility, string Message, string Value1) { WriteEvent(24, Facility, Message, Value1); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = "Guid parameter is safe with WriteEvent")] [Event(25, Keywords = Keywords.DebugActivityId)] public void SetActivityId(Guid NewId) { if (DebugActivityId) WriteEvent(25, NewId); } [Event(26, Keywords = Keywords.Debug)] public void NewID(int TaskID) { if (Debug) WriteEvent(26, TaskID); } [NonEvent] public void IncompleteAsyncMethod(IAsyncStateMachineBox stateMachineBox) { System.Diagnostics.Debug.Assert(stateMachineBox != null); if (IsEnabled() && IsEnabled(EventLevel.Warning, Keywords.AsyncMethod)) { IAsyncStateMachine stateMachine = stateMachineBox.GetStateMachineObject(); if (stateMachine != null) { string description = AsyncMethodBuilderCore.GetAsyncStateMachineDescription(stateMachine); IncompleteAsyncMethod(description); } } } [Event(27, Level = EventLevel.Warning, Keywords = Keywords.AsyncMethod)] private void IncompleteAsyncMethod(string stateMachineDescription) => WriteEvent(27, stateMachineDescription); /// <summary> /// Activity IDs are GUIDS but task IDS are integers (and are not unique across appdomains /// This routine creates a process wide unique GUID given a task ID /// </summary> internal static Guid CreateGuidForTaskID(int taskID) { // The thread pool generated a process wide unique GUID from a task GUID by // using the taskGuid, the appdomain ID, and 8 bytes of 'randomization' chosen by // using the last 8 bytes as the provider GUID for this provider. // These were generated by CreateGuid, and are reasonably random (and thus unlikely to collide int pid = Environment.ProcessId; return new Guid(taskID, (short)DefaultAppDomainID, (short)(DefaultAppDomainID >> 16), (byte)pid, (byte)(pid >> 8), (byte)(pid >> 16), (byte)(pid >> 24), 0xff, 0xdc, 0xd7, 0xb5); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Private.Xml/tests/XmlDocument/XmlCharacterDataTests/InsertDataTests.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.Xml.Tests { public class InsertDataTests { [Fact] public static void InsertDataAtBeginningOfCdataNode() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection("comment"); cdataNode.InsertData(0, "hello "); Assert.Equal("hello comment", cdataNode.Data); } [Fact] public static void InsertDataAtMiddleOfCdataNode() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection("comment"); cdataNode.InsertData(3, " hello "); Assert.Equal("com hello ment", cdataNode.Data); } [Fact] public static void InsertDataInEmptyCdataNode() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection(null); cdataNode.InsertData(0, "hello"); Assert.Equal("hello", cdataNode.Data); } [Fact] public static void InsertDataBeyondEndOfEmptyCdataNode() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection(null); Assert.Throws<ArgumentOutOfRangeException>(() => cdataNode.InsertData(1, "hello ")); } [Fact] public static void InsertDataBeyondEndOfCdataNodeBigNumber() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection("hello"); Assert.Throws<ArgumentOutOfRangeException>(() => cdataNode.InsertData(10, "hello ")); } } }
// 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.Xml.Tests { public class InsertDataTests { [Fact] public static void InsertDataAtBeginningOfCdataNode() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection("comment"); cdataNode.InsertData(0, "hello "); Assert.Equal("hello comment", cdataNode.Data); } [Fact] public static void InsertDataAtMiddleOfCdataNode() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection("comment"); cdataNode.InsertData(3, " hello "); Assert.Equal("com hello ment", cdataNode.Data); } [Fact] public static void InsertDataInEmptyCdataNode() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection(null); cdataNode.InsertData(0, "hello"); Assert.Equal("hello", cdataNode.Data); } [Fact] public static void InsertDataBeyondEndOfEmptyCdataNode() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection(null); Assert.Throws<ArgumentOutOfRangeException>(() => cdataNode.InsertData(1, "hello ")); } [Fact] public static void InsertDataBeyondEndOfCdataNodeBigNumber() { var xmlDocument = new XmlDocument(); var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection("hello"); Assert.Throws<ArgumentOutOfRangeException>(() => cdataNode.InsertData(10, "hello ")); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/Methodical/NaN/r4NaNdiv_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="r4NaNdiv.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="r4NaNdiv.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/BuildWasmApps/Wasm.Build.Tests/MainWithArgsTests.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 Xunit; using Xunit.Abstractions; #nullable enable namespace Wasm.Build.Tests { public class MainWithArgsTests : BuildTestBase { public MainWithArgsTests(ITestOutputHelper output, SharedBuildPerTestClassFixture buildContext) : base(output, buildContext) { } public static IEnumerable<object?[]> MainWithArgsTestData(bool aot, RunHost host) => ConfigWithAOTData(aot).Multiply( new object?[] { new object?[] { "abc", "foobar"} }, new object?[] { new object?[0] } ).WithRunHosts(host).UnwrapItemsAsArrays(); [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/61725", TestPlatforms.Windows)] [MemberData(nameof(MainWithArgsTestData), parameters: new object[] { /*aot*/ false, RunHost.All })] [MemberData(nameof(MainWithArgsTestData), parameters: new object[] { /*aot*/ true, RunHost.All })] public void AsyncMainWithArgs(BuildArgs buildArgs, string[] args, RunHost host, string id) => TestMainWithArgs("async_main_with_args", @" public class TestClass { public static async System.Threading.Tasks.Task<int> Main(string[] args) { ##CODE## return await System.Threading.Tasks.Task.FromResult(42 + count); } }", buildArgs, args, host, id); [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/61725", TestPlatforms.Windows)] [MemberData(nameof(MainWithArgsTestData), parameters: new object[] { /*aot*/ false, RunHost.All })] [MemberData(nameof(MainWithArgsTestData), parameters: new object[] { /*aot*/ true, RunHost.All })] public void TopLevelWithArgs(BuildArgs buildArgs, string[] args, RunHost host, string id) => TestMainWithArgs("top_level_args", @"##CODE## return await System.Threading.Tasks.Task.FromResult(42 + count);", buildArgs, args, host, id); [Theory] [MemberData(nameof(MainWithArgsTestData), parameters: new object[] { /*aot*/ false, RunHost.All })] [MemberData(nameof(MainWithArgsTestData), parameters: new object[] { /*aot*/ true, RunHost.All })] public void NonAsyncMainWithArgs(BuildArgs buildArgs, string[] args, RunHost host, string id) => TestMainWithArgs("non_async_main_args", @" public class TestClass { public static int Main(string[] args) { ##CODE## return 42 + count; } }", buildArgs, args, host, id); void TestMainWithArgs(string projectNamePrefix, string projectContents, BuildArgs buildArgs, string[] args, RunHost host, string id, bool? dotnetWasmFromRuntimePack=null) { string projectName = $"{projectNamePrefix}_{buildArgs.Config}_{buildArgs.AOT}"; string code = @" int count = args == null ? 0 : args.Length; System.Console.WriteLine($""args#: {args?.Length}""); foreach (var arg in args ?? System.Array.Empty<string>()) System.Console.WriteLine($""arg: {arg}""); "; string programText = projectContents.Replace("##CODE##", code); buildArgs = buildArgs with { ProjectName = projectName, ProjectFileContents = programText }; buildArgs = ExpandBuildArgs(buildArgs); if (dotnetWasmFromRuntimePack == null) dotnetWasmFromRuntimePack = !(buildArgs.AOT || buildArgs.Config == "Release"); Console.WriteLine ($"-- args: {buildArgs}, name: {projectName}"); BuildProject(buildArgs, id: id, new BuildProjectOptions( InitProject: () => File.WriteAllText(Path.Combine(_projectDir!, "Program.cs"), programText), DotnetWasmFromRuntimePack: dotnetWasmFromRuntimePack)); RunAndTestWasmApp(buildArgs, buildDir: _projectDir, expectedExitCode: 42 + args.Length, args: string.Join(' ', args), test: output => { Assert.Contains($"args#: {args.Length}", output); foreach (var arg in args) Assert.Contains($"arg: {arg}", output); }, host: host, id: id); } } }
// 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 Xunit; using Xunit.Abstractions; #nullable enable namespace Wasm.Build.Tests { public class MainWithArgsTests : BuildTestBase { public MainWithArgsTests(ITestOutputHelper output, SharedBuildPerTestClassFixture buildContext) : base(output, buildContext) { } public static IEnumerable<object?[]> MainWithArgsTestData(bool aot, RunHost host) => ConfigWithAOTData(aot).Multiply( new object?[] { new object?[] { "abc", "foobar"} }, new object?[] { new object?[0] } ).WithRunHosts(host).UnwrapItemsAsArrays(); [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/61725", TestPlatforms.Windows)] [MemberData(nameof(MainWithArgsTestData), parameters: new object[] { /*aot*/ false, RunHost.All })] [MemberData(nameof(MainWithArgsTestData), parameters: new object[] { /*aot*/ true, RunHost.All })] public void AsyncMainWithArgs(BuildArgs buildArgs, string[] args, RunHost host, string id) => TestMainWithArgs("async_main_with_args", @" public class TestClass { public static async System.Threading.Tasks.Task<int> Main(string[] args) { ##CODE## return await System.Threading.Tasks.Task.FromResult(42 + count); } }", buildArgs, args, host, id); [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/61725", TestPlatforms.Windows)] [MemberData(nameof(MainWithArgsTestData), parameters: new object[] { /*aot*/ false, RunHost.All })] [MemberData(nameof(MainWithArgsTestData), parameters: new object[] { /*aot*/ true, RunHost.All })] public void TopLevelWithArgs(BuildArgs buildArgs, string[] args, RunHost host, string id) => TestMainWithArgs("top_level_args", @"##CODE## return await System.Threading.Tasks.Task.FromResult(42 + count);", buildArgs, args, host, id); [Theory] [MemberData(nameof(MainWithArgsTestData), parameters: new object[] { /*aot*/ false, RunHost.All })] [MemberData(nameof(MainWithArgsTestData), parameters: new object[] { /*aot*/ true, RunHost.All })] public void NonAsyncMainWithArgs(BuildArgs buildArgs, string[] args, RunHost host, string id) => TestMainWithArgs("non_async_main_args", @" public class TestClass { public static int Main(string[] args) { ##CODE## return 42 + count; } }", buildArgs, args, host, id); void TestMainWithArgs(string projectNamePrefix, string projectContents, BuildArgs buildArgs, string[] args, RunHost host, string id, bool? dotnetWasmFromRuntimePack=null) { string projectName = $"{projectNamePrefix}_{buildArgs.Config}_{buildArgs.AOT}"; string code = @" int count = args == null ? 0 : args.Length; System.Console.WriteLine($""args#: {args?.Length}""); foreach (var arg in args ?? System.Array.Empty<string>()) System.Console.WriteLine($""arg: {arg}""); "; string programText = projectContents.Replace("##CODE##", code); buildArgs = buildArgs with { ProjectName = projectName, ProjectFileContents = programText }; buildArgs = ExpandBuildArgs(buildArgs); if (dotnetWasmFromRuntimePack == null) dotnetWasmFromRuntimePack = !(buildArgs.AOT || buildArgs.Config == "Release"); Console.WriteLine ($"-- args: {buildArgs}, name: {projectName}"); BuildProject(buildArgs, id: id, new BuildProjectOptions( InitProject: () => File.WriteAllText(Path.Combine(_projectDir!, "Program.cs"), programText), DotnetWasmFromRuntimePack: dotnetWasmFromRuntimePack)); RunAndTestWasmApp(buildArgs, buildDir: _projectDir, expectedExitCode: 42 + args.Length, args: string.Join(' ', args), test: output => { Assert.Contains($"args#: {args.Length}", output); foreach (var arg in args) Assert.Contains($"arg: {arg}", output); }, host: host, id: id); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/jit64/gc/misc/structfp1_4.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; struct Pad { #pragma warning disable 0414 public double d1; public double d2; public double d3; public double d4; public double d5; public double d6; public double d7; public double d8; public double d9; public double d10; public double d11; public double d12; public double d13; public double d14; public double d15; public double d16; public double d17; public double d18; public double d19; public double d20; public double d21; public double d22; public double d23; public double d24; public double d25; public double d26; public double d27; public double d28; public double d29; public double d30; #pragma warning restore 0414 } struct S { #pragma warning disable 0414 public String str2; #pragma warning restore 0414 public String str; public Pad pad; public S(String s) { str = s; str2 = s + str; pad.d1 = pad.d2 = pad.d3 = pad.d4 = pad.d5 = pad.d6 = pad.d7 = pad.d8 = pad.d9 = pad.d10 = pad.d11 = pad.d12 = pad.d13 = pad.d14 = pad.d15 = pad.d16 = pad.d17 = pad.d18 = pad.d19 = pad.d20 = pad.d21 = pad.d22 = pad.d23 = pad.d24 = pad.d25 = pad.d26 = pad.d27 = pad.d28 = pad.d29 = pad.d30 = 3.3; } } class Test_structfp1_4 { public static void c(float f1, float f2, float f3, float f4, float f5, S s1) { Console.WriteLine(s1.str); } public static int Main() { S sM = new S("test"); c(1, 2, 3, 4, 5, sM); 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; struct Pad { #pragma warning disable 0414 public double d1; public double d2; public double d3; public double d4; public double d5; public double d6; public double d7; public double d8; public double d9; public double d10; public double d11; public double d12; public double d13; public double d14; public double d15; public double d16; public double d17; public double d18; public double d19; public double d20; public double d21; public double d22; public double d23; public double d24; public double d25; public double d26; public double d27; public double d28; public double d29; public double d30; #pragma warning restore 0414 } struct S { #pragma warning disable 0414 public String str2; #pragma warning restore 0414 public String str; public Pad pad; public S(String s) { str = s; str2 = s + str; pad.d1 = pad.d2 = pad.d3 = pad.d4 = pad.d5 = pad.d6 = pad.d7 = pad.d8 = pad.d9 = pad.d10 = pad.d11 = pad.d12 = pad.d13 = pad.d14 = pad.d15 = pad.d16 = pad.d17 = pad.d18 = pad.d19 = pad.d20 = pad.d21 = pad.d22 = pad.d23 = pad.d24 = pad.d25 = pad.d26 = pad.d27 = pad.d28 = pad.d29 = pad.d30 = 3.3; } } class Test_structfp1_4 { public static void c(float f1, float f2, float f3, float f4, float f5, S s1) { Console.WriteLine(s1.str); } public static int Main() { S sM = new S("test"); c(1, 2, 3, 4, 5, sM); return 100; } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Reflection.Extensions/tests/Definitions/FieldDefinitions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma warning disable 3026 namespace System.Reflection.Tests { public class FieldTestBaseClass { public static int Members = 35; public static int MembersEverything = 41; public static string[] DeclaredFieldNames = new string[] { "SubPubfld1", "Pubfld1", "Pubfld2", "Pubfld3", "SubIntfld1", "Intfld1", "Intfld2", "Intfld3", "SubProfld1", "Profld1", "Profld2", "Profld3", "SubProIntfld1", "ProIntfld1", "ProIntfld2", "ProIntfld3", "Pubfld4", "Pubfld5", "Pubfld6", "Intfld4", "Intfld5", "Intfld6", "Profld4", "Profld5", "Profld6", "ProIntfld4", "ProIntfld5", "ProIntfld6", "Members", "DeclaredFieldNames", "InheritedFieldNames", "MembersEverything", "PublicFieldNames"}; public static string[] InheritedFieldNames = new string[] { }; public static string[] PublicFieldNames = new string[] { "SubPubfld1", "Pubfld1", "Pubfld2", "Pubfld3", "Pubfld4", "Pubfld5", "Pubfld6", "Members", "DeclaredFieldNames", "InheritedFieldNames", "MembersEverything", "PublicFieldNames"}; public string SubPubfld1 = ""; public string Pubfld1 = ""; public readonly string Pubfld2 = ""; public volatile string Pubfld3 = ""; public static string Pubfld4 = ""; public static readonly string Pubfld5 = ""; public static volatile string Pubfld6 = ""; internal string SubIntfld1 = ""; internal string Intfld1 = ""; internal readonly string Intfld2 = ""; internal volatile string Intfld3 = ""; internal static string Intfld4 = ""; internal static readonly string Intfld5 = ""; internal static volatile string Intfld6 = ""; protected string SubProfld1 = ""; protected string Profld1 = ""; protected readonly string Profld2 = ""; protected volatile string Profld3 = ""; protected static string Profld4 = ""; protected static readonly string Profld5 = ""; protected static volatile string Profld6 = ""; protected internal string SubProIntfld1 = ""; protected internal string ProIntfld1 = ""; protected internal readonly string ProIntfld2 = ""; protected internal volatile string ProIntfld3 = ""; protected internal static string ProIntfld4 = ""; protected internal static readonly string ProIntfld5 = ""; protected internal static volatile string ProIntfld6 = ""; } public class FieldTestSubClass : FieldTestBaseClass { public static new int Members = 32; public static new int MembersEverything = 54; public static new string[] DeclaredFieldNames = new string[] { "Pubfld1", "Pubfld2", "Pubfld3", "Intfld1", "Intfld2", "Intfld3", "Profld1", "Profld2", "Profld3", "ProIntfld1", "ProIntfld2", "ProIntfld3", "Pubfld4", "Pubfld5", "Pubfld6", "Intfld4", "Intfld5", "Intfld6", "Profld4", "Profld5", "Profld6", "ProIntfld4", "ProIntfld5", "ProIntfld6", "Members", "DeclaredFieldNames", "InheritedFieldNames", "NewFieldNames", "MembersEverything", "PublicFieldNames"}; public static new string[] InheritedFieldNames = new string[] { "SubPubfld1", "SubIntfld1", "SubProfld1", "SubProIntfld1" }; public static string[] NewFieldNames = new string[] { "Pubfld1", "Pubfld2", "Pubfld3", "Intfld1", "Intfld2", "Intfld3", "Profld1", "Profld2", "Profld3", "ProIntfld1", "ProIntfld2", "ProIntfld3"}; public static new string[] PublicFieldNames = new string[] { "Pubfld1", "Pubfld2", "Pubfld3", "Pubfld4", "Pubfld5", "Pubfld6", "Members", "DeclaredFieldNames", "InheritedFieldNames", "NewFieldNames", "MembersEverything", "PublicFieldNames"}; public new string Pubfld1 = ""; public new readonly string Pubfld2 = ""; public new volatile string Pubfld3 = ""; public static new string Pubfld4 = ""; public static new readonly string Pubfld5 = ""; public static new volatile string Pubfld6 = ""; internal new string Intfld1 = ""; internal new readonly string Intfld2 = ""; internal new volatile string Intfld3 = ""; internal static new string Intfld4 = ""; internal static new readonly string Intfld5 = ""; internal static new volatile string Intfld6 = ""; protected new string Profld1 = ""; protected new readonly string Profld2 = ""; protected new volatile string Profld3 = ""; protected static new string Profld4 = ""; protected static new readonly string Profld5 = ""; protected static new volatile string Profld6 = ""; protected internal new string ProIntfld1 = ""; protected internal new readonly string ProIntfld2 = ""; protected internal new volatile string ProIntfld3 = ""; protected internal static new string ProIntfld4 = ""; protected internal static new readonly string ProIntfld5 = ""; protected internal static new volatile string ProIntfld6 = ""; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma warning disable 3026 namespace System.Reflection.Tests { public class FieldTestBaseClass { public static int Members = 35; public static int MembersEverything = 41; public static string[] DeclaredFieldNames = new string[] { "SubPubfld1", "Pubfld1", "Pubfld2", "Pubfld3", "SubIntfld1", "Intfld1", "Intfld2", "Intfld3", "SubProfld1", "Profld1", "Profld2", "Profld3", "SubProIntfld1", "ProIntfld1", "ProIntfld2", "ProIntfld3", "Pubfld4", "Pubfld5", "Pubfld6", "Intfld4", "Intfld5", "Intfld6", "Profld4", "Profld5", "Profld6", "ProIntfld4", "ProIntfld5", "ProIntfld6", "Members", "DeclaredFieldNames", "InheritedFieldNames", "MembersEverything", "PublicFieldNames"}; public static string[] InheritedFieldNames = new string[] { }; public static string[] PublicFieldNames = new string[] { "SubPubfld1", "Pubfld1", "Pubfld2", "Pubfld3", "Pubfld4", "Pubfld5", "Pubfld6", "Members", "DeclaredFieldNames", "InheritedFieldNames", "MembersEverything", "PublicFieldNames"}; public string SubPubfld1 = ""; public string Pubfld1 = ""; public readonly string Pubfld2 = ""; public volatile string Pubfld3 = ""; public static string Pubfld4 = ""; public static readonly string Pubfld5 = ""; public static volatile string Pubfld6 = ""; internal string SubIntfld1 = ""; internal string Intfld1 = ""; internal readonly string Intfld2 = ""; internal volatile string Intfld3 = ""; internal static string Intfld4 = ""; internal static readonly string Intfld5 = ""; internal static volatile string Intfld6 = ""; protected string SubProfld1 = ""; protected string Profld1 = ""; protected readonly string Profld2 = ""; protected volatile string Profld3 = ""; protected static string Profld4 = ""; protected static readonly string Profld5 = ""; protected static volatile string Profld6 = ""; protected internal string SubProIntfld1 = ""; protected internal string ProIntfld1 = ""; protected internal readonly string ProIntfld2 = ""; protected internal volatile string ProIntfld3 = ""; protected internal static string ProIntfld4 = ""; protected internal static readonly string ProIntfld5 = ""; protected internal static volatile string ProIntfld6 = ""; } public class FieldTestSubClass : FieldTestBaseClass { public static new int Members = 32; public static new int MembersEverything = 54; public static new string[] DeclaredFieldNames = new string[] { "Pubfld1", "Pubfld2", "Pubfld3", "Intfld1", "Intfld2", "Intfld3", "Profld1", "Profld2", "Profld3", "ProIntfld1", "ProIntfld2", "ProIntfld3", "Pubfld4", "Pubfld5", "Pubfld6", "Intfld4", "Intfld5", "Intfld6", "Profld4", "Profld5", "Profld6", "ProIntfld4", "ProIntfld5", "ProIntfld6", "Members", "DeclaredFieldNames", "InheritedFieldNames", "NewFieldNames", "MembersEverything", "PublicFieldNames"}; public static new string[] InheritedFieldNames = new string[] { "SubPubfld1", "SubIntfld1", "SubProfld1", "SubProIntfld1" }; public static string[] NewFieldNames = new string[] { "Pubfld1", "Pubfld2", "Pubfld3", "Intfld1", "Intfld2", "Intfld3", "Profld1", "Profld2", "Profld3", "ProIntfld1", "ProIntfld2", "ProIntfld3"}; public static new string[] PublicFieldNames = new string[] { "Pubfld1", "Pubfld2", "Pubfld3", "Pubfld4", "Pubfld5", "Pubfld6", "Members", "DeclaredFieldNames", "InheritedFieldNames", "NewFieldNames", "MembersEverything", "PublicFieldNames"}; public new string Pubfld1 = ""; public new readonly string Pubfld2 = ""; public new volatile string Pubfld3 = ""; public static new string Pubfld4 = ""; public static new readonly string Pubfld5 = ""; public static new volatile string Pubfld6 = ""; internal new string Intfld1 = ""; internal new readonly string Intfld2 = ""; internal new volatile string Intfld3 = ""; internal static new string Intfld4 = ""; internal static new readonly string Intfld5 = ""; internal static new volatile string Intfld6 = ""; protected new string Profld1 = ""; protected new readonly string Profld2 = ""; protected new volatile string Profld3 = ""; protected static new string Profld4 = ""; protected static new readonly string Profld5 = ""; protected static new volatile string Profld6 = ""; protected internal new string ProIntfld1 = ""; protected internal new readonly string ProIntfld2 = ""; protected internal new volatile string ProIntfld3 = ""; protected internal static new string ProIntfld4 = ""; protected internal static new readonly string ProIntfld5 = ""; protected internal static new volatile string ProIntfld6 = ""; } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.ValueTuple/tests/ValueTupleTests.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 Xunit; #if NETCOREAPP using System.Runtime.CompilerServices; #endif namespace System.Tests { public class ValueTupleTests { private class ValueTupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> { private int _nItems; private readonly object valueTuple; private readonly ValueTuple valueTuple0; private readonly ValueTuple<T1> valueTuple1; private readonly ValueTuple<T1, T2> valueTuple2; private readonly ValueTuple<T1, T2, T3> valueTuple3; private readonly ValueTuple<T1, T2, T3, T4> valueTuple4; private readonly ValueTuple<T1, T2, T3, T4, T5> valueTuple5; private readonly ValueTuple<T1, T2, T3, T4, T5, T6> valueTuple6; private readonly ValueTuple<T1, T2, T3, T4, T5, T6, T7> valueTuple7; private readonly ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> valueTuple8; private readonly ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>> valueTuple9; private readonly ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>> valueTuple10; internal ValueTupleTestDriver(params object[] values) { if (values.Length > 10) throw new ArgumentOutOfRangeException("values", "You must provide at most 10 values"); _nItems = values.Length; switch (_nItems) { case 0: valueTuple0 = ValueTuple.Create(); valueTuple = valueTuple0; break; case 1: valueTuple1 = ValueTuple.Create((T1)values[0]); valueTuple = valueTuple1; break; case 2: valueTuple2 = ValueTuple.Create((T1)values[0], (T2)values[1]); valueTuple = valueTuple2; break; case 3: valueTuple3 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2]); valueTuple = valueTuple3; break; case 4: valueTuple4 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3]); valueTuple = valueTuple4; break; case 5: valueTuple5 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4]); valueTuple = valueTuple5; break; case 6: valueTuple6 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5]); valueTuple = valueTuple6; break; case 7: valueTuple7 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5], (T7)values[6]); valueTuple = valueTuple7; break; case 8: valueTuple8 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5], (T7)values[6], (T8)values[7]); valueTuple = valueTuple8; break; case 9: valueTuple9 = new ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5], (T7)values[6], new ValueTuple<T8, T9>((T8)values[7], (T9)values[8])); valueTuple = valueTuple9; break; case 10: valueTuple10 = new ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5], (T7)values[6], new ValueTuple<T8, T9, T10>((T8)values[7], (T9)values[8], (T10)values[9])); valueTuple = valueTuple10; break; } } private void VerifyItem(int itemPos, object Item1, object Item2) { Assert.True(object.Equals(Item1, Item2)); } public void TestConstructor(params object[] expectedValue) { if (expectedValue.Length != _nItems) throw new ArgumentOutOfRangeException("expectedValues", "You must provide " + _nItems + " expectedvalues"); switch (_nItems) { case 0: break; case 1: VerifyItem(1, valueTuple1.Item1, expectedValue[0]); break; case 2: VerifyItem(1, valueTuple2.Item1, expectedValue[0]); VerifyItem(2, valueTuple2.Item2, expectedValue[1]); break; case 3: VerifyItem(1, valueTuple3.Item1, expectedValue[0]); VerifyItem(2, valueTuple3.Item2, expectedValue[1]); VerifyItem(3, valueTuple3.Item3, expectedValue[2]); break; case 4: VerifyItem(1, valueTuple4.Item1, expectedValue[0]); VerifyItem(2, valueTuple4.Item2, expectedValue[1]); VerifyItem(3, valueTuple4.Item3, expectedValue[2]); VerifyItem(4, valueTuple4.Item4, expectedValue[3]); break; case 5: VerifyItem(1, valueTuple5.Item1, expectedValue[0]); VerifyItem(2, valueTuple5.Item2, expectedValue[1]); VerifyItem(3, valueTuple5.Item3, expectedValue[2]); VerifyItem(4, valueTuple5.Item4, expectedValue[3]); VerifyItem(5, valueTuple5.Item5, expectedValue[4]); break; case 6: VerifyItem(1, valueTuple6.Item1, expectedValue[0]); VerifyItem(2, valueTuple6.Item2, expectedValue[1]); VerifyItem(3, valueTuple6.Item3, expectedValue[2]); VerifyItem(4, valueTuple6.Item4, expectedValue[3]); VerifyItem(5, valueTuple6.Item5, expectedValue[4]); VerifyItem(6, valueTuple6.Item6, expectedValue[5]); break; case 7: VerifyItem(1, valueTuple7.Item1, expectedValue[0]); VerifyItem(2, valueTuple7.Item2, expectedValue[1]); VerifyItem(3, valueTuple7.Item3, expectedValue[2]); VerifyItem(4, valueTuple7.Item4, expectedValue[3]); VerifyItem(5, valueTuple7.Item5, expectedValue[4]); VerifyItem(6, valueTuple7.Item6, expectedValue[5]); VerifyItem(7, valueTuple7.Item7, expectedValue[6]); break; case 8: // Extended ValueTuple VerifyItem(1, valueTuple8.Item1, expectedValue[0]); VerifyItem(2, valueTuple8.Item2, expectedValue[1]); VerifyItem(3, valueTuple8.Item3, expectedValue[2]); VerifyItem(4, valueTuple8.Item4, expectedValue[3]); VerifyItem(5, valueTuple8.Item5, expectedValue[4]); VerifyItem(6, valueTuple8.Item6, expectedValue[5]); VerifyItem(7, valueTuple8.Item7, expectedValue[6]); VerifyItem(8, valueTuple8.Rest.Item1, expectedValue[7]); break; case 9: // Extended ValueTuple VerifyItem(1, valueTuple9.Item1, expectedValue[0]); VerifyItem(2, valueTuple9.Item2, expectedValue[1]); VerifyItem(3, valueTuple9.Item3, expectedValue[2]); VerifyItem(4, valueTuple9.Item4, expectedValue[3]); VerifyItem(5, valueTuple9.Item5, expectedValue[4]); VerifyItem(6, valueTuple9.Item6, expectedValue[5]); VerifyItem(7, valueTuple9.Item7, expectedValue[6]); VerifyItem(8, valueTuple9.Rest.Item1, expectedValue[7]); VerifyItem(9, valueTuple9.Rest.Item2, expectedValue[8]); break; case 10: // Extended ValueTuple VerifyItem(1, valueTuple10.Item1, expectedValue[0]); VerifyItem(2, valueTuple10.Item2, expectedValue[1]); VerifyItem(3, valueTuple10.Item3, expectedValue[2]); VerifyItem(4, valueTuple10.Item4, expectedValue[3]); VerifyItem(5, valueTuple10.Item5, expectedValue[4]); VerifyItem(6, valueTuple10.Item6, expectedValue[5]); VerifyItem(7, valueTuple10.Item7, expectedValue[6]); VerifyItem(8, valueTuple10.Rest.Item1, expectedValue[7]); VerifyItem(9, valueTuple10.Rest.Item2, expectedValue[8]); VerifyItem(10, valueTuple10.Rest.Item3, expectedValue[9]); break; default: throw new ArgumentException("Must specify between 0 and 10 expected values (inclusive)."); } } public void TestToString(string expected) { Assert.Equal(expected, valueTuple.ToString()); } public void TestEquals_GetHashCode(ValueTupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> other, bool expectEqual, bool expectStructuallyEqual) { if (expectEqual) { Assert.True(valueTuple.Equals(other.valueTuple)); Assert.Equal(valueTuple.GetHashCode(), other.valueTuple.GetHashCode()); } else { Assert.False(valueTuple.Equals(other.valueTuple)); Assert.NotEqual(valueTuple.GetHashCode(), other.valueTuple.GetHashCode()); } if (expectStructuallyEqual) { var equatable = ((IStructuralEquatable)valueTuple); var otherEquatable = ((IStructuralEquatable)other.valueTuple); Assert.True(equatable.Equals(other.valueTuple, TestEqualityComparer.Instance)); Assert.Equal(equatable.GetHashCode(TestEqualityComparer.Instance), otherEquatable.GetHashCode(TestEqualityComparer.Instance)); } else { var equatable = ((IStructuralEquatable)valueTuple); var otherEquatable = ((IStructuralEquatable)other.valueTuple); Assert.False(equatable.Equals(other.valueTuple, TestEqualityComparer.Instance)); Assert.NotEqual(equatable.GetHashCode(TestEqualityComparer.Instance), otherEquatable.GetHashCode(TestEqualityComparer.Instance)); } Assert.False(valueTuple.Equals(null)); Assert.False(((IStructuralEquatable)valueTuple).Equals(null)); IStructuralEquatable_Equals_NullComparer_ThrowsNullReferenceException(); IStructuralEquatable_GetHashCode_NullComparer_ThrowsNullReferenceException(); } public void IStructuralEquatable_Equals_NullComparer_ThrowsNullReferenceException() { // This was not fixed in order to be compatible with the .NET Framework and Xamarin. // https://github.com/dotnet/runtime/issues/19275 IStructuralEquatable equatable = (IStructuralEquatable)valueTuple; if (valueTuple is ValueTuple) { Assert.True(equatable.Equals(valueTuple, null)); } else { Assert.Throws<NullReferenceException>(() => equatable.Equals(valueTuple, null)); } } public void IStructuralEquatable_GetHashCode_NullComparer_ThrowsNullReferenceException() { // This was not fixed in order to be compatible with the .NET Framework and Xamarin. // https://github.com/dotnet/runtime/issues/19275 IStructuralEquatable equatable = (IStructuralEquatable)valueTuple; if (valueTuple is ValueTuple) { Assert.Equal(0, valueTuple.GetHashCode()); } else { Assert.Throws<NullReferenceException>(() => equatable.GetHashCode(null)); } } public void TestCompareTo(ValueTupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> other, int expectedResult, int expectedStructuralResult) { Assert.Equal(expectedResult, ((IComparable)valueTuple).CompareTo(other.valueTuple)); Assert.Equal(expectedStructuralResult, ((IStructuralComparable)valueTuple).CompareTo(other.valueTuple, DummyTestComparer.Instance)); Assert.Equal(1, ((IComparable)valueTuple).CompareTo(null)); IStructuralComparable_NullComparer_ThrowsNullReferenceException(); } public void IStructuralComparable_NullComparer_ThrowsNullReferenceException() { // This was not fixed in order to be compatible with the .NET Framework and Xamarin. // https://github.com/dotnet/runtime/issues/19275 IStructuralComparable comparable = (IStructuralComparable)valueTuple; if (valueTuple is ValueTuple) { Assert.Equal(0, comparable.CompareTo(valueTuple, null)); } else { Assert.Throws<NullReferenceException>(() => comparable.CompareTo(valueTuple, null)); } } public void TestNotEqual() { ValueTuple<int> ValueTupleB = new ValueTuple<int>((int)10000); Assert.NotEqual(valueTuple, ValueTupleB); } internal void TestCompareToThrows() { ValueTuple<int> ValueTupleB = new ValueTuple<int>((int)10000); AssertExtensions.Throws<ArgumentException>("other", () => ((IComparable)valueTuple).CompareTo(ValueTupleB)); } } [Fact] public static void TestConstructor() { ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan> ValueTupleDriverA; //ValueTuple-0 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(); ValueTupleDriverA.TestConstructor(); //ValueTuple-1 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue); ValueTupleDriverA.TestConstructor(short.MaxValue); //ValueTuple-2 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); ValueTupleDriverA.TestConstructor(short.MinValue, int.MaxValue); //ValueTuple-3 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); ValueTupleDriverA.TestConstructor((short)0, (int)0, long.MaxValue); //ValueTuple-4 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); ValueTupleDriverA.TestConstructor((short)1, (int)1, long.MinValue, "This"); //ValueTuple-5 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); ValueTupleDriverA.TestConstructor((short)(-1), (int)(-1), (long)0, "is", 'A'); //ValueTuple-6 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MaxValue); ValueTupleDriverA.TestConstructor((short)10, (int)100, (long)1, "testing", 'Z', float.MaxValue); //ValueTuple-7 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue); ValueTupleDriverA.TestConstructor((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue); object myObj = new object(); //ValueTuple-10 DateTime now = DateTime.Now; ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (float)0.0001, (double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero); ValueTupleDriverA.TestConstructor((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (float)0.0001, (double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero); } [Fact] public static void TestToString() { ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan> ValueTupleDriverA; //ValueTuple-0 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(); ValueTupleDriverA.TestToString("()"); //ValueTuple-1 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue); ValueTupleDriverA.TestToString("(" + short.MaxValue + ")"); //ValueTuple-2 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); ValueTupleDriverA.TestToString("(" + short.MinValue + ", " + int.MaxValue + ")"); //ValueTuple-3 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); ValueTupleDriverA.TestToString("(" + ((short)0) + ", " + ((int)0) + ", " + long.MaxValue + ")"); //ValueTuple-4 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); ValueTupleDriverA.TestConstructor((short)1, (int)1, long.MinValue, "This"); ValueTupleDriverA.TestToString("(" + ((short)1) + ", " + ((int)1) + ", " + long.MinValue + ", This)"); //ValueTuple-5 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); ValueTupleDriverA.TestToString("(" + ((short)(-1)) + ", " + ((int)(-1)) + ", " + ((long)0) + ", is, A)"); //ValueTuple-6 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MaxValue); ValueTupleDriverA.TestToString("(" + ((short)10) + ", " + ((int)100) + ", " + ((long)1) + ", testing, Z, " + float.MaxValue + ")"); //ValueTuple-7 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue); ValueTupleDriverA.TestToString("(" + ((short)(-100)) + ", " + ((int)(-1000)) + ", " + ((long)(-1)) + ", ValueTuples, , " + float.MinValue + ", " + double.MaxValue + ")"); object myObj = new object(); //ValueTuple-10 DateTime now = DateTime.Now; ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (float)0.0001, (double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero); // .NET Native bug 438149 - object.ToString in incorrect ValueTupleDriverA.TestToString("(" + ((short)10000) + ", " + ((int)1000000) + ", " + ((long)10000000) + ", 2008?7?2?, 0, " + ((float)0.0001) + ", " + ((double)0.0000001) + ", " + now + ", (False, System.Object), " + TimeSpan.Zero + ")"); } [Fact] public static void TestEquals_GetHashCode() { ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan> ValueTupleDriverA, ValueTupleDriverB, ValueTupleDriverC, ValueTupleDriverD; //ValueTuple-0 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(); ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue, int.MaxValue); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false); //ValueTuple-1 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue); ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue, int.MaxValue); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false); //ValueTuple-2 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MinValue); ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), long.MinValue); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false); //ValueTuple-3 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), long.MinValue); ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "this"); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false); //ValueTuple-4 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "this"); ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, (long)1, "IS", 'a'); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false); //ValueTuple-5 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, (long)1, "IS", 'a'); ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MinValue); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false); //ValueTuple-6 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MinValue); ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "ValueTuples", ' ', float.MinValue, (double)0.0); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false); //ValueTuple-7 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "ValueTuples", ' ', float.MinValue, (double)0.0); ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10001, (int)1000001, (long)10000001, "2008?7?3?", '1', (float)0.0002, (double)0.0000002, DateTime.Now.AddMilliseconds(1)); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false); //ValueTuple-8 DateTime now = DateTime.Now; ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue, now); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue, now); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "ValueTuples", ' ', float.MinValue, (double)0.0, now.AddMilliseconds(1)); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); object myObj = new object(); //ValueTuple-10 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (float)0.0001, (double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (float)0.0001, (double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10001, (int)1000001, (long)10000001, "2008?7?3?", '1', (float)0.0002, (double)0.0000002, now.AddMilliseconds(1), ValueTuple.Create(true, myObj), TimeSpan.MaxValue); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); } [Fact] public static void TestCompareTo() { ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan> ValueTupleDriverA, ValueTupleDriverB, ValueTupleDriverC; //ValueTuple-0 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 0); //ValueTuple-1 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5); ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 65535, 5); //ValueTuple-2 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MinValue); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5); ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 1, 5); //ValueTuple-3 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), long.MinValue); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5); ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 1, 5); //ValueTuple-4 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "this"); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5); ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 1, 5); //ValueTuple-5 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, (long)1, "IS", 'a'); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5); ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, -1, 5); //ValueTuple-6 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MinValue); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5); ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 1, 5); //ValueTuple-7 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "ValueTuples", ' ', float.MinValue, (double)0.0); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5); ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 1, 5); object myObj = new object(); //ValueTuple-10 DateTime now = DateTime.Now; ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (float)0.0001, (double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (float)0.0001, (double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10001, (int)1000001, (long)10000001, "2008?7?3?", '1', (float)0.0002, (double)0.0000002, now.AddMilliseconds(1), ValueTuple.Create(true, myObj), TimeSpan.MaxValue); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5); ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, -1, 5); } [Fact] public static void TestNotEqual() { ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan> ValueTupleDriverA; //ValueTuple-0 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>(); ValueTupleDriverA.TestNotEqual(); //ValueTuple-1 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000); ValueTupleDriverA.TestNotEqual(); // This is for code coverage purposes //ValueTuple-2 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000); ValueTupleDriverA.TestNotEqual(); //ValueTuple-3 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000); ValueTupleDriverA.TestNotEqual(); //ValueTuple-4 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?"); ValueTupleDriverA.TestNotEqual(); //ValueTuple-5 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0'); ValueTupleDriverA.TestNotEqual(); //ValueTuple-6 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', float.NaN); ValueTupleDriverA.TestNotEqual(); //ValueTuple-7 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', float.NaN, double.NegativeInfinity); ValueTupleDriverA.TestNotEqual(); //ValueTuple-8, extended ValueTuple ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', float.NaN, double.NegativeInfinity, DateTime.Now); ValueTupleDriverA.TestNotEqual(); //ValueTuple-9 and ValueTuple-10 are not necessary because they use the same code path as ValueTuple-8 } [Fact] public static void IncomparableTypes() { ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan> ValueTupleDriverA; //ValueTuple-0 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>(); ValueTupleDriverA.TestCompareToThrows(); //ValueTuple-1 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000); ValueTupleDriverA.TestCompareToThrows(); // This is for code coverage purposes //ValueTuple-2 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000); ValueTupleDriverA.TestCompareToThrows(); //ValueTuple-3 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000); ValueTupleDriverA.TestCompareToThrows(); //ValueTuple-4 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?"); ValueTupleDriverA.TestCompareToThrows(); //ValueTuple-5 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0'); ValueTupleDriverA.TestCompareToThrows(); //ValueTuple-6 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', float.NaN); ValueTupleDriverA.TestCompareToThrows(); //ValueTuple-7 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', float.NaN, double.NegativeInfinity); ValueTupleDriverA.TestCompareToThrows(); //ValueTuple-8, extended ValueTuple ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', float.NaN, double.NegativeInfinity, DateTime.Now); ValueTupleDriverA.TestCompareToThrows(); //ValueTuple-9 and ValueTuple-10 are not necessary because they use the same code path as ValueTuple-8 } [Fact] public static void FloatingPointNaNCases() { var a = ValueTuple.Create(double.MinValue, double.NaN, float.MinValue, float.NaN); var b = ValueTuple.Create(double.MinValue, double.NaN, float.MinValue, float.NaN); Assert.True(a.Equals(b)); Assert.Equal(0, ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); } [Fact] public static void TestCustomTypeParameter1() { // Special case of ValueTuple<T1> where T1 is a custom type var testClass = new TestClass(); var a = ValueTuple.Create(testClass); var b = ValueTuple.Create(testClass); Assert.True(a.Equals(b)); Assert.Equal(0, ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); } [Fact] public static void TestCustomTypeParameter2() { // Special case of ValueTuple<T1, T2> where T2 is a custom type var testClass = new TestClass(1); var a = ValueTuple.Create(1, testClass); var b = ValueTuple.Create(1, testClass); Assert.True(a.Equals(b)); Assert.Equal(0, ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); } [Fact] public static void TestCustomTypeParameter3() { // Special case of ValueTuple<T1, T2> where T1 and T2 are custom types var testClassA = new TestClass(100); var testClassB = new TestClass(101); var a = ValueTuple.Create(testClassA, testClassB); var b = ValueTuple.Create(testClassB, testClassA); Assert.False(a.Equals(b)); Assert.Equal(-1, ((IComparable)a).CompareTo(b)); Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance)); // Equals(IEqualityComparer) is false, ignore hash code } [Fact] public static void TestCustomTypeParameter4() { // Special case of ValueTuple<T1, T2> where T1 and T2 are custom types var testClassA = new TestClass(100); var testClassB = new TestClass(101); var a = ValueTuple.Create(testClassA, testClassB); var b = ValueTuple.Create(testClassA, testClassA); Assert.False(a.Equals(b)); Assert.Equal(1, ((IComparable)a).CompareTo(b)); Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance)); // Equals(IEqualityComparer) is false, ignore hash code } [Fact] public static void NestedValueTuples1() { var a = ValueTuple.Create(1, 2, ValueTuple.Create(31, 32), 4, 5, 6, 7, ValueTuple.Create(8, 9)); var b = ValueTuple.Create(1, 2, ValueTuple.Create(31, 32), 4, 5, 6, 7, ValueTuple.Create(8, 9)); Assert.True(a.Equals(b)); Assert.Equal(0, ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); Assert.Equal("(1, 2, (31, 32), 4, 5, 6, 7, (8, 9))", a.ToString()); Assert.Equal("(31, 32)", a.Item3.ToString()); Assert.Equal("((8, 9))", a.Rest.ToString()); } [Fact] public static void NestedValueTuples2() { var a = ValueTuple.Create(0, 1, 2, 3, 4, 5, 6, ValueTuple.Create(7, 8, 9, 10, 11, 12, 13, ValueTuple.Create(14, 15))); var b = ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10, 11, 12, 13, 14, ValueTuple.Create(15, 16))); Assert.False(a.Equals(b)); Assert.Equal(-1, ((IComparable)a).CompareTo(b)); Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance)); Assert.Equal("(0, 1, 2, 3, 4, 5, 6, (7, 8, 9, 10, 11, 12, 13, (14, 15)))", a.ToString()); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, (8, 9, 10, 11, 12, 13, 14, (15, 16)))", b.ToString()); Assert.Equal("((7, 8, 9, 10, 11, 12, 13, (14, 15)))", a.Rest.ToString()); var a2 = Tuple.Create(0, 1, 2, 3, 4, 5, 6, Tuple.Create(7, 8, 9, 10, 11, 12, 13, Tuple.Create(14, 15))); var b2 = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10, 11, 12, 13, 14, Tuple.Create(15, 16))); Assert.Equal(a2.ToString(), a.ToString()); Assert.Equal(b2.ToString(), b.ToString()); Assert.Equal(a2.Rest.ToString(), a.Rest.ToString()); } [Fact] public static void IncomparableTypesSpecialCase() { // Special case when T does not implement IComparable var testClassA = new TestClass2(100); var testClassB = new TestClass2(100); var a = ValueTuple.Create(testClassA); var b = ValueTuple.Create(testClassB); Assert.True(a.Equals(b)); AssertExtensions.Throws<ArgumentException>(null, () => ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); Assert.Equal("([100])", a.ToString()); } [Fact] public static void ZeroTuples() { var a = ValueTuple.Create(); Assert.True(a.Equals(new ValueTuple())); Assert.Equal(0, a.CompareTo(new ValueTuple())); Assert.Equal(1, ((IStructuralComparable)a).CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)a).CompareTo("string", DummyTestComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, )", CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple()).ToString()); #if NETCOREAPP ITuple it = ValueTuple.Create(); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Throws<IndexOutOfRangeException>(() => it[0].ToString()); Assert.Throws<IndexOutOfRangeException>(() => it[1].ToString()); #endif } [Fact] public static void OneTuples() { IComparable c = ValueTuple.Create(1); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3))); IStructuralComparable sc = (IStructuralComparable)c; Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(3), TestComparer.Instance)); Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1)", CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(1)).ToString()); var vtWithNull = new ValueTuple<string>(null); var tupleWithNull = new Tuple<string>(null); Assert.Equal("()", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); #if NETCOREAPP ITuple it = ValueTuple.Create(1); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Throws<IndexOutOfRangeException>(() => it[1].ToString()); #endif } [Fact] public static void TwoTuples() { IComparable c = ValueTuple.Create(1, 1); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3))); IStructuralComparable sc = (IStructuralComparable)c; Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3), TestComparer.Instance)); Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 2)", CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(1, 2)).ToString()); var vtWithNull = new ValueTuple<string, string>(null, null); var tupleWithNull = new Tuple<string, string>(null, null); Assert.Equal("(, )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); #if NETCOREAPP ITuple it = ValueTuple.Create(1, 2); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Equal(2, it[1]); Assert.Throws<IndexOutOfRangeException>(() => it[2].ToString()); #endif } [Fact] public static void ThreeTuples() { IComparable c = ValueTuple.Create(1, 1, 1); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 3))); IStructuralComparable sc = (IStructuralComparable)c; Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 3), TestComparer.Instance)); Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 2, 3)", CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(1, 2, 3)).ToString()); var vtWithNull = new ValueTuple<string, string, string>(null, null, null); var tupleWithNull = new Tuple<string, string, string>(null, null, null); Assert.Equal("(, , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); #if NETCOREAPP ITuple it = ValueTuple.Create(1, 2, 3); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Equal(2, it[1]); Assert.Equal(3, it[2]); Assert.Throws<IndexOutOfRangeException>(() => it[3].ToString()); #endif } [Fact] public static void FourTuples() { IComparable c = ValueTuple.Create(1, 1, 1, 1); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 3, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 3))); IStructuralComparable sc = (IStructuralComparable)c; Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(3, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 3, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 3), TestComparer.Instance)); Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4)", CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(1, 2, 3, 4)).ToString()); var vtWithNull = new ValueTuple<string, string, string, string>(null, null, null, null); var tupleWithNull = new Tuple<string, string, string, string>(null, null, null, null); Assert.Equal("(, , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); #if NETCOREAPP ITuple it = ValueTuple.Create(1, 2, 3, 4); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Equal(2, it[1]); Assert.Equal(3, it[2]); Assert.Equal(4, it[3]); Assert.Throws<IndexOutOfRangeException>(() => it[4].ToString()); #endif } [Fact] public static void FiveTuples() { IComparable c = ValueTuple.Create(1, 1, 1, 1, 1); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3))); IStructuralComparable sc = (IStructuralComparable)c; Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3), TestComparer.Instance)); Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5)", CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(1, 2, 3, 4, 5)).ToString()); var vtWithNull = new ValueTuple<string, string, string, string, string>(null, null, null, null, null); var tupleWithNull = new Tuple<string, string, string, string, string>(null, null, null, null, null); Assert.Equal("(, , , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); #if NETCOREAPP ITuple it = ValueTuple.Create(1, 2, 3, 4, 5); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Equal(2, it[1]); Assert.Equal(3, it[2]); Assert.Equal(4, it[3]); Assert.Equal(5, it[4]); Assert.Throws<IndexOutOfRangeException>(() => it[5].ToString()); #endif } [Fact] public static void SixTuples() { IComparable c = ValueTuple.Create(1, 1, 1, 1, 1, 1); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 3))); IStructuralComparable sc = (IStructuralComparable)c; Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 3), TestComparer.Instance)); Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6)", CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(1, 2, 3, 4, 5, 6)).ToString()); var vtWithNull = new ValueTuple<string, string, string, string, string, string>(null, null, null, null, null, null); var tupleWithNull = new Tuple<string, string, string, string, string, string>(null, null, null, null, null, null); Assert.Equal("(, , , , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); #if NETCOREAPP ITuple it = ValueTuple.Create(1, 2, 3, 4, 5, 6); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Equal(2, it[1]); Assert.Equal(3, it[2]); Assert.Equal(4, it[3]); Assert.Equal(5, it[4]); Assert.Equal(6, it[5]); Assert.Throws<IndexOutOfRangeException>(() => it[6].ToString()); #endif } [Fact] public static void SevenTuples() { IComparable c = ValueTuple.Create(1, 1, 1, 1, 1, 1, 1); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 3, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 1, 3))); IStructuralComparable sc = (IStructuralComparable)c; Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 3, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 1, 3), TestComparer.Instance)); Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7)", CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(1, 2, 3, 4, 5, 6, 7)).ToString()); var vtWithNull = new ValueTuple<string, string, string, string, string, string, string>(null, null, null, null, null, null, null); var tupleWithNull = new Tuple<string, string, string, string, string, string, string>(null, null, null, null, null, null, null); Assert.Equal("(, , , , , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); #if NETCOREAPP ITuple it = ValueTuple.Create(1, 2, 3, 4, 5, 6, 7); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Equal(2, it[1]); Assert.Equal(3, it[2]); Assert.Equal(4, it[3]); Assert.Equal(5, it[4]); Assert.Equal(6, it[5]); Assert.Equal(7, it[6]); Assert.Throws<IndexOutOfRangeException>(() => it[7].ToString()); #endif } public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> CreateLong<T1, T2, T3, T4, T5, T6, T7, TRest>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) where TRest : struct { return new ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>(item1, item2, item3, item4, item5, item6, item7, rest); } public static Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> CreateLongRef<T1, T2, T3, T4, T5, T6, T7, TRest>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { return new Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>(item1, item2, item3, item4, item5, item6, item7, rest); } [Fact] public static void EightTuples() { var x = new Tuple<int, int, int, int, int, int, int, Tuple<string, string>>(1, 2, 3, 4, 5, 6, 7, new Tuple<string, string>("alice", "bob")); var y = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<string, string>>(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string, string>("alice", "bob")); Assert.Equal(x.ToString(), y.ToString()); var t = CreateLong(1, 1, 1, 1, 1, 1, 1, ValueTuple.Create(1)); IStructuralEquatable se = t; Assert.False(se.Equals(null, TestEqualityComparer.Instance)); Assert.False(se.Equals("string", TestEqualityComparer.Instance)); Assert.False(se.Equals(new ValueTuple(), TestEqualityComparer.Instance)); IComparable c = t; Assert.Equal(-1, c.CompareTo(CreateLong(3, 1, 1, 1, 1, 1, 1, ValueTuple.Create(1)))); Assert.Equal(-1, c.CompareTo(CreateLong(1, 3, 1, 1, 1, 1, 1, ValueTuple.Create(1)))); Assert.Equal(-1, c.CompareTo(CreateLong(1, 1, 3, 1, 1, 1, 1, ValueTuple.Create(1)))); Assert.Equal(-1, c.CompareTo(CreateLong(1, 1, 1, 3, 1, 1, 1, ValueTuple.Create(1)))); Assert.Equal(-1, c.CompareTo(CreateLong(1, 1, 1, 1, 3, 1, 1, ValueTuple.Create(1)))); Assert.Equal(-1, c.CompareTo(CreateLong(1, 1, 1, 1, 1, 3, 1, ValueTuple.Create(1)))); Assert.Equal(-1, c.CompareTo(CreateLong(1, 1, 1, 1, 1, 1, 3, ValueTuple.Create(1)))); IStructuralComparable sc = t; Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => sc.CompareTo("string", DummyTestComparer.Instance)); Assert.Equal(1, sc.CompareTo(CreateLong(3, 1, 1, 1, 1, 1, 1, ValueTuple.Create(1)), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(CreateLong(1, 3, 1, 1, 1, 1, 1, ValueTuple.Create(1)), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(CreateLong(1, 1, 3, 1, 1, 1, 1, ValueTuple.Create(1)), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(CreateLong(1, 1, 1, 3, 1, 1, 1, ValueTuple.Create(1)), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(CreateLong(1, 1, 1, 1, 3, 1, 1, ValueTuple.Create(1)), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(CreateLong(1, 1, 1, 1, 1, 3, 1, ValueTuple.Create(1)), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(CreateLong(1, 1, 1, 1, 1, 1, 3, ValueTuple.Create(1)), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(CreateLong(1, 1, 1, 1, 1, 1, 1, ValueTuple.Create(3)), TestComparer.Instance)); Assert.False(se.Equals(t, DummyTestEqualityComparer.Instance)); // Notice that 0-tuple prints as empty position Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, )", CreateLong(1, 2, 3, 4, 5, 6, 7, CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create())).ToString()); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 1)", CreateLong(1, 2, 3, 4, 5, 6, 7, CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(1))).ToString()); var vtWithNull = new ValueTuple<string, string, string, string, string, string, string, ValueTuple<string>>(null, null, null, null, null, null, null, new ValueTuple<string>(null)); var tupleWithNull = new Tuple<string, string, string, string, string, string, string, Tuple<string>>(null, null, null, null, null, null, null, new Tuple<string>(null)); Assert.Equal("(, , , , , , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); #if NETCOREAPP ITuple it = CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8)); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Equal(2, it[1]); Assert.Equal(3, it[2]); Assert.Equal(4, it[3]); Assert.Equal(5, it[4]); Assert.Equal(6, it[5]); Assert.Equal(7, it[6]); Assert.Equal(8, it[7]); Assert.Throws<IndexOutOfRangeException>(() => it[8].ToString()); #endif } [Fact] public static void LongTuplesWithNull() { { var vtWithNull = CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string>(null)); var tupleWithNull = CreateLongRef(1, 2, 3, 4, 5, 6, 7, new Tuple<string>(null)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); } { var vtWithNull = CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string>(null)); var tupleWithNull = CreateLongRef(1, 2, 3, 4, 5, 6, 7, new Tuple<string>(null)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); } { var vtWithNull = CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string, string>(null, null)); var tupleWithNull = CreateLongRef(1, 2, 3, 4, 5, 6, 7, new Tuple<string, string>(null, null)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); } { var vtWithNull = CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string, string, string>(null, null, null)); var tupleWithNull = CreateLongRef(1, 2, 3, 4, 5, 6, 7, new Tuple<string, string, string>(null, null, null)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); } { var vtWithNull = CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string, string, string, string>(null, null, null, null)); var tupleWithNull = CreateLongRef(1, 2, 3, 4, 5, 6, 7, new Tuple<string, string, string, string>(null, null, null, null)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, , , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); } { var vtWithNull = CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string, string, string, string, string>(null, null, null, null, null)); var tupleWithNull = CreateLongRef(1, 2, 3, 4, 5, 6, 7, new Tuple<string, string, string, string, string>(null, null, null, null, null)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, , , , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); } { var vtWithNull = CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string, string, string, string, string, string>(null, null, null, null, null, null)); var tupleWithNull = CreateLongRef(1, 2, 3, 4, 5, 6, 7, new Tuple<string, string, string, string, string, string>(null, null, null, null, null, null)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, , , , , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); } { var vtWithNull = CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string, string, string, string, string, string, string>(null, null, null, null, null, null, null)); var tupleWithNull = CreateLongRef(1, 2, 3, 4, 5, 6, 7, new Tuple<string, string, string, string, string, string, string>(null, null, null, null, null, null, null)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, , , , , , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); } } [Fact] public static void EightTuplesWithBadRest() { var d = default(ValueTuple<int, int, int, int, int, int, int, int>); d.Item1 = 1; d.Rest = 42; Assert.Equal("(1, 0, 0, 0, 0, 0, 0, 42)", d.ToString()); // GetHashCode only tries to hash the first 7 elements when rest is not ITupleInternal Assert.Equal(ValueTuple.Create(1, 0, 0, 0, 0, 0, 0).GetHashCode(), d.GetHashCode()); Assert.Equal(((IStructuralEquatable)ValueTuple.Create(1, 0, 0, 0, 0, 0, 0)).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)d).GetHashCode(TestEqualityComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 0, 0, 0, 0, 0, 0, 42)", CreateLong(1, 2, 3, 4, 5, 6, 7, d).ToString()); #if NETCOREAPP ITuple it = d; Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Equal(0, it[1]); Assert.Equal(0, it[2]); Assert.Equal(0, it[3]); Assert.Equal(0, it[4]); Assert.Equal(0, it[5]); Assert.Equal(0, it[6]); Assert.Equal(42, it[7]); Assert.Throws<IndexOutOfRangeException>(() => it[8].ToString()); #endif } private class TestClass : IComparable { private readonly int _value; internal TestClass() : this(0) { } internal TestClass(int value) { this._value = value; } public override string ToString() { return "{" + _value.ToString() + "}"; } public int CompareTo(object x) { TestClass tmp = x as TestClass; if (tmp != null) return this._value.CompareTo(tmp._value); else return 1; } } private class TestClass2 { private readonly int _value; internal TestClass2() : this(0) { } internal TestClass2(int value) { this._value = value; } public override string ToString() { return "[" + _value.ToString() + "]"; } public override bool Equals(object x) { TestClass2 tmp = x as TestClass2; if (tmp != null) return _value.Equals(tmp._value); else return false; } public override int GetHashCode() { return _value.GetHashCode(); } } private class DummyTestComparer : IComparer { public static readonly DummyTestComparer Instance = new DummyTestComparer(); public int Compare(object x, object y) { return 5; } } private class TestComparer : IComparer { public static readonly TestComparer Instance = new TestComparer(); public int Compare(object x, object y) { return x.Equals(y) ? 0 : 1; } } private class DummyTestEqualityComparer : IEqualityComparer { public static readonly DummyTestEqualityComparer Instance = new DummyTestEqualityComparer(); public new bool Equals(object x, object y) { return false; } public int GetHashCode(object x) { return x.GetHashCode(); } } private class TestEqualityComparer : IEqualityComparer { public static readonly TestEqualityComparer Instance = new TestEqualityComparer(); public new bool Equals(object x, object y) { return x.Equals(y); } public int GetHashCode(object x) { return x.GetHashCode(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using Xunit; #if NETCOREAPP using System.Runtime.CompilerServices; #endif namespace System.Tests { public class ValueTupleTests { private class ValueTupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> { private int _nItems; private readonly object valueTuple; private readonly ValueTuple valueTuple0; private readonly ValueTuple<T1> valueTuple1; private readonly ValueTuple<T1, T2> valueTuple2; private readonly ValueTuple<T1, T2, T3> valueTuple3; private readonly ValueTuple<T1, T2, T3, T4> valueTuple4; private readonly ValueTuple<T1, T2, T3, T4, T5> valueTuple5; private readonly ValueTuple<T1, T2, T3, T4, T5, T6> valueTuple6; private readonly ValueTuple<T1, T2, T3, T4, T5, T6, T7> valueTuple7; private readonly ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> valueTuple8; private readonly ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>> valueTuple9; private readonly ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>> valueTuple10; internal ValueTupleTestDriver(params object[] values) { if (values.Length > 10) throw new ArgumentOutOfRangeException("values", "You must provide at most 10 values"); _nItems = values.Length; switch (_nItems) { case 0: valueTuple0 = ValueTuple.Create(); valueTuple = valueTuple0; break; case 1: valueTuple1 = ValueTuple.Create((T1)values[0]); valueTuple = valueTuple1; break; case 2: valueTuple2 = ValueTuple.Create((T1)values[0], (T2)values[1]); valueTuple = valueTuple2; break; case 3: valueTuple3 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2]); valueTuple = valueTuple3; break; case 4: valueTuple4 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3]); valueTuple = valueTuple4; break; case 5: valueTuple5 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4]); valueTuple = valueTuple5; break; case 6: valueTuple6 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5]); valueTuple = valueTuple6; break; case 7: valueTuple7 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5], (T7)values[6]); valueTuple = valueTuple7; break; case 8: valueTuple8 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5], (T7)values[6], (T8)values[7]); valueTuple = valueTuple8; break; case 9: valueTuple9 = new ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5], (T7)values[6], new ValueTuple<T8, T9>((T8)values[7], (T9)values[8])); valueTuple = valueTuple9; break; case 10: valueTuple10 = new ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5], (T7)values[6], new ValueTuple<T8, T9, T10>((T8)values[7], (T9)values[8], (T10)values[9])); valueTuple = valueTuple10; break; } } private void VerifyItem(int itemPos, object Item1, object Item2) { Assert.True(object.Equals(Item1, Item2)); } public void TestConstructor(params object[] expectedValue) { if (expectedValue.Length != _nItems) throw new ArgumentOutOfRangeException("expectedValues", "You must provide " + _nItems + " expectedvalues"); switch (_nItems) { case 0: break; case 1: VerifyItem(1, valueTuple1.Item1, expectedValue[0]); break; case 2: VerifyItem(1, valueTuple2.Item1, expectedValue[0]); VerifyItem(2, valueTuple2.Item2, expectedValue[1]); break; case 3: VerifyItem(1, valueTuple3.Item1, expectedValue[0]); VerifyItem(2, valueTuple3.Item2, expectedValue[1]); VerifyItem(3, valueTuple3.Item3, expectedValue[2]); break; case 4: VerifyItem(1, valueTuple4.Item1, expectedValue[0]); VerifyItem(2, valueTuple4.Item2, expectedValue[1]); VerifyItem(3, valueTuple4.Item3, expectedValue[2]); VerifyItem(4, valueTuple4.Item4, expectedValue[3]); break; case 5: VerifyItem(1, valueTuple5.Item1, expectedValue[0]); VerifyItem(2, valueTuple5.Item2, expectedValue[1]); VerifyItem(3, valueTuple5.Item3, expectedValue[2]); VerifyItem(4, valueTuple5.Item4, expectedValue[3]); VerifyItem(5, valueTuple5.Item5, expectedValue[4]); break; case 6: VerifyItem(1, valueTuple6.Item1, expectedValue[0]); VerifyItem(2, valueTuple6.Item2, expectedValue[1]); VerifyItem(3, valueTuple6.Item3, expectedValue[2]); VerifyItem(4, valueTuple6.Item4, expectedValue[3]); VerifyItem(5, valueTuple6.Item5, expectedValue[4]); VerifyItem(6, valueTuple6.Item6, expectedValue[5]); break; case 7: VerifyItem(1, valueTuple7.Item1, expectedValue[0]); VerifyItem(2, valueTuple7.Item2, expectedValue[1]); VerifyItem(3, valueTuple7.Item3, expectedValue[2]); VerifyItem(4, valueTuple7.Item4, expectedValue[3]); VerifyItem(5, valueTuple7.Item5, expectedValue[4]); VerifyItem(6, valueTuple7.Item6, expectedValue[5]); VerifyItem(7, valueTuple7.Item7, expectedValue[6]); break; case 8: // Extended ValueTuple VerifyItem(1, valueTuple8.Item1, expectedValue[0]); VerifyItem(2, valueTuple8.Item2, expectedValue[1]); VerifyItem(3, valueTuple8.Item3, expectedValue[2]); VerifyItem(4, valueTuple8.Item4, expectedValue[3]); VerifyItem(5, valueTuple8.Item5, expectedValue[4]); VerifyItem(6, valueTuple8.Item6, expectedValue[5]); VerifyItem(7, valueTuple8.Item7, expectedValue[6]); VerifyItem(8, valueTuple8.Rest.Item1, expectedValue[7]); break; case 9: // Extended ValueTuple VerifyItem(1, valueTuple9.Item1, expectedValue[0]); VerifyItem(2, valueTuple9.Item2, expectedValue[1]); VerifyItem(3, valueTuple9.Item3, expectedValue[2]); VerifyItem(4, valueTuple9.Item4, expectedValue[3]); VerifyItem(5, valueTuple9.Item5, expectedValue[4]); VerifyItem(6, valueTuple9.Item6, expectedValue[5]); VerifyItem(7, valueTuple9.Item7, expectedValue[6]); VerifyItem(8, valueTuple9.Rest.Item1, expectedValue[7]); VerifyItem(9, valueTuple9.Rest.Item2, expectedValue[8]); break; case 10: // Extended ValueTuple VerifyItem(1, valueTuple10.Item1, expectedValue[0]); VerifyItem(2, valueTuple10.Item2, expectedValue[1]); VerifyItem(3, valueTuple10.Item3, expectedValue[2]); VerifyItem(4, valueTuple10.Item4, expectedValue[3]); VerifyItem(5, valueTuple10.Item5, expectedValue[4]); VerifyItem(6, valueTuple10.Item6, expectedValue[5]); VerifyItem(7, valueTuple10.Item7, expectedValue[6]); VerifyItem(8, valueTuple10.Rest.Item1, expectedValue[7]); VerifyItem(9, valueTuple10.Rest.Item2, expectedValue[8]); VerifyItem(10, valueTuple10.Rest.Item3, expectedValue[9]); break; default: throw new ArgumentException("Must specify between 0 and 10 expected values (inclusive)."); } } public void TestToString(string expected) { Assert.Equal(expected, valueTuple.ToString()); } public void TestEquals_GetHashCode(ValueTupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> other, bool expectEqual, bool expectStructuallyEqual) { if (expectEqual) { Assert.True(valueTuple.Equals(other.valueTuple)); Assert.Equal(valueTuple.GetHashCode(), other.valueTuple.GetHashCode()); } else { Assert.False(valueTuple.Equals(other.valueTuple)); Assert.NotEqual(valueTuple.GetHashCode(), other.valueTuple.GetHashCode()); } if (expectStructuallyEqual) { var equatable = ((IStructuralEquatable)valueTuple); var otherEquatable = ((IStructuralEquatable)other.valueTuple); Assert.True(equatable.Equals(other.valueTuple, TestEqualityComparer.Instance)); Assert.Equal(equatable.GetHashCode(TestEqualityComparer.Instance), otherEquatable.GetHashCode(TestEqualityComparer.Instance)); } else { var equatable = ((IStructuralEquatable)valueTuple); var otherEquatable = ((IStructuralEquatable)other.valueTuple); Assert.False(equatable.Equals(other.valueTuple, TestEqualityComparer.Instance)); Assert.NotEqual(equatable.GetHashCode(TestEqualityComparer.Instance), otherEquatable.GetHashCode(TestEqualityComparer.Instance)); } Assert.False(valueTuple.Equals(null)); Assert.False(((IStructuralEquatable)valueTuple).Equals(null)); IStructuralEquatable_Equals_NullComparer_ThrowsNullReferenceException(); IStructuralEquatable_GetHashCode_NullComparer_ThrowsNullReferenceException(); } public void IStructuralEquatable_Equals_NullComparer_ThrowsNullReferenceException() { // This was not fixed in order to be compatible with the .NET Framework and Xamarin. // https://github.com/dotnet/runtime/issues/19275 IStructuralEquatable equatable = (IStructuralEquatable)valueTuple; if (valueTuple is ValueTuple) { Assert.True(equatable.Equals(valueTuple, null)); } else { Assert.Throws<NullReferenceException>(() => equatable.Equals(valueTuple, null)); } } public void IStructuralEquatable_GetHashCode_NullComparer_ThrowsNullReferenceException() { // This was not fixed in order to be compatible with the .NET Framework and Xamarin. // https://github.com/dotnet/runtime/issues/19275 IStructuralEquatable equatable = (IStructuralEquatable)valueTuple; if (valueTuple is ValueTuple) { Assert.Equal(0, valueTuple.GetHashCode()); } else { Assert.Throws<NullReferenceException>(() => equatable.GetHashCode(null)); } } public void TestCompareTo(ValueTupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> other, int expectedResult, int expectedStructuralResult) { Assert.Equal(expectedResult, ((IComparable)valueTuple).CompareTo(other.valueTuple)); Assert.Equal(expectedStructuralResult, ((IStructuralComparable)valueTuple).CompareTo(other.valueTuple, DummyTestComparer.Instance)); Assert.Equal(1, ((IComparable)valueTuple).CompareTo(null)); IStructuralComparable_NullComparer_ThrowsNullReferenceException(); } public void IStructuralComparable_NullComparer_ThrowsNullReferenceException() { // This was not fixed in order to be compatible with the .NET Framework and Xamarin. // https://github.com/dotnet/runtime/issues/19275 IStructuralComparable comparable = (IStructuralComparable)valueTuple; if (valueTuple is ValueTuple) { Assert.Equal(0, comparable.CompareTo(valueTuple, null)); } else { Assert.Throws<NullReferenceException>(() => comparable.CompareTo(valueTuple, null)); } } public void TestNotEqual() { ValueTuple<int> ValueTupleB = new ValueTuple<int>((int)10000); Assert.NotEqual(valueTuple, ValueTupleB); } internal void TestCompareToThrows() { ValueTuple<int> ValueTupleB = new ValueTuple<int>((int)10000); AssertExtensions.Throws<ArgumentException>("other", () => ((IComparable)valueTuple).CompareTo(ValueTupleB)); } } [Fact] public static void TestConstructor() { ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan> ValueTupleDriverA; //ValueTuple-0 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(); ValueTupleDriverA.TestConstructor(); //ValueTuple-1 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue); ValueTupleDriverA.TestConstructor(short.MaxValue); //ValueTuple-2 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); ValueTupleDriverA.TestConstructor(short.MinValue, int.MaxValue); //ValueTuple-3 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); ValueTupleDriverA.TestConstructor((short)0, (int)0, long.MaxValue); //ValueTuple-4 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); ValueTupleDriverA.TestConstructor((short)1, (int)1, long.MinValue, "This"); //ValueTuple-5 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); ValueTupleDriverA.TestConstructor((short)(-1), (int)(-1), (long)0, "is", 'A'); //ValueTuple-6 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MaxValue); ValueTupleDriverA.TestConstructor((short)10, (int)100, (long)1, "testing", 'Z', float.MaxValue); //ValueTuple-7 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue); ValueTupleDriverA.TestConstructor((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue); object myObj = new object(); //ValueTuple-10 DateTime now = DateTime.Now; ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (float)0.0001, (double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero); ValueTupleDriverA.TestConstructor((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (float)0.0001, (double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero); } [Fact] public static void TestToString() { ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan> ValueTupleDriverA; //ValueTuple-0 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(); ValueTupleDriverA.TestToString("()"); //ValueTuple-1 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue); ValueTupleDriverA.TestToString("(" + short.MaxValue + ")"); //ValueTuple-2 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); ValueTupleDriverA.TestToString("(" + short.MinValue + ", " + int.MaxValue + ")"); //ValueTuple-3 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); ValueTupleDriverA.TestToString("(" + ((short)0) + ", " + ((int)0) + ", " + long.MaxValue + ")"); //ValueTuple-4 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); ValueTupleDriverA.TestConstructor((short)1, (int)1, long.MinValue, "This"); ValueTupleDriverA.TestToString("(" + ((short)1) + ", " + ((int)1) + ", " + long.MinValue + ", This)"); //ValueTuple-5 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); ValueTupleDriverA.TestToString("(" + ((short)(-1)) + ", " + ((int)(-1)) + ", " + ((long)0) + ", is, A)"); //ValueTuple-6 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MaxValue); ValueTupleDriverA.TestToString("(" + ((short)10) + ", " + ((int)100) + ", " + ((long)1) + ", testing, Z, " + float.MaxValue + ")"); //ValueTuple-7 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue); ValueTupleDriverA.TestToString("(" + ((short)(-100)) + ", " + ((int)(-1000)) + ", " + ((long)(-1)) + ", ValueTuples, , " + float.MinValue + ", " + double.MaxValue + ")"); object myObj = new object(); //ValueTuple-10 DateTime now = DateTime.Now; ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (float)0.0001, (double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero); // .NET Native bug 438149 - object.ToString in incorrect ValueTupleDriverA.TestToString("(" + ((short)10000) + ", " + ((int)1000000) + ", " + ((long)10000000) + ", 2008?7?2?, 0, " + ((float)0.0001) + ", " + ((double)0.0000001) + ", " + now + ", (False, System.Object), " + TimeSpan.Zero + ")"); } [Fact] public static void TestEquals_GetHashCode() { ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan> ValueTupleDriverA, ValueTupleDriverB, ValueTupleDriverC, ValueTupleDriverD; //ValueTuple-0 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(); ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue, int.MaxValue); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false); //ValueTuple-1 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue); ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue, int.MaxValue); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false); //ValueTuple-2 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MinValue); ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), long.MinValue); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false); //ValueTuple-3 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), long.MinValue); ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "this"); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false); //ValueTuple-4 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "this"); ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, (long)1, "IS", 'a'); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false); //ValueTuple-5 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, (long)1, "IS", 'a'); ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MinValue); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false); //ValueTuple-6 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MinValue); ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "ValueTuples", ' ', float.MinValue, (double)0.0); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false); //ValueTuple-7 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "ValueTuples", ' ', float.MinValue, (double)0.0); ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10001, (int)1000001, (long)10000001, "2008?7?3?", '1', (float)0.0002, (double)0.0000002, DateTime.Now.AddMilliseconds(1)); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false); //ValueTuple-8 DateTime now = DateTime.Now; ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue, now); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue, now); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "ValueTuples", ' ', float.MinValue, (double)0.0, now.AddMilliseconds(1)); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); object myObj = new object(); //ValueTuple-10 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (float)0.0001, (double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (float)0.0001, (double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10001, (int)1000001, (long)10000001, "2008?7?3?", '1', (float)0.0002, (double)0.0000002, now.AddMilliseconds(1), ValueTuple.Create(true, myObj), TimeSpan.MaxValue); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true); ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false); } [Fact] public static void TestCompareTo() { ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan> ValueTupleDriverA, ValueTupleDriverB, ValueTupleDriverC; //ValueTuple-0 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 0); //ValueTuple-1 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5); ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 65535, 5); //ValueTuple-2 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MinValue); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5); ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 1, 5); //ValueTuple-3 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), long.MinValue); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5); ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 1, 5); //ValueTuple-4 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "this"); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5); ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 1, 5); //ValueTuple-5 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, (long)1, "IS", 'a'); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5); ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, -1, 5); //ValueTuple-6 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', float.MinValue); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5); ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 1, 5); //ValueTuple-7 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', float.MinValue, double.MaxValue); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "ValueTuples", ' ', float.MinValue, (double)0.0); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5); ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 1, 5); object myObj = new object(); //ValueTuple-10 DateTime now = DateTime.Now; ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (float)0.0001, (double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero); ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (float)0.0001, (double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero); ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10001, (int)1000001, (long)10000001, "2008?7?3?", '1', (float)0.0002, (double)0.0000002, now.AddMilliseconds(1), ValueTuple.Create(true, myObj), TimeSpan.MaxValue); ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5); ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, -1, 5); } [Fact] public static void TestNotEqual() { ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan> ValueTupleDriverA; //ValueTuple-0 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>(); ValueTupleDriverA.TestNotEqual(); //ValueTuple-1 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000); ValueTupleDriverA.TestNotEqual(); // This is for code coverage purposes //ValueTuple-2 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000); ValueTupleDriverA.TestNotEqual(); //ValueTuple-3 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000); ValueTupleDriverA.TestNotEqual(); //ValueTuple-4 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?"); ValueTupleDriverA.TestNotEqual(); //ValueTuple-5 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0'); ValueTupleDriverA.TestNotEqual(); //ValueTuple-6 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', float.NaN); ValueTupleDriverA.TestNotEqual(); //ValueTuple-7 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', float.NaN, double.NegativeInfinity); ValueTupleDriverA.TestNotEqual(); //ValueTuple-8, extended ValueTuple ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', float.NaN, double.NegativeInfinity, DateTime.Now); ValueTupleDriverA.TestNotEqual(); //ValueTuple-9 and ValueTuple-10 are not necessary because they use the same code path as ValueTuple-8 } [Fact] public static void IncomparableTypes() { ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan> ValueTupleDriverA; //ValueTuple-0 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>(); ValueTupleDriverA.TestCompareToThrows(); //ValueTuple-1 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000); ValueTupleDriverA.TestCompareToThrows(); // This is for code coverage purposes //ValueTuple-2 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000); ValueTupleDriverA.TestCompareToThrows(); //ValueTuple-3 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000); ValueTupleDriverA.TestCompareToThrows(); //ValueTuple-4 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?"); ValueTupleDriverA.TestCompareToThrows(); //ValueTuple-5 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0'); ValueTupleDriverA.TestCompareToThrows(); //ValueTuple-6 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', float.NaN); ValueTupleDriverA.TestCompareToThrows(); //ValueTuple-7 ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', float.NaN, double.NegativeInfinity); ValueTupleDriverA.TestCompareToThrows(); //ValueTuple-8, extended ValueTuple ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, char, float, double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', float.NaN, double.NegativeInfinity, DateTime.Now); ValueTupleDriverA.TestCompareToThrows(); //ValueTuple-9 and ValueTuple-10 are not necessary because they use the same code path as ValueTuple-8 } [Fact] public static void FloatingPointNaNCases() { var a = ValueTuple.Create(double.MinValue, double.NaN, float.MinValue, float.NaN); var b = ValueTuple.Create(double.MinValue, double.NaN, float.MinValue, float.NaN); Assert.True(a.Equals(b)); Assert.Equal(0, ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); } [Fact] public static void TestCustomTypeParameter1() { // Special case of ValueTuple<T1> where T1 is a custom type var testClass = new TestClass(); var a = ValueTuple.Create(testClass); var b = ValueTuple.Create(testClass); Assert.True(a.Equals(b)); Assert.Equal(0, ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); } [Fact] public static void TestCustomTypeParameter2() { // Special case of ValueTuple<T1, T2> where T2 is a custom type var testClass = new TestClass(1); var a = ValueTuple.Create(1, testClass); var b = ValueTuple.Create(1, testClass); Assert.True(a.Equals(b)); Assert.Equal(0, ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); } [Fact] public static void TestCustomTypeParameter3() { // Special case of ValueTuple<T1, T2> where T1 and T2 are custom types var testClassA = new TestClass(100); var testClassB = new TestClass(101); var a = ValueTuple.Create(testClassA, testClassB); var b = ValueTuple.Create(testClassB, testClassA); Assert.False(a.Equals(b)); Assert.Equal(-1, ((IComparable)a).CompareTo(b)); Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance)); // Equals(IEqualityComparer) is false, ignore hash code } [Fact] public static void TestCustomTypeParameter4() { // Special case of ValueTuple<T1, T2> where T1 and T2 are custom types var testClassA = new TestClass(100); var testClassB = new TestClass(101); var a = ValueTuple.Create(testClassA, testClassB); var b = ValueTuple.Create(testClassA, testClassA); Assert.False(a.Equals(b)); Assert.Equal(1, ((IComparable)a).CompareTo(b)); Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance)); // Equals(IEqualityComparer) is false, ignore hash code } [Fact] public static void NestedValueTuples1() { var a = ValueTuple.Create(1, 2, ValueTuple.Create(31, 32), 4, 5, 6, 7, ValueTuple.Create(8, 9)); var b = ValueTuple.Create(1, 2, ValueTuple.Create(31, 32), 4, 5, 6, 7, ValueTuple.Create(8, 9)); Assert.True(a.Equals(b)); Assert.Equal(0, ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); Assert.Equal("(1, 2, (31, 32), 4, 5, 6, 7, (8, 9))", a.ToString()); Assert.Equal("(31, 32)", a.Item3.ToString()); Assert.Equal("((8, 9))", a.Rest.ToString()); } [Fact] public static void NestedValueTuples2() { var a = ValueTuple.Create(0, 1, 2, 3, 4, 5, 6, ValueTuple.Create(7, 8, 9, 10, 11, 12, 13, ValueTuple.Create(14, 15))); var b = ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10, 11, 12, 13, 14, ValueTuple.Create(15, 16))); Assert.False(a.Equals(b)); Assert.Equal(-1, ((IComparable)a).CompareTo(b)); Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance)); Assert.Equal("(0, 1, 2, 3, 4, 5, 6, (7, 8, 9, 10, 11, 12, 13, (14, 15)))", a.ToString()); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, (8, 9, 10, 11, 12, 13, 14, (15, 16)))", b.ToString()); Assert.Equal("((7, 8, 9, 10, 11, 12, 13, (14, 15)))", a.Rest.ToString()); var a2 = Tuple.Create(0, 1, 2, 3, 4, 5, 6, Tuple.Create(7, 8, 9, 10, 11, 12, 13, Tuple.Create(14, 15))); var b2 = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10, 11, 12, 13, 14, Tuple.Create(15, 16))); Assert.Equal(a2.ToString(), a.ToString()); Assert.Equal(b2.ToString(), b.ToString()); Assert.Equal(a2.Rest.ToString(), a.Rest.ToString()); } [Fact] public static void IncomparableTypesSpecialCase() { // Special case when T does not implement IComparable var testClassA = new TestClass2(100); var testClassB = new TestClass2(100); var a = ValueTuple.Create(testClassA); var b = ValueTuple.Create(testClassB); Assert.True(a.Equals(b)); AssertExtensions.Throws<ArgumentException>(null, () => ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); Assert.Equal("([100])", a.ToString()); } [Fact] public static void ZeroTuples() { var a = ValueTuple.Create(); Assert.True(a.Equals(new ValueTuple())); Assert.Equal(0, a.CompareTo(new ValueTuple())); Assert.Equal(1, ((IStructuralComparable)a).CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)a).CompareTo("string", DummyTestComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, )", CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple()).ToString()); #if NETCOREAPP ITuple it = ValueTuple.Create(); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Throws<IndexOutOfRangeException>(() => it[0].ToString()); Assert.Throws<IndexOutOfRangeException>(() => it[1].ToString()); #endif } [Fact] public static void OneTuples() { IComparable c = ValueTuple.Create(1); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3))); IStructuralComparable sc = (IStructuralComparable)c; Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(3), TestComparer.Instance)); Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1)", CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(1)).ToString()); var vtWithNull = new ValueTuple<string>(null); var tupleWithNull = new Tuple<string>(null); Assert.Equal("()", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); #if NETCOREAPP ITuple it = ValueTuple.Create(1); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Throws<IndexOutOfRangeException>(() => it[1].ToString()); #endif } [Fact] public static void TwoTuples() { IComparable c = ValueTuple.Create(1, 1); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3))); IStructuralComparable sc = (IStructuralComparable)c; Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3), TestComparer.Instance)); Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 2)", CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(1, 2)).ToString()); var vtWithNull = new ValueTuple<string, string>(null, null); var tupleWithNull = new Tuple<string, string>(null, null); Assert.Equal("(, )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); #if NETCOREAPP ITuple it = ValueTuple.Create(1, 2); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Equal(2, it[1]); Assert.Throws<IndexOutOfRangeException>(() => it[2].ToString()); #endif } [Fact] public static void ThreeTuples() { IComparable c = ValueTuple.Create(1, 1, 1); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 3))); IStructuralComparable sc = (IStructuralComparable)c; Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 3), TestComparer.Instance)); Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 2, 3)", CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(1, 2, 3)).ToString()); var vtWithNull = new ValueTuple<string, string, string>(null, null, null); var tupleWithNull = new Tuple<string, string, string>(null, null, null); Assert.Equal("(, , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); #if NETCOREAPP ITuple it = ValueTuple.Create(1, 2, 3); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Equal(2, it[1]); Assert.Equal(3, it[2]); Assert.Throws<IndexOutOfRangeException>(() => it[3].ToString()); #endif } [Fact] public static void FourTuples() { IComparable c = ValueTuple.Create(1, 1, 1, 1); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 3, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 3))); IStructuralComparable sc = (IStructuralComparable)c; Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(3, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 3, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 3), TestComparer.Instance)); Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4)", CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(1, 2, 3, 4)).ToString()); var vtWithNull = new ValueTuple<string, string, string, string>(null, null, null, null); var tupleWithNull = new Tuple<string, string, string, string>(null, null, null, null); Assert.Equal("(, , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); #if NETCOREAPP ITuple it = ValueTuple.Create(1, 2, 3, 4); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Equal(2, it[1]); Assert.Equal(3, it[2]); Assert.Equal(4, it[3]); Assert.Throws<IndexOutOfRangeException>(() => it[4].ToString()); #endif } [Fact] public static void FiveTuples() { IComparable c = ValueTuple.Create(1, 1, 1, 1, 1); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3))); IStructuralComparable sc = (IStructuralComparable)c; Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3), TestComparer.Instance)); Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5)", CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(1, 2, 3, 4, 5)).ToString()); var vtWithNull = new ValueTuple<string, string, string, string, string>(null, null, null, null, null); var tupleWithNull = new Tuple<string, string, string, string, string>(null, null, null, null, null); Assert.Equal("(, , , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); #if NETCOREAPP ITuple it = ValueTuple.Create(1, 2, 3, 4, 5); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Equal(2, it[1]); Assert.Equal(3, it[2]); Assert.Equal(4, it[3]); Assert.Equal(5, it[4]); Assert.Throws<IndexOutOfRangeException>(() => it[5].ToString()); #endif } [Fact] public static void SixTuples() { IComparable c = ValueTuple.Create(1, 1, 1, 1, 1, 1); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 3))); IStructuralComparable sc = (IStructuralComparable)c; Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 3), TestComparer.Instance)); Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6)", CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(1, 2, 3, 4, 5, 6)).ToString()); var vtWithNull = new ValueTuple<string, string, string, string, string, string>(null, null, null, null, null, null); var tupleWithNull = new Tuple<string, string, string, string, string, string>(null, null, null, null, null, null); Assert.Equal("(, , , , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); #if NETCOREAPP ITuple it = ValueTuple.Create(1, 2, 3, 4, 5, 6); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Equal(2, it[1]); Assert.Equal(3, it[2]); Assert.Equal(4, it[3]); Assert.Equal(5, it[4]); Assert.Equal(6, it[5]); Assert.Throws<IndexOutOfRangeException>(() => it[6].ToString()); #endif } [Fact] public static void SevenTuples() { IComparable c = ValueTuple.Create(1, 1, 1, 1, 1, 1, 1); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3, 1, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 3, 1))); Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 1, 3))); IStructuralComparable sc = (IStructuralComparable)c; Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3, 1, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 3, 1), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 1, 3), TestComparer.Instance)); Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7)", CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(1, 2, 3, 4, 5, 6, 7)).ToString()); var vtWithNull = new ValueTuple<string, string, string, string, string, string, string>(null, null, null, null, null, null, null); var tupleWithNull = new Tuple<string, string, string, string, string, string, string>(null, null, null, null, null, null, null); Assert.Equal("(, , , , , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); #if NETCOREAPP ITuple it = ValueTuple.Create(1, 2, 3, 4, 5, 6, 7); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Equal(2, it[1]); Assert.Equal(3, it[2]); Assert.Equal(4, it[3]); Assert.Equal(5, it[4]); Assert.Equal(6, it[5]); Assert.Equal(7, it[6]); Assert.Throws<IndexOutOfRangeException>(() => it[7].ToString()); #endif } public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> CreateLong<T1, T2, T3, T4, T5, T6, T7, TRest>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) where TRest : struct { return new ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>(item1, item2, item3, item4, item5, item6, item7, rest); } public static Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> CreateLongRef<T1, T2, T3, T4, T5, T6, T7, TRest>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { return new Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>(item1, item2, item3, item4, item5, item6, item7, rest); } [Fact] public static void EightTuples() { var x = new Tuple<int, int, int, int, int, int, int, Tuple<string, string>>(1, 2, 3, 4, 5, 6, 7, new Tuple<string, string>("alice", "bob")); var y = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<string, string>>(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string, string>("alice", "bob")); Assert.Equal(x.ToString(), y.ToString()); var t = CreateLong(1, 1, 1, 1, 1, 1, 1, ValueTuple.Create(1)); IStructuralEquatable se = t; Assert.False(se.Equals(null, TestEqualityComparer.Instance)); Assert.False(se.Equals("string", TestEqualityComparer.Instance)); Assert.False(se.Equals(new ValueTuple(), TestEqualityComparer.Instance)); IComparable c = t; Assert.Equal(-1, c.CompareTo(CreateLong(3, 1, 1, 1, 1, 1, 1, ValueTuple.Create(1)))); Assert.Equal(-1, c.CompareTo(CreateLong(1, 3, 1, 1, 1, 1, 1, ValueTuple.Create(1)))); Assert.Equal(-1, c.CompareTo(CreateLong(1, 1, 3, 1, 1, 1, 1, ValueTuple.Create(1)))); Assert.Equal(-1, c.CompareTo(CreateLong(1, 1, 1, 3, 1, 1, 1, ValueTuple.Create(1)))); Assert.Equal(-1, c.CompareTo(CreateLong(1, 1, 1, 1, 3, 1, 1, ValueTuple.Create(1)))); Assert.Equal(-1, c.CompareTo(CreateLong(1, 1, 1, 1, 1, 3, 1, ValueTuple.Create(1)))); Assert.Equal(-1, c.CompareTo(CreateLong(1, 1, 1, 1, 1, 1, 3, ValueTuple.Create(1)))); IStructuralComparable sc = t; Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance)); AssertExtensions.Throws<ArgumentException>("other", () => sc.CompareTo("string", DummyTestComparer.Instance)); Assert.Equal(1, sc.CompareTo(CreateLong(3, 1, 1, 1, 1, 1, 1, ValueTuple.Create(1)), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(CreateLong(1, 3, 1, 1, 1, 1, 1, ValueTuple.Create(1)), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(CreateLong(1, 1, 3, 1, 1, 1, 1, ValueTuple.Create(1)), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(CreateLong(1, 1, 1, 3, 1, 1, 1, ValueTuple.Create(1)), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(CreateLong(1, 1, 1, 1, 3, 1, 1, ValueTuple.Create(1)), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(CreateLong(1, 1, 1, 1, 1, 3, 1, ValueTuple.Create(1)), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(CreateLong(1, 1, 1, 1, 1, 1, 3, ValueTuple.Create(1)), TestComparer.Instance)); Assert.Equal(1, sc.CompareTo(CreateLong(1, 1, 1, 1, 1, 1, 1, ValueTuple.Create(3)), TestComparer.Instance)); Assert.False(se.Equals(t, DummyTestEqualityComparer.Instance)); // Notice that 0-tuple prints as empty position Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, )", CreateLong(1, 2, 3, 4, 5, 6, 7, CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create())).ToString()); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 1)", CreateLong(1, 2, 3, 4, 5, 6, 7, CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(1))).ToString()); var vtWithNull = new ValueTuple<string, string, string, string, string, string, string, ValueTuple<string>>(null, null, null, null, null, null, null, new ValueTuple<string>(null)); var tupleWithNull = new Tuple<string, string, string, string, string, string, string, Tuple<string>>(null, null, null, null, null, null, null, new Tuple<string>(null)); Assert.Equal("(, , , , , , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); #if NETCOREAPP ITuple it = CreateLong(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8)); Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Equal(2, it[1]); Assert.Equal(3, it[2]); Assert.Equal(4, it[3]); Assert.Equal(5, it[4]); Assert.Equal(6, it[5]); Assert.Equal(7, it[6]); Assert.Equal(8, it[7]); Assert.Throws<IndexOutOfRangeException>(() => it[8].ToString()); #endif } [Fact] public static void LongTuplesWithNull() { { var vtWithNull = CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string>(null)); var tupleWithNull = CreateLongRef(1, 2, 3, 4, 5, 6, 7, new Tuple<string>(null)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); } { var vtWithNull = CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string>(null)); var tupleWithNull = CreateLongRef(1, 2, 3, 4, 5, 6, 7, new Tuple<string>(null)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); } { var vtWithNull = CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string, string>(null, null)); var tupleWithNull = CreateLongRef(1, 2, 3, 4, 5, 6, 7, new Tuple<string, string>(null, null)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); } { var vtWithNull = CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string, string, string>(null, null, null)); var tupleWithNull = CreateLongRef(1, 2, 3, 4, 5, 6, 7, new Tuple<string, string, string>(null, null, null)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); } { var vtWithNull = CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string, string, string, string>(null, null, null, null)); var tupleWithNull = CreateLongRef(1, 2, 3, 4, 5, 6, 7, new Tuple<string, string, string, string>(null, null, null, null)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, , , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); } { var vtWithNull = CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string, string, string, string, string>(null, null, null, null, null)); var tupleWithNull = CreateLongRef(1, 2, 3, 4, 5, 6, 7, new Tuple<string, string, string, string, string>(null, null, null, null, null)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, , , , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); } { var vtWithNull = CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string, string, string, string, string, string>(null, null, null, null, null, null)); var tupleWithNull = CreateLongRef(1, 2, 3, 4, 5, 6, 7, new Tuple<string, string, string, string, string, string>(null, null, null, null, null, null)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, , , , , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); } { var vtWithNull = CreateLong(1, 2, 3, 4, 5, 6, 7, new ValueTuple<string, string, string, string, string, string, string>(null, null, null, null, null, null, null)); var tupleWithNull = CreateLongRef(1, 2, 3, 4, 5, 6, 7, new Tuple<string, string, string, string, string, string, string>(null, null, null, null, null, null, null)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, , , , , , , )", vtWithNull.ToString()); Assert.Equal(tupleWithNull.ToString(), vtWithNull.ToString()); } } [Fact] public static void EightTuplesWithBadRest() { var d = default(ValueTuple<int, int, int, int, int, int, int, int>); d.Item1 = 1; d.Rest = 42; Assert.Equal("(1, 0, 0, 0, 0, 0, 0, 42)", d.ToString()); // GetHashCode only tries to hash the first 7 elements when rest is not ITupleInternal Assert.Equal(ValueTuple.Create(1, 0, 0, 0, 0, 0, 0).GetHashCode(), d.GetHashCode()); Assert.Equal(((IStructuralEquatable)ValueTuple.Create(1, 0, 0, 0, 0, 0, 0)).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)d).GetHashCode(TestEqualityComparer.Instance)); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, 1, 0, 0, 0, 0, 0, 0, 42)", CreateLong(1, 2, 3, 4, 5, 6, 7, d).ToString()); #if NETCOREAPP ITuple it = d; Assert.Throws<IndexOutOfRangeException>(() => it[-1].ToString()); Assert.Equal(1, it[0]); Assert.Equal(0, it[1]); Assert.Equal(0, it[2]); Assert.Equal(0, it[3]); Assert.Equal(0, it[4]); Assert.Equal(0, it[5]); Assert.Equal(0, it[6]); Assert.Equal(42, it[7]); Assert.Throws<IndexOutOfRangeException>(() => it[8].ToString()); #endif } private class TestClass : IComparable { private readonly int _value; internal TestClass() : this(0) { } internal TestClass(int value) { this._value = value; } public override string ToString() { return "{" + _value.ToString() + "}"; } public int CompareTo(object x) { TestClass tmp = x as TestClass; if (tmp != null) return this._value.CompareTo(tmp._value); else return 1; } } private class TestClass2 { private readonly int _value; internal TestClass2() : this(0) { } internal TestClass2(int value) { this._value = value; } public override string ToString() { return "[" + _value.ToString() + "]"; } public override bool Equals(object x) { TestClass2 tmp = x as TestClass2; if (tmp != null) return _value.Equals(tmp._value); else return false; } public override int GetHashCode() { return _value.GetHashCode(); } } private class DummyTestComparer : IComparer { public static readonly DummyTestComparer Instance = new DummyTestComparer(); public int Compare(object x, object y) { return 5; } } private class TestComparer : IComparer { public static readonly TestComparer Instance = new TestComparer(); public int Compare(object x, object y) { return x.Equals(y) ? 0 : 1; } } private class DummyTestEqualityComparer : IEqualityComparer { public static readonly DummyTestEqualityComparer Instance = new DummyTestEqualityComparer(); public new bool Equals(object x, object y) { return false; } public int GetHashCode(object x) { return x.GetHashCode(); } } private class TestEqualityComparer : IEqualityComparer { public static readonly TestEqualityComparer Instance = new TestEqualityComparer(); public new bool Equals(object x, object y) { return x.Equals(y); } public int GetHashCode(object x) { return x.GetHashCode(); } } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Diagnostics.TextWriterTraceListener/tests/TextWriterTraceListener_WriteTests.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 Xunit; namespace System.Diagnostics.TextWriterTraceListenerTests { public class TextWriterTraceListener_WriteTestsCtorFileName : TextWriterTraceListener_WriteTestsBase { public TextWriterTraceListener_WriteTestsCtorFileName() { CommonUtilities.DeleteFile(_fileName); } public override TextWriterTraceListener GetListener() { return new TextWriterTraceListener(_fileName); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } } public class TextWriterTraceListener_WriteTestsCtorStream : TextWriterTraceListener_WriteTestsBase { private readonly Stream _stream; public TextWriterTraceListener_WriteTestsCtorStream() { CommonUtilities.DeleteFile(_fileName); _stream = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.Write); } public override TextWriterTraceListener GetListener() { return new TextWriterTraceListener(_stream); } [Fact] public void TestWriterPropery() { var testWriter = new StreamWriter(_stream); using (var target = new TextWriterTraceListener()) { Assert.Null(target.Writer); target.Writer = testWriter; Assert.NotNull(target.Writer); Assert.Same(testWriter, target.Writer); } } protected override void Dispose(bool disposing) { _stream.Dispose(); base.Dispose(disposing); } } public abstract class TextWriterTraceListener_WriteTestsBase : FileCleanupTestBase { protected readonly string _fileName; private const string TestMessage = "HelloWorld"; public TextWriterTraceListener_WriteTestsBase() { _fileName = $"{GetTestFilePath()}.xml"; } public abstract TextWriterTraceListener GetListener(); [Fact] public void TestWrite() { using (var target = GetListener()) { target.Write(TestMessage); } Assert.Contains(TestMessage, File.ReadAllText(_fileName)); } [Fact] public void TestWriteLine() { using (var target = GetListener()) { target.WriteLine(TestMessage); } string expected = TestMessage + Environment.NewLine; Assert.Contains(expected, File.ReadAllText(_fileName)); } [Fact] public void TestFlush() { using (var target = GetListener()) { target.Write(TestMessage); target.Flush(); } } [Fact] public void TestWriteAfterDisposeShouldNotThrow() { var target = GetListener(); target.Dispose(); target.WriteLine(TestMessage); target.Write(TestMessage); target.Flush(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } } }
// 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 Xunit; namespace System.Diagnostics.TextWriterTraceListenerTests { public class TextWriterTraceListener_WriteTestsCtorFileName : TextWriterTraceListener_WriteTestsBase { public TextWriterTraceListener_WriteTestsCtorFileName() { CommonUtilities.DeleteFile(_fileName); } public override TextWriterTraceListener GetListener() { return new TextWriterTraceListener(_fileName); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } } public class TextWriterTraceListener_WriteTestsCtorStream : TextWriterTraceListener_WriteTestsBase { private readonly Stream _stream; public TextWriterTraceListener_WriteTestsCtorStream() { CommonUtilities.DeleteFile(_fileName); _stream = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.Write); } public override TextWriterTraceListener GetListener() { return new TextWriterTraceListener(_stream); } [Fact] public void TestWriterPropery() { var testWriter = new StreamWriter(_stream); using (var target = new TextWriterTraceListener()) { Assert.Null(target.Writer); target.Writer = testWriter; Assert.NotNull(target.Writer); Assert.Same(testWriter, target.Writer); } } protected override void Dispose(bool disposing) { _stream.Dispose(); base.Dispose(disposing); } } public abstract class TextWriterTraceListener_WriteTestsBase : FileCleanupTestBase { protected readonly string _fileName; private const string TestMessage = "HelloWorld"; public TextWriterTraceListener_WriteTestsBase() { _fileName = $"{GetTestFilePath()}.xml"; } public abstract TextWriterTraceListener GetListener(); [Fact] public void TestWrite() { using (var target = GetListener()) { target.Write(TestMessage); } Assert.Contains(TestMessage, File.ReadAllText(_fileName)); } [Fact] public void TestWriteLine() { using (var target = GetListener()) { target.WriteLine(TestMessage); } string expected = TestMessage + Environment.NewLine; Assert.Contains(expected, File.ReadAllText(_fileName)); } [Fact] public void TestFlush() { using (var target = GetListener()) { target.Write(TestMessage); target.Flush(); } } [Fact] public void TestWriteAfterDisposeShouldNotThrow() { var target = GetListener(); target.Dispose(); target.WriteLine(TestMessage); target.Write(TestMessage); target.Flush(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Net.NameResolution/tests/FunctionalTests/TelemetryTest.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.Tracing; using System.Linq; using System.Net.Sockets; using System.Threading.Tasks; using Microsoft.DotNet.RemoteExecutor; using Microsoft.DotNet.XUnitExtensions; using Xunit; using Xunit.Sdk; namespace System.Net.NameResolution.Tests { public class TelemetryTest { [Fact] public static void EventSource_ExistsWithCorrectId() { Type esType = typeof(Dns).Assembly.GetType("System.Net.NameResolutionTelemetry", throwOnError: true, ignoreCase: false); Assert.NotNull(esType); Assert.Equal("System.Net.NameResolution", EventSource.GetName(esType)); Assert.Equal(Guid.Parse("4b326142-bfb5-5ed3-8585-7714181d14b0"), EventSource.GetGuid(esType)); Assert.NotEmpty(EventSource.GenerateManifest(esType, esType.Assembly.Location)); } [OuterLoop] [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public static void EventSource_ResolveValidHostName_LogsStartStop() { RemoteExecutor.Invoke(async () => { const string ValidHostName = "microsoft.com"; using var listener = new TestEventListener("System.Net.NameResolution", EventLevel.Informational); listener.AddActivityTracking(); var events = new ConcurrentQueue<(EventWrittenEventArgs Event, Guid ActivityId)>(); await listener.RunWithCallbackAsync(e => events.Enqueue((e, e.ActivityId)), async () => { await Dns.GetHostEntryAsync(ValidHostName); await Dns.GetHostAddressesAsync(ValidHostName); Dns.GetHostEntry(ValidHostName); Dns.GetHostAddresses(ValidHostName); Dns.EndGetHostEntry(Dns.BeginGetHostEntry(ValidHostName, null, null)); Dns.EndGetHostAddresses(Dns.BeginGetHostAddresses(ValidHostName, null, null)); }); VerifyEvents(events, ValidHostName, 6); }).Dispose(); } [OuterLoop] [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public static void EventSource_ResolveInvalidHostName_LogsStartFailureStop() { RemoteExecutor.Invoke(async () => { const string InvalidHostName = "invalid...example.com"; using var listener = new TestEventListener("System.Net.NameResolution", EventLevel.Informational); listener.AddActivityTracking(); var events = new ConcurrentQueue<(EventWrittenEventArgs Event, Guid ActivityId)>(); await listener.RunWithCallbackAsync(e => events.Enqueue((e, e.ActivityId)), async () => { await Assert.ThrowsAnyAsync<SocketException>(async () => await Dns.GetHostEntryAsync(InvalidHostName)); await Assert.ThrowsAnyAsync<SocketException>(async () => await Dns.GetHostAddressesAsync(InvalidHostName)); Assert.ThrowsAny<SocketException>(() => Dns.GetHostEntry(InvalidHostName)); Assert.ThrowsAny<SocketException>(() => Dns.GetHostAddresses(InvalidHostName)); Assert.ThrowsAny<SocketException>(() => Dns.EndGetHostEntry(Dns.BeginGetHostEntry(InvalidHostName, null, null))); Assert.ThrowsAny<SocketException>(() => Dns.EndGetHostAddresses(Dns.BeginGetHostAddresses(InvalidHostName, null, null))); }); VerifyEvents(events, InvalidHostName, 6, shouldHaveFailures: true); }).Dispose(); } [OuterLoop] [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public static void EventSource_GetHostEntryForIP_LogsStartStop() { RemoteExecutor.Invoke(async () => { const string ValidIPAddress = "8.8.4.4"; using var listener = new TestEventListener("System.Net.NameResolution", EventLevel.Informational); listener.AddActivityTracking(); var events = new ConcurrentQueue<(EventWrittenEventArgs Event, Guid ActivityId)>(); await listener.RunWithCallbackAsync(e => events.Enqueue((e, e.ActivityId)), async () => { IPAddress ipAddress = IPAddress.Parse(ValidIPAddress); await Dns.GetHostEntryAsync(ValidIPAddress); await Dns.GetHostEntryAsync(ipAddress); Dns.GetHostEntry(ValidIPAddress); Dns.GetHostEntry(ipAddress); Dns.EndGetHostEntry(Dns.BeginGetHostEntry(ValidIPAddress, null, null)); Dns.EndGetHostEntry(Dns.BeginGetHostEntry(ipAddress, null, null)); }); // Each GetHostEntry over an IP will yield 2 resolutions VerifyEvents(events, ValidIPAddress, 12, isHostEntryForIp: true); }).Dispose(); } private static void VerifyEvents(ConcurrentQueue<(EventWrittenEventArgs Event, Guid ActivityId)> events, string hostname, int expectedNumber, bool shouldHaveFailures = false, bool isHostEntryForIp = false) { Assert.DoesNotContain(events, e => e.Event.EventId == 0); // errors from the EventSource itself (EventWrittenEventArgs Event, Guid ActivityId)[] starts = events.Where(e => e.Event.EventName == "ResolutionStart").ToArray(); Assert.Equal(expectedNumber, starts.Length); int expectedHostnameStarts = isHostEntryForIp ? expectedNumber / 2 : expectedNumber; Assert.Equal(expectedHostnameStarts, starts.Count(s => Assert.Single(s.Event.Payload).ToString() == hostname)); (EventWrittenEventArgs Event, Guid ActivityId)[] stops = events.Where(e => e.Event.EventName == "ResolutionStop").ToArray(); Assert.Equal(expectedNumber, stops.Length); for (int i = 0; i < starts.Length; i++) { Assert.NotEqual(Guid.Empty, starts[i].ActivityId); Assert.Equal(starts[i].ActivityId, stops[i].ActivityId); } if (shouldHaveFailures) { (EventWrittenEventArgs Event, Guid ActivityId)[] failures = events.Where(e => e.Event.EventName == "ResolutionFailed").ToArray(); Assert.Equal(expectedNumber, failures.Length); for (int i = 0; i < starts.Length; i++) { Assert.Equal(starts[i].ActivityId, failures[i].ActivityId); } } else { Assert.DoesNotContain(events, e => e.Event.EventName == "ResolutionFailed"); } } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public static void ResolutionsWaitingOnQueue_ResolutionStartCalledBeforeEnqueued() { if (PlatformDetection.IsMonoInterpreter && PlatformDetection.IsDebian9) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/56449")] throw new SkipTestException("Test is consistently failing with Mono interpreter"); } // Some platforms (non-Windows) don't have proper support for GetAddrInfoAsync. // Instead we perform async-over-sync with a per-host queue. // This test ensures that ResolutionStart events are written before waiting on the queue. // We do this by blocking the first ResolutionStart event. // If the event was logged after waiting on the queue, the second request would never complete. RemoteExecutor.Invoke(async () => { using var listener = new TestEventListener("System.Net.NameResolution", EventLevel.Informational); listener.AddActivityTracking(); TaskCompletionSource firstResolutionStart = new(TaskCreationOptions.RunContinuationsAsynchronously); TaskCompletionSource secondResolutionStop = new(TaskCreationOptions.RunContinuationsAsynchronously); List<(string EventName, Guid ActivityId)> events = new(); bool? callbackWaitTimedOut = null; await listener.RunWithCallbackAsync(e => { if (e.EventName == "ResolutionStart" || e.EventName == "ResolutionStop") { events.Add((e.EventName, e.ActivityId)); } if (e.EventName == "ResolutionStart" && firstResolutionStart.TrySetResult()) { callbackWaitTimedOut = !secondResolutionStop.Task.Wait(TimeSpan.FromSeconds(15)); } }, async () => { Task first = DoResolutionAsync(); await firstResolutionStart.Task.WaitAsync(TimeSpan.FromSeconds(30)); Task second = DoResolutionAsync(); await Task.WhenAny(first, second).WaitAsync(TimeSpan.FromSeconds(30)); Assert.False(first.IsCompleted); await second; secondResolutionStop.SetResult(); await first.WaitAsync(TimeSpan.FromSeconds(30)); static Task DoResolutionAsync() { return Task.Run(async () => { try { await Dns.GetHostAddressesAsync("microsoft.com"); } catch { } // We don't care if the request failed, just that events were written properly }); } }); Assert.Equal(4, events.Count); Assert.Equal("ResolutionStart", events[0].EventName); Assert.Equal("ResolutionStart", events[1].EventName); Assert.Equal("ResolutionStop", events[2].EventName); Assert.Equal("ResolutionStop", events[3].EventName); Assert.All(events, e => Assert.NotEqual(Guid.Empty, e.ActivityId)); Assert.Equal(events[0].ActivityId, events[3].ActivityId); Assert.Equal(events[1].ActivityId, events[2].ActivityId); Assert.NotEqual(events[0].ActivityId, events[1].ActivityId); Assert.False(callbackWaitTimedOut); }).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.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Linq; using System.Net.Sockets; using System.Threading.Tasks; using Microsoft.DotNet.RemoteExecutor; using Microsoft.DotNet.XUnitExtensions; using Xunit; using Xunit.Sdk; namespace System.Net.NameResolution.Tests { public class TelemetryTest { [Fact] public static void EventSource_ExistsWithCorrectId() { Type esType = typeof(Dns).Assembly.GetType("System.Net.NameResolutionTelemetry", throwOnError: true, ignoreCase: false); Assert.NotNull(esType); Assert.Equal("System.Net.NameResolution", EventSource.GetName(esType)); Assert.Equal(Guid.Parse("4b326142-bfb5-5ed3-8585-7714181d14b0"), EventSource.GetGuid(esType)); Assert.NotEmpty(EventSource.GenerateManifest(esType, esType.Assembly.Location)); } [OuterLoop] [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public static void EventSource_ResolveValidHostName_LogsStartStop() { RemoteExecutor.Invoke(async () => { const string ValidHostName = "microsoft.com"; using var listener = new TestEventListener("System.Net.NameResolution", EventLevel.Informational); listener.AddActivityTracking(); var events = new ConcurrentQueue<(EventWrittenEventArgs Event, Guid ActivityId)>(); await listener.RunWithCallbackAsync(e => events.Enqueue((e, e.ActivityId)), async () => { await Dns.GetHostEntryAsync(ValidHostName); await Dns.GetHostAddressesAsync(ValidHostName); Dns.GetHostEntry(ValidHostName); Dns.GetHostAddresses(ValidHostName); Dns.EndGetHostEntry(Dns.BeginGetHostEntry(ValidHostName, null, null)); Dns.EndGetHostAddresses(Dns.BeginGetHostAddresses(ValidHostName, null, null)); }); VerifyEvents(events, ValidHostName, 6); }).Dispose(); } [OuterLoop] [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public static void EventSource_ResolveInvalidHostName_LogsStartFailureStop() { RemoteExecutor.Invoke(async () => { const string InvalidHostName = "invalid...example.com"; using var listener = new TestEventListener("System.Net.NameResolution", EventLevel.Informational); listener.AddActivityTracking(); var events = new ConcurrentQueue<(EventWrittenEventArgs Event, Guid ActivityId)>(); await listener.RunWithCallbackAsync(e => events.Enqueue((e, e.ActivityId)), async () => { await Assert.ThrowsAnyAsync<SocketException>(async () => await Dns.GetHostEntryAsync(InvalidHostName)); await Assert.ThrowsAnyAsync<SocketException>(async () => await Dns.GetHostAddressesAsync(InvalidHostName)); Assert.ThrowsAny<SocketException>(() => Dns.GetHostEntry(InvalidHostName)); Assert.ThrowsAny<SocketException>(() => Dns.GetHostAddresses(InvalidHostName)); Assert.ThrowsAny<SocketException>(() => Dns.EndGetHostEntry(Dns.BeginGetHostEntry(InvalidHostName, null, null))); Assert.ThrowsAny<SocketException>(() => Dns.EndGetHostAddresses(Dns.BeginGetHostAddresses(InvalidHostName, null, null))); }); VerifyEvents(events, InvalidHostName, 6, shouldHaveFailures: true); }).Dispose(); } [OuterLoop] [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public static void EventSource_GetHostEntryForIP_LogsStartStop() { RemoteExecutor.Invoke(async () => { const string ValidIPAddress = "8.8.4.4"; using var listener = new TestEventListener("System.Net.NameResolution", EventLevel.Informational); listener.AddActivityTracking(); var events = new ConcurrentQueue<(EventWrittenEventArgs Event, Guid ActivityId)>(); await listener.RunWithCallbackAsync(e => events.Enqueue((e, e.ActivityId)), async () => { IPAddress ipAddress = IPAddress.Parse(ValidIPAddress); await Dns.GetHostEntryAsync(ValidIPAddress); await Dns.GetHostEntryAsync(ipAddress); Dns.GetHostEntry(ValidIPAddress); Dns.GetHostEntry(ipAddress); Dns.EndGetHostEntry(Dns.BeginGetHostEntry(ValidIPAddress, null, null)); Dns.EndGetHostEntry(Dns.BeginGetHostEntry(ipAddress, null, null)); }); // Each GetHostEntry over an IP will yield 2 resolutions VerifyEvents(events, ValidIPAddress, 12, isHostEntryForIp: true); }).Dispose(); } private static void VerifyEvents(ConcurrentQueue<(EventWrittenEventArgs Event, Guid ActivityId)> events, string hostname, int expectedNumber, bool shouldHaveFailures = false, bool isHostEntryForIp = false) { Assert.DoesNotContain(events, e => e.Event.EventId == 0); // errors from the EventSource itself (EventWrittenEventArgs Event, Guid ActivityId)[] starts = events.Where(e => e.Event.EventName == "ResolutionStart").ToArray(); Assert.Equal(expectedNumber, starts.Length); int expectedHostnameStarts = isHostEntryForIp ? expectedNumber / 2 : expectedNumber; Assert.Equal(expectedHostnameStarts, starts.Count(s => Assert.Single(s.Event.Payload).ToString() == hostname)); (EventWrittenEventArgs Event, Guid ActivityId)[] stops = events.Where(e => e.Event.EventName == "ResolutionStop").ToArray(); Assert.Equal(expectedNumber, stops.Length); for (int i = 0; i < starts.Length; i++) { Assert.NotEqual(Guid.Empty, starts[i].ActivityId); Assert.Equal(starts[i].ActivityId, stops[i].ActivityId); } if (shouldHaveFailures) { (EventWrittenEventArgs Event, Guid ActivityId)[] failures = events.Where(e => e.Event.EventName == "ResolutionFailed").ToArray(); Assert.Equal(expectedNumber, failures.Length); for (int i = 0; i < starts.Length; i++) { Assert.Equal(starts[i].ActivityId, failures[i].ActivityId); } } else { Assert.DoesNotContain(events, e => e.Event.EventName == "ResolutionFailed"); } } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public static void ResolutionsWaitingOnQueue_ResolutionStartCalledBeforeEnqueued() { if (PlatformDetection.IsMonoInterpreter && PlatformDetection.IsDebian9) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/56449")] throw new SkipTestException("Test is consistently failing with Mono interpreter"); } // Some platforms (non-Windows) don't have proper support for GetAddrInfoAsync. // Instead we perform async-over-sync with a per-host queue. // This test ensures that ResolutionStart events are written before waiting on the queue. // We do this by blocking the first ResolutionStart event. // If the event was logged after waiting on the queue, the second request would never complete. RemoteExecutor.Invoke(async () => { using var listener = new TestEventListener("System.Net.NameResolution", EventLevel.Informational); listener.AddActivityTracking(); TaskCompletionSource firstResolutionStart = new(TaskCreationOptions.RunContinuationsAsynchronously); TaskCompletionSource secondResolutionStop = new(TaskCreationOptions.RunContinuationsAsynchronously); List<(string EventName, Guid ActivityId)> events = new(); bool? callbackWaitTimedOut = null; await listener.RunWithCallbackAsync(e => { if (e.EventName == "ResolutionStart" || e.EventName == "ResolutionStop") { events.Add((e.EventName, e.ActivityId)); } if (e.EventName == "ResolutionStart" && firstResolutionStart.TrySetResult()) { callbackWaitTimedOut = !secondResolutionStop.Task.Wait(TimeSpan.FromSeconds(15)); } }, async () => { Task first = DoResolutionAsync(); await firstResolutionStart.Task.WaitAsync(TimeSpan.FromSeconds(30)); Task second = DoResolutionAsync(); await Task.WhenAny(first, second).WaitAsync(TimeSpan.FromSeconds(30)); Assert.False(first.IsCompleted); await second; secondResolutionStop.SetResult(); await first.WaitAsync(TimeSpan.FromSeconds(30)); static Task DoResolutionAsync() { return Task.Run(async () => { try { await Dns.GetHostAddressesAsync("microsoft.com"); } catch { } // We don't care if the request failed, just that events were written properly }); } }); Assert.Equal(4, events.Count); Assert.Equal("ResolutionStart", events[0].EventName); Assert.Equal("ResolutionStart", events[1].EventName); Assert.Equal("ResolutionStop", events[2].EventName); Assert.Equal("ResolutionStop", events[3].EventName); Assert.All(events, e => Assert.NotEqual(Guid.Empty, e.ActivityId)); Assert.Equal(events[0].ActivityId, events[3].ActivityId); Assert.Equal(events[1].ActivityId, events[2].ActivityId); Assert.NotEqual(events[0].ActivityId, events[1].ActivityId); Assert.False(callbackWaitTimedOut); }).Dispose(); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Management/src/System/Management/ManagementOptions.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.Security; namespace System.Management { /// <summary> /// <para>Describes the authentication level to be used to connect to WMI. This is used for the COM connection to WMI.</para> /// </summary> public enum AuthenticationLevel { /// <summary> /// <para>The default COM authentication level. WMI uses the default Windows Authentication setting.</para> /// </summary> Default = 0, /// <summary> /// <para> No COM authentication.</para> /// </summary> None = 1, /// <summary> /// <para> Connect-level COM authentication.</para> /// </summary> Connect = 2, /// <summary> /// <para> Call-level COM authentication.</para> /// </summary> Call = 3, /// <summary> /// <para> Packet-level COM authentication.</para> /// </summary> Packet = 4, /// <summary> /// <para>Packet Integrity-level COM authentication.</para> /// </summary> PacketIntegrity = 5, /// <summary> /// <para>Packet Privacy-level COM authentication.</para> /// </summary> PacketPrivacy = 6, /// <summary> /// <para>The default COM authentication level. WMI uses the default Windows Authentication setting.</para> /// </summary> Unchanged = -1 } /// <summary> /// <para>Describes the impersonation level to be used to connect to WMI.</para> /// </summary> public enum ImpersonationLevel { /// <summary> /// <para>Default impersonation.</para> /// </summary> Default = 0, /// <summary> /// <para> Anonymous COM impersonation level that hides the /// identity of the caller. Calls to WMI may fail /// with this impersonation level.</para> /// </summary> Anonymous = 1, /// <summary> /// <para> Identify-level COM impersonation level that allows objects /// to query the credentials of the caller. Calls to /// WMI may fail with this impersonation level.</para> /// </summary> Identify = 2, /// <summary> /// <para> Impersonate-level COM impersonation level that allows /// objects to use the credentials of the caller. This is the recommended impersonation level for WMI calls.</para> /// </summary> Impersonate = 3, /// <summary> /// <para> Delegate-level COM impersonation level that allows objects /// to permit other objects to use the credentials of the caller. This /// level, which will work with WMI calls but may constitute an unnecessary /// security risk, is supported only under Windows 2000.</para> /// </summary> Delegate = 4 } /// <summary> /// <para>Describes the possible effects of saving an object to WMI when /// using <see cref='System.Management.ManagementObject.Put()'/>.</para> /// </summary> public enum PutType { /// <summary> /// <para> Invalid Type </para> /// </summary> None = 0, /// <summary> /// <para> Updates an existing object /// only; does not create a new object.</para> /// </summary> UpdateOnly = 1, /// <summary> /// <para> Creates an object only; /// does not update an existing object.</para> /// </summary> CreateOnly = 2, /// <summary> /// <para> Saves the object, whether /// updating an existing object or creating a new object.</para> /// </summary> UpdateOrCreate = 3 } //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> /// Provides an abstract base class for all Options objects.</para> /// <para>Options objects are used to customize different management operations. </para> /// <para>Use one of the Options classes derived from this class, as /// indicated by the signature of the operation being performed.</para> /// </summary> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// [TypeConverter(typeof(ExpandableObjectConverter))] public abstract class ManagementOptions : ICloneable { /// <summary> /// <para> Specifies an infinite timeout.</para> /// </summary> public static readonly TimeSpan InfiniteTimeout = TimeSpan.MaxValue; internal int flags; internal ManagementNamedValueCollection context; internal TimeSpan timeout; //Used when any public property on this object is changed, to signal //to the containing object that it needs to be refreshed. internal event IdentifierChangedEventHandler IdentifierChanged; //Fires IdentifierChanged event internal void FireIdentifierChanged() { if (IdentifierChanged != null) IdentifierChanged(this, null); } //Called when IdentifierChanged() event fires internal void HandleIdentifierChange(object sender, IdentifierChangedEventArgs args) { //Something inside ManagementOptions changed, we need to fire an event //to the parent object FireIdentifierChanged(); } internal int Flags { get { return flags; } set { flags = value; } } /// <summary> /// <para> Gets or sets a WMI context object. This is a /// name-value pairs list to be passed through to a WMI provider that supports /// context information for customized operation.</para> /// </summary> /// <value> /// <para>A name-value pairs list to be passed through to a WMI provider that /// supports context information for customized operation.</para> /// </value> public ManagementNamedValueCollection Context { get { if (context == null) return context = new ManagementNamedValueCollection(); else return context; } set { ManagementNamedValueCollection oldContext = context; if (null != value) context = (ManagementNamedValueCollection)value.Clone(); else context = new ManagementNamedValueCollection(); if (null != oldContext) oldContext.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); //register for change events in this object context.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange); //the context property has changed so act like we fired the event HandleIdentifierChange(this, null); } } /// <summary> /// <para>Gets or sets the timeout to apply to the operation. /// Note that for operations that return collections, this timeout applies to the /// enumeration through the resulting collection, not the operation itself /// (the <see cref='System.Management.EnumerationOptions.ReturnImmediately'/> /// property is used for the latter).</para> /// This property is used to indicate that the operation should be performed semisynchronously. /// </summary> /// <value> /// <para>The default value for this property is <see cref='System.Management.ManagementOptions.InfiniteTimeout'/> /// , which means the operation will block. /// The value specified must be positive.</para> /// </value> public TimeSpan Timeout { get { return timeout; } set { //Timespan allows for negative values, but we want to make sure it's positive here... if (value.Ticks < 0) throw new ArgumentOutOfRangeException(nameof(value)); timeout = value; FireIdentifierChanged(); } } internal ManagementOptions() : this(null, InfiniteTimeout) { } internal ManagementOptions(ManagementNamedValueCollection context, TimeSpan timeout) : this(context, timeout, 0) { } internal ManagementOptions(ManagementNamedValueCollection context, TimeSpan timeout, int flags) { this.flags = flags; if (context != null) this.Context = context; else this.context = null; this.Timeout = timeout; } internal IWbemContext GetContext() { if (context != null) return context.GetContext(); else return null; } // We do not expose this publicly; instead the flag is set automatically // when making an async call if we detect that someone has requested to // listen for status messages. internal bool SendStatus { get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_SEND_STATUS) != 0) ? true : false); } set { Flags = (value == false) ? (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_SEND_STATUS) : (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_SEND_STATUS); } } /// <summary> /// <para> Returns a copy of the object.</para> /// </summary> /// <returns> /// <para>The cloned object.</para> /// </returns> public abstract object Clone(); } //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para>Provides a base class for query and enumeration-related options /// objects.</para> /// <para>Use this class to customize enumeration of management /// objects, traverse management object relationships, or query for /// management objects.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to enumerate all top-level WMI classes /// // and subclasses in root/cimv2 namespace. /// class Sample_EnumerationOptions /// { /// public static int Main(string[] args) { /// ManagementClass newClass = new ManagementClass(); /// EnumerationOptions options = new EnumerationOptions(); /// options.EnumerateDeep = false; /// foreach (ManagementObject o in newClass.GetSubclasses(options)) { /// Console.WriteLine(o["__Class"]); /// } /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example demonstrates how to enumerate all top-level WMI classes /// ' and subclasses in root/cimv2 namespace. /// Class Sample_EnumerationOptions /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim newClass As New ManagementClass() /// Dim options As New EnumerationOptions() /// options.EnumerateDeep = False /// Dim o As ManagementObject /// For Each o In newClass.GetSubclasses(options) /// Console.WriteLine(o("__Class")) /// Next o /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class EnumerationOptions : ManagementOptions { private int blockSize; /// <summary> /// <para>Gets or sets a value indicating whether the invoked operation should be /// performed in a synchronous or semisynchronous fashion. If this property is set /// to <see langword='true'/>, the enumeration is invoked and the call returns immediately. The actual /// retrieval of the results will occur when the resulting collection is walked.</para> /// </summary> /// <value> /// <para><see langword='true'/> if the invoked operation should /// be performed in a synchronous or semisynchronous fashion; otherwise, /// <see langword='false'/>. The default value is <see langword='true'/>.</para> /// </value> public bool ReturnImmediately { get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY) != 0) ? true : false); } set { Flags = (value == false) ? (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY) : (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY); } } /// <summary> /// <para> Gets or sets the block size /// for block operations. When enumerating through a collection, WMI will return results in /// groups of the specified size.</para> /// </summary> /// <value> /// <para>The default value is 1.</para> /// </value> public int BlockSize { get { return blockSize; } set { //Unfortunately BlockSize was defined as int, but valid values are only > 0 if (value <= 0) throw new ArgumentOutOfRangeException(nameof(value)); blockSize = value; } } /// <summary> /// <para>Gets or sets a value indicating whether the collection is assumed to be /// rewindable. If <see langword='true'/>, the objects in the /// collection will be kept available for multiple enumerations. If /// <see langword='false'/>, the collection /// can only be enumerated one time.</para> /// </summary> /// <value> /// <para><see langword='true'/> if the collection is assumed to /// be rewindable; otherwise, <see langword='false'/>. The default value is /// <see langword='true'/>.</para> /// </value> /// <remarks> /// <para>A rewindable collection is more costly in memory /// consumption as all the objects need to be kept available at the same time. /// In a collection defined as non-rewindable, the objects are discarded after being returned /// in the enumeration.</para> /// </remarks> public bool Rewindable { get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_FORWARD_ONLY) != 0) ? false : true); } set { Flags = (value == true) ? (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_FORWARD_ONLY) : (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_FORWARD_ONLY); } } /// <summary> /// <para> Gets or sets a value indicating whether the objects returned from /// WMI should contain amended information. Typically, amended information is localizable /// information attached to the WMI object, such as object and property /// descriptions.</para> /// </summary> /// <value> /// <para><see langword='true'/> if the objects returned from WMI /// should contain amended information; otherwise, <see langword='false'/>. The /// default value is <see langword='false'/>.</para> /// </value> /// <remarks> /// <para>If descriptions and other amended information are not of /// interest, setting this property to <see langword='false'/> /// is more /// efficient.</para> /// </remarks> public bool UseAmendedQualifiers { get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) != 0) ? true : false); } set { Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) : (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS); } } /// <summary> /// <para>Gets or sets a value indicating whether to the objects returned should have /// locatable information in them. This ensures that the system properties, such as /// <see langword='__PATH'/>, <see langword='__RELPATH'/>, and /// <see langword='__SERVER'/>, are non-NULL. This flag can only be used in queries, /// and is ignored in enumerations.</para> /// </summary> /// <value> /// <para><see langword='true'/> if WMI /// should ensure all returned objects have valid paths; otherwise, /// <see langword='false'/>. The default value is <see langword='false'/>.</para> /// </value> public bool EnsureLocatable { get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_ENSURE_LOCATABLE) != 0) ? true : false); } set { Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_ENSURE_LOCATABLE) : (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_ENSURE_LOCATABLE); } } /// <summary> /// <para>Gets or sets a value indicating whether the query should return a /// prototype of the result set instead of the actual results. This flag is used for /// prototyping.</para> /// </summary> /// <value> /// <para><see langword='true'/> if the /// query should return a prototype of the result set instead of the actual results; /// otherwise, <see langword='false'/>. The default value is /// <see langword='false'/>.</para> /// </value> public bool PrototypeOnly { get { return (((Flags & (int)tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_PROTOTYPE) != 0) ? true : false); } set { Flags = (value == true) ? (Flags | (int)tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_PROTOTYPE) : (Flags & (int)~tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_PROTOTYPE); } } /// <summary> /// <para> Gets or sets a value indicating whether direct access to the WMI provider is requested for the specified class, /// without any regard to its base class or derived classes.</para> /// </summary> /// <value> /// <para><see langword='true'/> if only /// objects of the specified class should be received, without regard to derivation /// or inheritance; otherwise, <see langword='false'/>. The default value is /// <see langword='false'/>. </para> /// </value> public bool DirectRead { get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_DIRECT_READ) != 0) ? true : false); } set { Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_DIRECT_READ) : (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_DIRECT_READ); } } /// <summary> /// <para> Gets or sets a value indicating whether recursive enumeration is requested /// into all classes derived from the specified base class. If /// <see langword='false'/>, only immediate derived /// class members are returned.</para> /// </summary> /// <value> /// <para><see langword='true'/> if recursive enumeration is requested /// into all classes derived from the specified base class; otherwise, /// <see langword='false'/>. The default value is <see langword='false'/>.</para> /// </value> public bool EnumerateDeep { get { return (((Flags & (int)tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_SHALLOW) != 0) ? false : true); } set { Flags = (value == false) ? (Flags | (int)tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_SHALLOW) : (Flags & (int)~tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_SHALLOW); } } //default constructor /// <overload> /// Initializes a new instance /// of the <see cref='System.Management.EnumerationOptions'/> class. /// </overload> /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.EnumerationOptions'/> /// class with default values (see the individual property descriptions /// for what the default values are). This is the default constructor. </para> /// </summary> public EnumerationOptions() : this(null, InfiniteTimeout, 1, true, true, false, false, false, false, false) { } //Constructor that specifies flags as individual values - we need to set the flags accordingly ! /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.EnumerationOptions'/> class to be used for queries or enumerations, /// allowing the user to specify values for the different options.</para> /// </summary> /// <param name='context'>The options context object containing provider-specific information that can be passed through to the provider.</param> /// <param name=' timeout'>The timeout value for enumerating through the results.</param> /// <param name=' blockSize'>The number of items to retrieve at one time from WMI.</param> /// <param name=' rewindable'><see langword='true'/> to specify whether the result set is rewindable (=allows multiple traversal or one-time); otherwise, <see langword='false'/>.</param> /// <param name=' returnImmediatley'><see langword='true'/> to specify whether the operation should return immediately (semi-sync) or block until all results are available; otherwise, <see langword='false'/> .</param> /// <param name=' useAmendedQualifiers'><see langword='true'/> to specify whether the returned objects should contain amended (locale-aware) qualifiers; otherwise, <see langword='false'/> .</param> /// <param name=' ensureLocatable'><see langword='true'/> to specify to WMI that it should ensure all returned objects have valid paths; otherwise, <see langword='false'/> .</param> /// <param name=' prototypeOnly'><see langword='true'/> to return a prototype of the result set instead of the actual results; otherwise, <see langword='false'/> .</param> /// <param name=' directRead'><see langword='true'/> to retrieve objects of only the specified class only or from derived classes as well; otherwise, <see langword='false'/> .</param> /// <param name=' enumerateDeep'><see langword='true'/> to specify recursive enumeration in subclasses; otherwise, <see langword='false'/> .</param> public EnumerationOptions( ManagementNamedValueCollection context, TimeSpan timeout, int blockSize, bool rewindable, bool returnImmediatley, bool useAmendedQualifiers, bool ensureLocatable, bool prototypeOnly, bool directRead, bool enumerateDeep) : base(context, timeout) { BlockSize = blockSize; Rewindable = rewindable; ReturnImmediately = returnImmediatley; UseAmendedQualifiers = useAmendedQualifiers; EnsureLocatable = ensureLocatable; PrototypeOnly = prototypeOnly; DirectRead = directRead; EnumerateDeep = enumerateDeep; } /// <summary> /// <para> Returns a copy of the object.</para> /// </summary> /// <returns> /// <para>The cloned object.</para> /// </returns> public override object Clone() { ManagementNamedValueCollection newContext = null; if (null != Context) newContext = (ManagementNamedValueCollection)Context.Clone(); return new EnumerationOptions(newContext, Timeout, blockSize, Rewindable, ReturnImmediately, UseAmendedQualifiers, EnsureLocatable, PrototypeOnly, DirectRead, EnumerateDeep); } }//EnumerationOptions //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Specifies options for management event watching.</para> /// <para>Use this class to customize subscriptions for watching management events. </para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to listen to an event using ManagementEventWatcher object. /// class Sample_EventWatcherOptions /// { /// public static int Main(string[] args) { /// ManagementClass newClass = new ManagementClass(); /// newClass["__CLASS"] = "TestDeletionClass"; /// newClass.Put(); /// /// EventWatcherOptions options = new EventWatcherOptions(); /// ManagementEventWatcher watcher = new ManagementEventWatcher(null, /// new WqlEventQuery("__classdeletionevent"), /// options); /// MyHandler handler = new MyHandler(); /// watcher.EventArrived += new EventArrivedEventHandler(handler.Arrived); /// watcher.Start(); /// /// // Delete class to trigger event /// newClass.Delete(); /// /// //For the purpose of this example, we will wait /// // two seconds before main thread terminates. /// System.Threading.Thread.Sleep(2000); /// /// watcher.Stop(); /// /// return 0; /// } /// /// public class MyHandler /// { /// public void Arrived(object sender, EventArrivedEventArgs e) { /// Console.WriteLine("Class Deleted= " + /// ((ManagementBaseObject)e.NewEvent["TargetClass"])["__CLASS"]); /// } /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example demonstrates how to listen to an event using the ManagementEventWatcher object. /// Class Sample_EventWatcherOptions /// Public Shared Sub Main() /// Dim newClass As New ManagementClass() /// newClass("__CLASS") = "TestDeletionClass" /// newClass.Put() /// /// Dim options As _ /// New EventWatcherOptions() /// Dim watcher As New ManagementEventWatcher( _ /// Nothing, _ /// New WqlEventQuery("__classdeletionevent"), _ /// options) /// Dim handler As New MyHandler() /// AddHandler watcher.EventArrived, AddressOf handler.Arrived /// watcher.Start() /// /// ' Delete class to trigger event /// newClass.Delete() /// /// ' For the purpose of this example, we will wait /// ' two seconds before main thread terminates. /// System.Threading.Thread.Sleep(2000) /// watcher.Stop() /// End Sub /// /// Public Class MyHandler /// Public Sub Arrived(sender As Object, e As EventArrivedEventArgs) /// Console.WriteLine("Class Deleted = " &amp; _ /// CType(e.NewEvent("TargetClass"), ManagementBaseObject)("__CLASS")) /// End Sub /// End Class /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class EventWatcherOptions : ManagementOptions { private int blockSize = 1; /// <summary> /// <para>Gets or sets the block size for block operations. When waiting for events, this /// value specifies how many events to wait for before returning.</para> /// </summary> /// <value> /// <para>The default value is 1.</para> /// </value> public int BlockSize { get { return blockSize; } set { blockSize = value; FireIdentifierChanged(); } } /// <overload> /// <para>Initializes a new instance of the <see cref='System.Management.EventWatcherOptions'/> class. </para> /// </overload> /// <summary> /// <para> Initializes a new instance of the <see cref='System.Management.EventWatcherOptions'/> class for event watching, using default values. /// This is the default constructor.</para> /// </summary> public EventWatcherOptions() : this(null, InfiniteTimeout, 1) { } /// <summary> /// <para> Initializes a new instance of the <see cref='System.Management.EventWatcherOptions'/> class with the given /// values.</para> /// </summary> /// <param name='context'>The options context object containing provider-specific information to be passed through to the provider. </param> /// <param name=' timeout'>The timeout to wait for the next events.</param> /// <param name=' blockSize'>The number of events to wait for in each block.</param> public EventWatcherOptions(ManagementNamedValueCollection context, TimeSpan timeout, int blockSize) : base(context, timeout) { Flags = (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_FORWARD_ONLY; BlockSize = blockSize; } /// <summary> /// <para> Returns a copy of the object.</para> /// </summary> /// <returns> /// The cloned object. /// </returns> public override object Clone() { ManagementNamedValueCollection newContext = null; if (null != Context) newContext = (ManagementNamedValueCollection)Context.Clone(); return new EventWatcherOptions(newContext, Timeout, blockSize); } }//EventWatcherOptions //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Specifies options for getting a management object.</para> /// Use this class to customize retrieval of a management object. /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to set a timeout value and list /// // all amended qualifiers in a ManagementClass object. /// class Sample_ObjectGetOptions /// { /// public static int Main(string[] args) { /// // Request amended qualifiers /// ObjectGetOptions options = /// new ObjectGetOptions(null, new TimeSpan(0,0,0,5), true); /// ManagementClass diskClass = /// new ManagementClass("root/cimv2", "Win32_Process", options); /// foreach (QualifierData qualifier in diskClass.Qualifiers) { /// Console.WriteLine(qualifier.Name + ":" + qualifier.Value); /// } /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example demonstrates how to set a timeout value and list /// ' all amended qualifiers in a ManagementClass object. /// Class Sample_ObjectGetOptions /// Overloads Public Shared Function Main(args() As String) As Integer /// ' Request amended qualifiers /// Dim options As _ /// New ObjectGetOptions(Nothing, New TimeSpan(0, 0, 0, 5), True) /// Dim diskClass As New ManagementClass( _ /// "root/cimv2", _ /// "Win32_Process", _ /// options) /// Dim qualifier As QualifierData /// For Each qualifier In diskClass.Qualifiers /// Console.WriteLine(qualifier.Name &amp; ":" &amp; qualifier.Value) /// Next qualifier /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class ObjectGetOptions : ManagementOptions { internal static ObjectGetOptions _Clone(ObjectGetOptions options) { return ObjectGetOptions._Clone(options, null); } internal static ObjectGetOptions _Clone(ObjectGetOptions options, IdentifierChangedEventHandler handler) { ObjectGetOptions optionsTmp; if (options != null) optionsTmp = new ObjectGetOptions(options.context, options.timeout, options.UseAmendedQualifiers); else optionsTmp = new ObjectGetOptions(); // Wire up change handler chain. Use supplied handler, if specified; // otherwise, default to that of the path argument. if (handler != null) optionsTmp.IdentifierChanged += handler; else if (options != null) optionsTmp.IdentifierChanged += new IdentifierChangedEventHandler(options.HandleIdentifierChange); return optionsTmp; } /// <summary> /// <para> Gets or sets a value indicating whether the objects returned from WMI should /// contain amended information. Typically, amended information is localizable information /// attached to the WMI object, such as object and property descriptions.</para> /// </summary> /// <value> /// <para><see langword='true'/> if the objects returned from WMI /// should contain amended information; otherwise, <see langword='false'/>. The /// default value is <see langword='false'/>.</para> /// </value> public bool UseAmendedQualifiers { get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) != 0) ? true : false); } set { Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) : (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS); FireIdentifierChanged(); } } /// <overload> /// <para>Initializes a new instance of the <see cref='System.Management.ObjectGetOptions'/> class.</para> /// </overload> /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ObjectGetOptions'/> class for getting a WMI object, using /// default values. This is the default constructor.</para> /// </summary> public ObjectGetOptions() : this(null, InfiniteTimeout, false) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ObjectGetOptions'/> class for getting a WMI object, using the /// specified provider-specific context.</para> /// </summary> /// <param name='context'>A provider-specific, named-value pairs context object to be passed through to the provider.</param> public ObjectGetOptions(ManagementNamedValueCollection context) : this(context, InfiniteTimeout, false) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ObjectGetOptions'/> class for getting a WMI object, /// using the given options values.</para> /// </summary> /// <param name='context'>A provider-specific, named-value pairs context object to be passed through to the provider.</param> /// <param name=' timeout'>The length of time to let the operation perform before it times out. The default is <see cref='System.Management.ManagementOptions.InfiniteTimeout'/> .</param> /// <param name=' useAmendedQualifiers'><see langword='true'/> if the returned objects should contain amended (locale-aware) qualifiers; otherwise, <see langword='false'/>. </param> public ObjectGetOptions(ManagementNamedValueCollection context, TimeSpan timeout, bool useAmendedQualifiers) : base(context, timeout) { UseAmendedQualifiers = useAmendedQualifiers; } /// <summary> /// <para> Returns a copy of the object.</para> /// </summary> /// <returns> /// <para>The cloned object.</para> /// </returns> public override object Clone() { ManagementNamedValueCollection newContext = null; if (null != Context) newContext = (ManagementNamedValueCollection)Context.Clone(); return new ObjectGetOptions(newContext, Timeout, UseAmendedQualifiers); } } //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Specifies options for committing management /// object changes.</para> /// <para>Use this class to customize how values are saved to a management object.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to specify a PutOptions using /// // PutOptions object when saving a ManagementClass object to /// // the WMI respository. /// class Sample_PutOptions /// { /// public static int Main(string[] args) { /// ManagementClass newClass = new ManagementClass("root/default", /// String.Empty, /// null); /// newClass["__Class"] = "class999xc"; /// /// PutOptions options = new PutOptions(); /// options.Type = PutType.UpdateOnly; /// /// try /// { /// newClass.Put(options); //will fail if the class doesn't already exist /// } /// catch (ManagementException e) /// { /// Console.WriteLine("Couldn't update class: " + e.ErrorCode); /// } /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example demonstrates how to specify a PutOptions using /// ' PutOptions object when saving a ManagementClass object to /// ' WMI respository. /// Class Sample_PutOptions /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim newClass As New ManagementClass( _ /// "root/default", _ /// String.Empty, _ /// Nothing) /// newClass("__Class") = "class999xc" /// /// Dim options As New PutOptions() /// options.Type = PutType.UpdateOnly 'will fail if the class doesn't already exist /// /// Try /// newClass.Put(options) /// Catch e As ManagementException /// Console.WriteLine("Couldn't update class: " &amp; e.ErrorCode) /// End Try /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class PutOptions : ManagementOptions { /// <summary> /// <para> Gets or sets a value indicating whether the objects returned from WMI should /// contain amended information. Typically, amended information is localizable information /// attached to the WMI object, such as object and property descriptions.</para> /// </summary> /// <value> /// <para><see langword='true'/> if the objects returned from WMI /// should contain amended information; otherwise, <see langword='false'/>. The /// default value is <see langword='false'/>.</para> /// </value> public bool UseAmendedQualifiers { get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) != 0) ? true : false); } set { Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) : (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS); } } /// <summary> /// <para>Gets or sets the type of commit to be performed for the object.</para> /// </summary> /// <value> /// <para>The default value is <see cref='System.Management.PutType.UpdateOrCreate'/>.</para> /// </value> public PutType Type { get { return (((Flags & (int)tag_WBEM_CHANGE_FLAG_TYPE.WBEM_FLAG_UPDATE_ONLY) != 0) ? PutType.UpdateOnly : ((Flags & (int)tag_WBEM_CHANGE_FLAG_TYPE.WBEM_FLAG_CREATE_ONLY) != 0) ? PutType.CreateOnly : PutType.UpdateOrCreate); } set { Flags |= value switch { PutType.UpdateOnly => (int)tag_WBEM_CHANGE_FLAG_TYPE.WBEM_FLAG_UPDATE_ONLY, PutType.CreateOnly => (int)tag_WBEM_CHANGE_FLAG_TYPE.WBEM_FLAG_CREATE_ONLY, PutType.UpdateOrCreate => (int)tag_WBEM_CHANGE_FLAG_TYPE.WBEM_FLAG_CREATE_OR_UPDATE, _ => throw new ArgumentException(null, nameof(Type)), }; } } /// <overload> /// <para> Initializes a new instance of the <see cref='System.Management.PutOptions'/> class.</para> /// </overload> /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.PutOptions'/> class for put operations, using default values. /// This is the default constructor.</para> /// </summary> public PutOptions() : this(null, InfiniteTimeout, false, PutType.UpdateOrCreate) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.PutOptions'/> class for committing a WMI object, using the /// specified provider-specific context.</para> /// </summary> /// <param name='context'>A provider-specific, named-value pairs context object to be passed through to the provider.</param> public PutOptions(ManagementNamedValueCollection context) : this(context, InfiniteTimeout, false, PutType.UpdateOrCreate) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.PutOptions'/> class for committing a WMI object, using /// the specified option values.</para> /// </summary> /// <param name='context'>A provider-specific, named-value pairs object to be passed through to the provider. </param> /// <param name=' timeout'>The length of time to let the operation perform before it times out. The default is <see cref='System.Management.ManagementOptions.InfiniteTimeout'/> .</param> /// <param name=' useAmendedQualifiers'><see langword='true'/> if the returned objects should contain amended (locale-aware) qualifiers; otherwise, <see langword='false'/>. </param> /// <param name=' putType'> The type of commit to be performed (update or create).</param> public PutOptions(ManagementNamedValueCollection context, TimeSpan timeout, bool useAmendedQualifiers, PutType putType) : base(context, timeout) { UseAmendedQualifiers = useAmendedQualifiers; Type = putType; } /// <summary> /// <para> Returns a copy of the object.</para> /// </summary> /// <returns> /// <para>The cloned object.</para> /// </returns> public override object Clone() { ManagementNamedValueCollection newContext = null; if (null != Context) newContext = (ManagementNamedValueCollection)Context.Clone(); return new PutOptions(newContext, Timeout, UseAmendedQualifiers, Type); } } //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Specifies options for deleting a management /// object.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to specify a timeout value /// // when deleting a ManagementClass object. /// class Sample_DeleteOptions /// { /// public static int Main(string[] args) { /// ManagementClass newClass = new ManagementClass(); /// newClass["__CLASS"] = "ClassToDelete"; /// newClass.Put(); /// /// // Set deletion options: delete operation timeout value /// DeleteOptions opt = new DeleteOptions(null, new TimeSpan(0,0,0,5)); /// /// ManagementClass dummyClassToDelete = /// new ManagementClass("ClassToDelete"); /// dummyClassToDelete.Delete(opt); /// /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This sample demonstrates how to specify a timeout value /// ' when deleting a ManagementClass object. /// Class Sample_DeleteOptions /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim newClass As New ManagementClass() /// newClass("__CLASS") = "ClassToDelete" /// newClass.Put() /// /// ' Set deletion options: delete operation timeout value /// Dim opt As New DeleteOptions(Nothing, New TimeSpan(0, 0, 0, 5)) /// /// Dim dummyClassToDelete As New ManagementClass("ClassToDelete") /// dummyClassToDelete.Delete(opt) /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class DeleteOptions : ManagementOptions { /// <overload> /// <para>Initializes a new instance of the <see cref='System.Management.DeleteOptions'/> class.</para> /// </overload> /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.DeleteOptions'/> class for the delete operation, using default values. /// This is the default constructor.</para> /// </summary> public DeleteOptions() : base() { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.DeleteOptions'/> class for a delete operation, using /// the specified values.</para> /// </summary> /// <param name='context'>A provider-specific, named-value pairs object to be passed through to the provider. </param> /// <param name='timeout'>The length of time to let the operation perform before it times out. The default value is <see cref='System.Management.ManagementOptions.InfiniteTimeout'/> . Setting this parameter will invoke the operation semisynchronously.</param> public DeleteOptions(ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout) { } /// <summary> /// <para> Returns a copy of the object.</para> /// </summary> /// <returns> /// <para>A cloned object.</para> /// </returns> public override object Clone() { ManagementNamedValueCollection newContext = null; if (null != Context) newContext = (ManagementNamedValueCollection)Context.Clone(); return new DeleteOptions(newContext, Timeout); } } //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Specifies options for invoking a management method.</para> /// <para>Use this class to customize the execution of a method on a management /// object.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to stop a system service. /// class Sample_InvokeMethodOptions /// { /// public static int Main(string[] args) { /// ManagementObject service = /// new ManagementObject("win32_service=\"winmgmt\""); /// InvokeMethodOptions options = new InvokeMethodOptions(); /// options.Timeout = new TimeSpan(0,0,0,5); /// /// ManagementBaseObject outParams = service.InvokeMethod("StopService", null, options); /// /// Console.WriteLine("Return Status = " + outParams["ReturnValue"]); /// /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This sample demonstrates how to stop a system service. /// Class Sample_InvokeMethodOptions /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim service As New ManagementObject("win32_service=""winmgmt""") /// Dim options As New InvokeMethodOptions() /// options.Timeout = New TimeSpan(0, 0, 0, 5) /// /// Dim outParams As ManagementBaseObject = service.InvokeMethod( _ /// "StopService", _ /// Nothing, _ /// options) /// /// Console.WriteLine("Return Status = " &amp; _ /// outParams("ReturnValue").ToString()) /// /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class InvokeMethodOptions : ManagementOptions { /// <overload> /// <para>Initializes a new instance of the <see cref='System.Management.InvokeMethodOptions'/> class.</para> /// </overload> /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.InvokeMethodOptions'/> class for the <see cref='System.Management.ManagementObject.InvokeMethod(string, ManagementBaseObject, InvokeMethodOptions) '/> operation, using default values. /// This is the default constructor.</para> /// </summary> public InvokeMethodOptions() : base() { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.InvokeMethodOptions'/> class for an invoke operation using /// the specified values.</para> /// </summary> /// <param name=' context'>A provider-specific, named-value pairs object to be passed through to the provider. </param> /// <param name='timeout'>The length of time to let the operation perform before it times out. The default value is <see cref='System.Management.ManagementOptions.InfiniteTimeout'/> . Setting this parameter will invoke the operation semisynchronously.</param> public InvokeMethodOptions(ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout) { } /// <summary> /// <para> Returns a copy of the object.</para> /// </summary> /// <returns> /// <para>The cloned object.</para> /// </returns> public override object Clone() { ManagementNamedValueCollection newContext = null; if (null != Context) newContext = (ManagementNamedValueCollection)Context.Clone(); return new InvokeMethodOptions(newContext, Timeout); } } //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Specifies all settings required to make a WMI connection.</para> /// <para>Use this class to customize a connection to WMI made via a /// ManagementScope object.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to connect to remote machine /// // using supplied credentials. /// class Sample_ConnectionOptions /// { /// public static int Main(string[] args) { /// ConnectionOptions options = new ConnectionOptions(); /// options.Username = "domain\\username"; /// options.Password = "password"; /// ManagementScope scope = new ManagementScope( /// "\\\\servername\\root\\cimv2", /// options); /// try { /// scope.Connect(); /// ManagementObject disk = new ManagementObject( /// scope, /// new ManagementPath("Win32_logicaldisk='c:'"), /// null); /// disk.Get(); /// } /// catch (Exception e) { /// Console.WriteLine("Failed to connect: " + e.Message); /// } /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example demonstrates how to connect to remote machine /// ' using supplied credentials. /// Class Sample_ConnectionOptions /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim options As New ConnectionOptions() /// options.Username = "domain\username" /// options.Password = "password" /// Dim scope As New ManagementScope("\\servername\root\cimv2", options) /// Try /// scope.Connect() /// Dim disk As New ManagementObject(scope, _ /// New ManagementPath("Win32_logicaldisk='c:'"), Nothing) /// disk.Get() /// Catch e As UnauthorizedAccessException /// Console.WriteLine(("Failed to connect: " + e.Message)) /// End Try /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class ConnectionOptions : ManagementOptions { internal const string DEFAULTLOCALE = null; internal const string DEFAULTAUTHORITY = null; internal const ImpersonationLevel DEFAULTIMPERSONATION = ImpersonationLevel.Impersonate; internal const AuthenticationLevel DEFAULTAUTHENTICATION = AuthenticationLevel.Unchanged; internal const bool DEFAULTENABLEPRIVILEGES = false; //Fields private string locale; private string username; private SecureString securePassword; private string authority; private ImpersonationLevel impersonation; private AuthenticationLevel authentication; private bool enablePrivileges; // //Properties // /// <summary> /// <para>Gets or sets the locale to be used for the connection operation.</para> /// </summary> /// <value> /// <para>The default value is DEFAULTLOCALE.</para> /// </value> public string Locale { get { return (null != locale) ? locale : string.Empty; } set { if (locale != value) { locale = value; FireIdentifierChanged(); } } } /// <summary> /// <para>Gets or sets the user name to be used for the connection operation.</para> /// </summary> /// <value> /// <para>Null if the connection will use the currently logged-on user; otherwise, a string representing the user name. The default value is null.</para> /// </value> /// <remarks> /// <para>If the user name is from a domain other than the current /// domain, the string may contain the domain name and user name, separated by a backslash:</para> /// <c> /// <para>string username = "EnterDomainHere\\EnterUsernameHere";</para> /// </c> /// </remarks> public string Username { get { return username; } set { if (username != value) { username = value; FireIdentifierChanged(); } } } /// <summary> /// <para>Sets the password for the specified user. The value can be set, but not retrieved.</para> /// </summary> /// <value> /// <para> The default value is null. If the user name is also /// null, the credentials used will be those of the currently logged-on user.</para> /// </value> /// <remarks> /// <para> A blank string ("") specifies a valid /// zero-length password.</para> /// </remarks> public string Password { set { if (value != null) { if (securePassword == null) { securePassword = new SecureString(); for (int i = 0; i < value.Length; i++) { securePassword.AppendChar(value[i]); } } else { SecureString tempStr = new SecureString(); for (int i = 0; i < value.Length; i++) { tempStr.AppendChar(value[i]); } securePassword.Clear(); securePassword = tempStr.Copy(); FireIdentifierChanged(); tempStr.Dispose(); } } else { if (securePassword != null) { securePassword.Dispose(); securePassword = null; FireIdentifierChanged(); } } } } /// <summary> /// <para>Sets the secure password for the specified user. The value can be set, but not retrieved.</para> /// </summary> /// <value> /// <para> The default value is null. If the user name is also /// null, the credentials used will be those of the currently logged-on user.</para> /// </value> /// <remarks> /// <para> A blank securestring ("") specifies a valid /// zero-length password.</para> /// </remarks> public SecureString SecurePassword { set { if (value != null) { if (securePassword == null) { securePassword = value.Copy(); } else { securePassword.Clear(); securePassword = value.Copy(); FireIdentifierChanged(); } } else { if (securePassword != null) { securePassword.Dispose(); securePassword = null; FireIdentifierChanged(); } } } } /// <summary> /// <para>Gets or sets the authority to be used to authenticate the specified user.</para> /// </summary> /// <value> /// <para>If not null, this property can contain the name of the /// Windows NT/Windows 2000 domain in which to obtain the user to /// authenticate.</para> /// </value> /// <remarks> /// <para> /// The property must be passed /// as follows: If it begins with the string "Kerberos:", Kerberos /// authentication will be used and this property should contain a Kerberos principal name. For /// example, Kerberos:&lt;principal name&gt;.</para> /// <para>If the property value begins with the string "NTLMDOMAIN:", NTLM /// authentication will be used and the property should contain a NTLM domain name. /// For example, NTLMDOMAIN:&lt;domain name&gt;. </para> /// <para>If the property is null, NTLM authentication will be used and the NTLM domain /// of the current user will be used.</para> /// </remarks> public string Authority { get { return (null != authority) ? authority : string.Empty; } set { if (authority != value) { authority = value; FireIdentifierChanged(); } } } /// <summary> /// <para>Gets or sets the COM impersonation level to be used for operations in this connection.</para> /// </summary> /// <value> /// <para>The COM impersonation level to be used for operations in /// this connection. The default value is <see cref='System.Management.ImpersonationLevel.Impersonate' qualify='true'/>, which indicates that the WMI provider can /// impersonate the client when performing the requested operations in this connection.</para> /// </value> /// <remarks> /// <para>The <see cref='System.Management.ImpersonationLevel.Impersonate' qualify='true'/> setting is advantageous when the provider is /// a trusted application or service. It eliminates the need for the provider to /// perform client identity and access checks for the requested operations. However, /// note that if for some reason the provider cannot be trusted, allowing it to /// impersonate the client may constitute a security threat. In such cases, it is /// recommended that this property be set by the client to a lower value, such as /// <see cref='System.Management.ImpersonationLevel. Identify' qualify='true'/>. Note that this may cause failure of the /// provider to perform the requested operations, for lack of sufficient permissions /// or inability to perform access checks.</para> /// </remarks> public ImpersonationLevel Impersonation { get { return impersonation; } set { if (impersonation != value) { impersonation = value; FireIdentifierChanged(); } } } /// <summary> /// <para>Gets or sets the COM authentication level to be used for operations in this connection.</para> /// </summary> /// <value> /// <para>The COM authentication level to be used for operations /// in this connection. The default value is <see cref='System.Management.AuthenticationLevel.Unchanged' qualify='true'/>, which indicates that the /// client will use the authentication level requested by the server, according to /// the standard DCOM negotiation process.</para> /// </value> /// <remarks> /// <para>On Windows 2000 and below, the WMI service will request /// Connect level authentication, while on Windows XP and higher it will request /// Packet level authentication. If the client requires a specific authentication /// setting, this property can be used to control the authentication level on this /// particular connection. For example, the property can be set to <see cref='System.Management.AuthenticationLevel.PacketPrivacy' qualify='true'/> /// if the /// client requires all communication to be encrypted.</para> /// </remarks> public AuthenticationLevel Authentication { get { return authentication; } set { if (authentication != value) { authentication = value; FireIdentifierChanged(); } } } /// <summary> /// <para>Gets or sets a value indicating whether user privileges need to be enabled for /// the connection operation. This property should only be used when the operation /// performed requires a certain user privilege to be enabled /// (for example, a machine reboot).</para> /// </summary> /// <value> /// <para><see langword='true'/> if user privileges need to be /// enabled for the connection operation; otherwise, <see langword='false'/>. The /// default value is <see langword='false'/>.</para> /// </value> public bool EnablePrivileges { get { return enablePrivileges; } set { if (enablePrivileges != value) { enablePrivileges = value; FireIdentifierChanged(); } } } // //Constructors // //default /// <overload> /// <para>Initializes a new instance of the <see cref='System.Management.ConnectionOptions'/> class.</para> /// </overload> /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ConnectionOptions'/> class for the connection operation, using default values. This is the /// default constructor.</para> /// </summary> public ConnectionOptions() : this(DEFAULTLOCALE, null, (string)null, DEFAULTAUTHORITY, DEFAULTIMPERSONATION, DEFAULTAUTHENTICATION, DEFAULTENABLEPRIVILEGES, null, InfiniteTimeout) { } //parameterized /// <summary> /// <para> Initializes a new instance of the <see cref='System.Management.ConnectionOptions'/> class to be used for a WMI /// connection, using the specified values.</para> /// </summary> /// <param name='locale'>The locale to be used for the connection.</param> /// <param name=' username'>The user name to be used for the connection. If null, the credentials of the currently logged-on user are used.</param> /// <param name=' password'>The password for the given user name. If the user name is also null, the credentials used will be those of the currently logged-on user.</param> /// <param name=' authority'><para>The authority to be used to authenticate the specified user.</para></param> /// <param name=' impersonation'>The COM impersonation level to be used for the connection.</param> /// <param name=' authentication'>The COM authentication level to be used for the connection.</param> /// <param name=' enablePrivileges'><see langword='true'/>to enable special user privileges; otherwise, <see langword='false'/> . This parameter should only be used when performing an operation that requires special Windows NT user privileges.</param> /// <param name=' context'>A provider-specific, named value pairs object to be passed through to the provider.</param> /// <param name=' timeout'>Reserved for future use.</param> public ConnectionOptions(string locale, string username, string password, string authority, ImpersonationLevel impersonation, AuthenticationLevel authentication, bool enablePrivileges, ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout) { if (locale != null) this.locale = locale; this.username = username; this.enablePrivileges = enablePrivileges; if (password != null) { this.securePassword = new SecureString(); for (int i = 0; i < password.Length; i++) { securePassword.AppendChar(password[i]); } } if (authority != null) this.authority = authority; if (impersonation != 0) this.impersonation = impersonation; if (authentication != 0) this.authentication = authentication; } //parameterized /// <summary> /// <para> Initializes a new instance of the <see cref='System.Management.ConnectionOptions'/> class to be used for a WMI /// connection, using the specified values.</para> /// </summary> /// <param name='locale'>The locale to be used for the connection.</param> /// <param name='username'>The user name to be used for the connection. If null, the credentials of the currently logged-on user are used.</param> /// <param name='password'>The secure password for the given user name. If the user name is also null, the credentials used will be those of the currently logged-on user.</param> /// <param name='authority'><para>The authority to be used to authenticate the specified user.</para></param> /// <param name='impersonation'>The COM impersonation level to be used for the connection.</param> /// <param name='authentication'>The COM authentication level to be used for the connection.</param> /// <param name='enablePrivileges'><see langword='true'/>to enable special user privileges; otherwise, <see langword='false'/> . This parameter should only be used when performing an operation that requires special Windows NT user privileges.</param> /// <param name='context'>A provider-specific, named value pairs object to be passed through to the provider.</param> /// <param name='timeout'>Reserved for future use.</param> public ConnectionOptions(string locale, string username, SecureString password, string authority, ImpersonationLevel impersonation, AuthenticationLevel authentication, bool enablePrivileges, ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout) { if (locale != null) this.locale = locale; this.username = username; this.enablePrivileges = enablePrivileges; if (password != null) { this.securePassword = password.Copy(); } if (authority != null) this.authority = authority; if (impersonation != 0) this.impersonation = impersonation; if (authentication != 0) this.authentication = authentication; } /// <summary> /// <para> Returns a copy of the object.</para> /// </summary> /// <returns> /// <para>The cloned object.</para> /// </returns> public override object Clone() { ManagementNamedValueCollection newContext = null; if (null != Context) newContext = (ManagementNamedValueCollection)Context.Clone(); return new ConnectionOptions(locale, username, GetSecurePassword(), authority, impersonation, authentication, enablePrivileges, newContext, Timeout); } // //Methods // internal IntPtr GetPassword() { if (securePassword != null) { try { return System.Runtime.InteropServices.Marshal.SecureStringToBSTR(securePassword); } catch (OutOfMemoryException) { return IntPtr.Zero; } } else return IntPtr.Zero; } internal SecureString GetSecurePassword() { if (securePassword != null) return securePassword.Copy(); else return null; } internal ConnectionOptions(ManagementNamedValueCollection context, TimeSpan timeout, int flags) : base(context, timeout, flags) { } internal ConnectionOptions(ManagementNamedValueCollection context) : base(context, InfiniteTimeout) { } internal static ConnectionOptions _Clone(ConnectionOptions options) { return ConnectionOptions._Clone(options, null); } internal static ConnectionOptions _Clone(ConnectionOptions options, IdentifierChangedEventHandler handler) { ConnectionOptions optionsTmp; if (options != null) { optionsTmp = new ConnectionOptions(options.Context, options.Timeout, options.Flags); optionsTmp.locale = options.locale; optionsTmp.username = options.username; optionsTmp.enablePrivileges = options.enablePrivileges; if (options.securePassword != null) { optionsTmp.securePassword = options.securePassword.Copy(); } else optionsTmp.securePassword = null; if (options.authority != null) optionsTmp.authority = options.authority; if (options.impersonation != 0) optionsTmp.impersonation = options.impersonation; if (options.authentication != 0) optionsTmp.authentication = options.authentication; } else optionsTmp = new ConnectionOptions(); // Wire up change handler chain. Use supplied handler, if specified; // otherwise, default to that of the path argument. if (handler != null) optionsTmp.IdentifierChanged += handler; else if (options != null) optionsTmp.IdentifierChanged += new IdentifierChangedEventHandler(options.HandleIdentifierChange); return optionsTmp; } }//ConnectionOptions }
// 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.Security; namespace System.Management { /// <summary> /// <para>Describes the authentication level to be used to connect to WMI. This is used for the COM connection to WMI.</para> /// </summary> public enum AuthenticationLevel { /// <summary> /// <para>The default COM authentication level. WMI uses the default Windows Authentication setting.</para> /// </summary> Default = 0, /// <summary> /// <para> No COM authentication.</para> /// </summary> None = 1, /// <summary> /// <para> Connect-level COM authentication.</para> /// </summary> Connect = 2, /// <summary> /// <para> Call-level COM authentication.</para> /// </summary> Call = 3, /// <summary> /// <para> Packet-level COM authentication.</para> /// </summary> Packet = 4, /// <summary> /// <para>Packet Integrity-level COM authentication.</para> /// </summary> PacketIntegrity = 5, /// <summary> /// <para>Packet Privacy-level COM authentication.</para> /// </summary> PacketPrivacy = 6, /// <summary> /// <para>The default COM authentication level. WMI uses the default Windows Authentication setting.</para> /// </summary> Unchanged = -1 } /// <summary> /// <para>Describes the impersonation level to be used to connect to WMI.</para> /// </summary> public enum ImpersonationLevel { /// <summary> /// <para>Default impersonation.</para> /// </summary> Default = 0, /// <summary> /// <para> Anonymous COM impersonation level that hides the /// identity of the caller. Calls to WMI may fail /// with this impersonation level.</para> /// </summary> Anonymous = 1, /// <summary> /// <para> Identify-level COM impersonation level that allows objects /// to query the credentials of the caller. Calls to /// WMI may fail with this impersonation level.</para> /// </summary> Identify = 2, /// <summary> /// <para> Impersonate-level COM impersonation level that allows /// objects to use the credentials of the caller. This is the recommended impersonation level for WMI calls.</para> /// </summary> Impersonate = 3, /// <summary> /// <para> Delegate-level COM impersonation level that allows objects /// to permit other objects to use the credentials of the caller. This /// level, which will work with WMI calls but may constitute an unnecessary /// security risk, is supported only under Windows 2000.</para> /// </summary> Delegate = 4 } /// <summary> /// <para>Describes the possible effects of saving an object to WMI when /// using <see cref='System.Management.ManagementObject.Put()'/>.</para> /// </summary> public enum PutType { /// <summary> /// <para> Invalid Type </para> /// </summary> None = 0, /// <summary> /// <para> Updates an existing object /// only; does not create a new object.</para> /// </summary> UpdateOnly = 1, /// <summary> /// <para> Creates an object only; /// does not update an existing object.</para> /// </summary> CreateOnly = 2, /// <summary> /// <para> Saves the object, whether /// updating an existing object or creating a new object.</para> /// </summary> UpdateOrCreate = 3 } //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> /// Provides an abstract base class for all Options objects.</para> /// <para>Options objects are used to customize different management operations. </para> /// <para>Use one of the Options classes derived from this class, as /// indicated by the signature of the operation being performed.</para> /// </summary> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// [TypeConverter(typeof(ExpandableObjectConverter))] public abstract class ManagementOptions : ICloneable { /// <summary> /// <para> Specifies an infinite timeout.</para> /// </summary> public static readonly TimeSpan InfiniteTimeout = TimeSpan.MaxValue; internal int flags; internal ManagementNamedValueCollection context; internal TimeSpan timeout; //Used when any public property on this object is changed, to signal //to the containing object that it needs to be refreshed. internal event IdentifierChangedEventHandler IdentifierChanged; //Fires IdentifierChanged event internal void FireIdentifierChanged() { if (IdentifierChanged != null) IdentifierChanged(this, null); } //Called when IdentifierChanged() event fires internal void HandleIdentifierChange(object sender, IdentifierChangedEventArgs args) { //Something inside ManagementOptions changed, we need to fire an event //to the parent object FireIdentifierChanged(); } internal int Flags { get { return flags; } set { flags = value; } } /// <summary> /// <para> Gets or sets a WMI context object. This is a /// name-value pairs list to be passed through to a WMI provider that supports /// context information for customized operation.</para> /// </summary> /// <value> /// <para>A name-value pairs list to be passed through to a WMI provider that /// supports context information for customized operation.</para> /// </value> public ManagementNamedValueCollection Context { get { if (context == null) return context = new ManagementNamedValueCollection(); else return context; } set { ManagementNamedValueCollection oldContext = context; if (null != value) context = (ManagementNamedValueCollection)value.Clone(); else context = new ManagementNamedValueCollection(); if (null != oldContext) oldContext.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); //register for change events in this object context.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange); //the context property has changed so act like we fired the event HandleIdentifierChange(this, null); } } /// <summary> /// <para>Gets or sets the timeout to apply to the operation. /// Note that for operations that return collections, this timeout applies to the /// enumeration through the resulting collection, not the operation itself /// (the <see cref='System.Management.EnumerationOptions.ReturnImmediately'/> /// property is used for the latter).</para> /// This property is used to indicate that the operation should be performed semisynchronously. /// </summary> /// <value> /// <para>The default value for this property is <see cref='System.Management.ManagementOptions.InfiniteTimeout'/> /// , which means the operation will block. /// The value specified must be positive.</para> /// </value> public TimeSpan Timeout { get { return timeout; } set { //Timespan allows for negative values, but we want to make sure it's positive here... if (value.Ticks < 0) throw new ArgumentOutOfRangeException(nameof(value)); timeout = value; FireIdentifierChanged(); } } internal ManagementOptions() : this(null, InfiniteTimeout) { } internal ManagementOptions(ManagementNamedValueCollection context, TimeSpan timeout) : this(context, timeout, 0) { } internal ManagementOptions(ManagementNamedValueCollection context, TimeSpan timeout, int flags) { this.flags = flags; if (context != null) this.Context = context; else this.context = null; this.Timeout = timeout; } internal IWbemContext GetContext() { if (context != null) return context.GetContext(); else return null; } // We do not expose this publicly; instead the flag is set automatically // when making an async call if we detect that someone has requested to // listen for status messages. internal bool SendStatus { get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_SEND_STATUS) != 0) ? true : false); } set { Flags = (value == false) ? (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_SEND_STATUS) : (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_SEND_STATUS); } } /// <summary> /// <para> Returns a copy of the object.</para> /// </summary> /// <returns> /// <para>The cloned object.</para> /// </returns> public abstract object Clone(); } //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para>Provides a base class for query and enumeration-related options /// objects.</para> /// <para>Use this class to customize enumeration of management /// objects, traverse management object relationships, or query for /// management objects.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to enumerate all top-level WMI classes /// // and subclasses in root/cimv2 namespace. /// class Sample_EnumerationOptions /// { /// public static int Main(string[] args) { /// ManagementClass newClass = new ManagementClass(); /// EnumerationOptions options = new EnumerationOptions(); /// options.EnumerateDeep = false; /// foreach (ManagementObject o in newClass.GetSubclasses(options)) { /// Console.WriteLine(o["__Class"]); /// } /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example demonstrates how to enumerate all top-level WMI classes /// ' and subclasses in root/cimv2 namespace. /// Class Sample_EnumerationOptions /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim newClass As New ManagementClass() /// Dim options As New EnumerationOptions() /// options.EnumerateDeep = False /// Dim o As ManagementObject /// For Each o In newClass.GetSubclasses(options) /// Console.WriteLine(o("__Class")) /// Next o /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class EnumerationOptions : ManagementOptions { private int blockSize; /// <summary> /// <para>Gets or sets a value indicating whether the invoked operation should be /// performed in a synchronous or semisynchronous fashion. If this property is set /// to <see langword='true'/>, the enumeration is invoked and the call returns immediately. The actual /// retrieval of the results will occur when the resulting collection is walked.</para> /// </summary> /// <value> /// <para><see langword='true'/> if the invoked operation should /// be performed in a synchronous or semisynchronous fashion; otherwise, /// <see langword='false'/>. The default value is <see langword='true'/>.</para> /// </value> public bool ReturnImmediately { get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY) != 0) ? true : false); } set { Flags = (value == false) ? (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY) : (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY); } } /// <summary> /// <para> Gets or sets the block size /// for block operations. When enumerating through a collection, WMI will return results in /// groups of the specified size.</para> /// </summary> /// <value> /// <para>The default value is 1.</para> /// </value> public int BlockSize { get { return blockSize; } set { //Unfortunately BlockSize was defined as int, but valid values are only > 0 if (value <= 0) throw new ArgumentOutOfRangeException(nameof(value)); blockSize = value; } } /// <summary> /// <para>Gets or sets a value indicating whether the collection is assumed to be /// rewindable. If <see langword='true'/>, the objects in the /// collection will be kept available for multiple enumerations. If /// <see langword='false'/>, the collection /// can only be enumerated one time.</para> /// </summary> /// <value> /// <para><see langword='true'/> if the collection is assumed to /// be rewindable; otherwise, <see langword='false'/>. The default value is /// <see langword='true'/>.</para> /// </value> /// <remarks> /// <para>A rewindable collection is more costly in memory /// consumption as all the objects need to be kept available at the same time. /// In a collection defined as non-rewindable, the objects are discarded after being returned /// in the enumeration.</para> /// </remarks> public bool Rewindable { get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_FORWARD_ONLY) != 0) ? false : true); } set { Flags = (value == true) ? (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_FORWARD_ONLY) : (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_FORWARD_ONLY); } } /// <summary> /// <para> Gets or sets a value indicating whether the objects returned from /// WMI should contain amended information. Typically, amended information is localizable /// information attached to the WMI object, such as object and property /// descriptions.</para> /// </summary> /// <value> /// <para><see langword='true'/> if the objects returned from WMI /// should contain amended information; otherwise, <see langword='false'/>. The /// default value is <see langword='false'/>.</para> /// </value> /// <remarks> /// <para>If descriptions and other amended information are not of /// interest, setting this property to <see langword='false'/> /// is more /// efficient.</para> /// </remarks> public bool UseAmendedQualifiers { get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) != 0) ? true : false); } set { Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) : (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS); } } /// <summary> /// <para>Gets or sets a value indicating whether to the objects returned should have /// locatable information in them. This ensures that the system properties, such as /// <see langword='__PATH'/>, <see langword='__RELPATH'/>, and /// <see langword='__SERVER'/>, are non-NULL. This flag can only be used in queries, /// and is ignored in enumerations.</para> /// </summary> /// <value> /// <para><see langword='true'/> if WMI /// should ensure all returned objects have valid paths; otherwise, /// <see langword='false'/>. The default value is <see langword='false'/>.</para> /// </value> public bool EnsureLocatable { get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_ENSURE_LOCATABLE) != 0) ? true : false); } set { Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_ENSURE_LOCATABLE) : (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_ENSURE_LOCATABLE); } } /// <summary> /// <para>Gets or sets a value indicating whether the query should return a /// prototype of the result set instead of the actual results. This flag is used for /// prototyping.</para> /// </summary> /// <value> /// <para><see langword='true'/> if the /// query should return a prototype of the result set instead of the actual results; /// otherwise, <see langword='false'/>. The default value is /// <see langword='false'/>.</para> /// </value> public bool PrototypeOnly { get { return (((Flags & (int)tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_PROTOTYPE) != 0) ? true : false); } set { Flags = (value == true) ? (Flags | (int)tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_PROTOTYPE) : (Flags & (int)~tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_PROTOTYPE); } } /// <summary> /// <para> Gets or sets a value indicating whether direct access to the WMI provider is requested for the specified class, /// without any regard to its base class or derived classes.</para> /// </summary> /// <value> /// <para><see langword='true'/> if only /// objects of the specified class should be received, without regard to derivation /// or inheritance; otherwise, <see langword='false'/>. The default value is /// <see langword='false'/>. </para> /// </value> public bool DirectRead { get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_DIRECT_READ) != 0) ? true : false); } set { Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_DIRECT_READ) : (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_DIRECT_READ); } } /// <summary> /// <para> Gets or sets a value indicating whether recursive enumeration is requested /// into all classes derived from the specified base class. If /// <see langword='false'/>, only immediate derived /// class members are returned.</para> /// </summary> /// <value> /// <para><see langword='true'/> if recursive enumeration is requested /// into all classes derived from the specified base class; otherwise, /// <see langword='false'/>. The default value is <see langword='false'/>.</para> /// </value> public bool EnumerateDeep { get { return (((Flags & (int)tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_SHALLOW) != 0) ? false : true); } set { Flags = (value == false) ? (Flags | (int)tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_SHALLOW) : (Flags & (int)~tag_WBEM_QUERY_FLAG_TYPE.WBEM_FLAG_SHALLOW); } } //default constructor /// <overload> /// Initializes a new instance /// of the <see cref='System.Management.EnumerationOptions'/> class. /// </overload> /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.EnumerationOptions'/> /// class with default values (see the individual property descriptions /// for what the default values are). This is the default constructor. </para> /// </summary> public EnumerationOptions() : this(null, InfiniteTimeout, 1, true, true, false, false, false, false, false) { } //Constructor that specifies flags as individual values - we need to set the flags accordingly ! /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.EnumerationOptions'/> class to be used for queries or enumerations, /// allowing the user to specify values for the different options.</para> /// </summary> /// <param name='context'>The options context object containing provider-specific information that can be passed through to the provider.</param> /// <param name=' timeout'>The timeout value for enumerating through the results.</param> /// <param name=' blockSize'>The number of items to retrieve at one time from WMI.</param> /// <param name=' rewindable'><see langword='true'/> to specify whether the result set is rewindable (=allows multiple traversal or one-time); otherwise, <see langword='false'/>.</param> /// <param name=' returnImmediatley'><see langword='true'/> to specify whether the operation should return immediately (semi-sync) or block until all results are available; otherwise, <see langword='false'/> .</param> /// <param name=' useAmendedQualifiers'><see langword='true'/> to specify whether the returned objects should contain amended (locale-aware) qualifiers; otherwise, <see langword='false'/> .</param> /// <param name=' ensureLocatable'><see langword='true'/> to specify to WMI that it should ensure all returned objects have valid paths; otherwise, <see langword='false'/> .</param> /// <param name=' prototypeOnly'><see langword='true'/> to return a prototype of the result set instead of the actual results; otherwise, <see langword='false'/> .</param> /// <param name=' directRead'><see langword='true'/> to retrieve objects of only the specified class only or from derived classes as well; otherwise, <see langword='false'/> .</param> /// <param name=' enumerateDeep'><see langword='true'/> to specify recursive enumeration in subclasses; otherwise, <see langword='false'/> .</param> public EnumerationOptions( ManagementNamedValueCollection context, TimeSpan timeout, int blockSize, bool rewindable, bool returnImmediatley, bool useAmendedQualifiers, bool ensureLocatable, bool prototypeOnly, bool directRead, bool enumerateDeep) : base(context, timeout) { BlockSize = blockSize; Rewindable = rewindable; ReturnImmediately = returnImmediatley; UseAmendedQualifiers = useAmendedQualifiers; EnsureLocatable = ensureLocatable; PrototypeOnly = prototypeOnly; DirectRead = directRead; EnumerateDeep = enumerateDeep; } /// <summary> /// <para> Returns a copy of the object.</para> /// </summary> /// <returns> /// <para>The cloned object.</para> /// </returns> public override object Clone() { ManagementNamedValueCollection newContext = null; if (null != Context) newContext = (ManagementNamedValueCollection)Context.Clone(); return new EnumerationOptions(newContext, Timeout, blockSize, Rewindable, ReturnImmediately, UseAmendedQualifiers, EnsureLocatable, PrototypeOnly, DirectRead, EnumerateDeep); } }//EnumerationOptions //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Specifies options for management event watching.</para> /// <para>Use this class to customize subscriptions for watching management events. </para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to listen to an event using ManagementEventWatcher object. /// class Sample_EventWatcherOptions /// { /// public static int Main(string[] args) { /// ManagementClass newClass = new ManagementClass(); /// newClass["__CLASS"] = "TestDeletionClass"; /// newClass.Put(); /// /// EventWatcherOptions options = new EventWatcherOptions(); /// ManagementEventWatcher watcher = new ManagementEventWatcher(null, /// new WqlEventQuery("__classdeletionevent"), /// options); /// MyHandler handler = new MyHandler(); /// watcher.EventArrived += new EventArrivedEventHandler(handler.Arrived); /// watcher.Start(); /// /// // Delete class to trigger event /// newClass.Delete(); /// /// //For the purpose of this example, we will wait /// // two seconds before main thread terminates. /// System.Threading.Thread.Sleep(2000); /// /// watcher.Stop(); /// /// return 0; /// } /// /// public class MyHandler /// { /// public void Arrived(object sender, EventArrivedEventArgs e) { /// Console.WriteLine("Class Deleted= " + /// ((ManagementBaseObject)e.NewEvent["TargetClass"])["__CLASS"]); /// } /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example demonstrates how to listen to an event using the ManagementEventWatcher object. /// Class Sample_EventWatcherOptions /// Public Shared Sub Main() /// Dim newClass As New ManagementClass() /// newClass("__CLASS") = "TestDeletionClass" /// newClass.Put() /// /// Dim options As _ /// New EventWatcherOptions() /// Dim watcher As New ManagementEventWatcher( _ /// Nothing, _ /// New WqlEventQuery("__classdeletionevent"), _ /// options) /// Dim handler As New MyHandler() /// AddHandler watcher.EventArrived, AddressOf handler.Arrived /// watcher.Start() /// /// ' Delete class to trigger event /// newClass.Delete() /// /// ' For the purpose of this example, we will wait /// ' two seconds before main thread terminates. /// System.Threading.Thread.Sleep(2000) /// watcher.Stop() /// End Sub /// /// Public Class MyHandler /// Public Sub Arrived(sender As Object, e As EventArrivedEventArgs) /// Console.WriteLine("Class Deleted = " &amp; _ /// CType(e.NewEvent("TargetClass"), ManagementBaseObject)("__CLASS")) /// End Sub /// End Class /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class EventWatcherOptions : ManagementOptions { private int blockSize = 1; /// <summary> /// <para>Gets or sets the block size for block operations. When waiting for events, this /// value specifies how many events to wait for before returning.</para> /// </summary> /// <value> /// <para>The default value is 1.</para> /// </value> public int BlockSize { get { return blockSize; } set { blockSize = value; FireIdentifierChanged(); } } /// <overload> /// <para>Initializes a new instance of the <see cref='System.Management.EventWatcherOptions'/> class. </para> /// </overload> /// <summary> /// <para> Initializes a new instance of the <see cref='System.Management.EventWatcherOptions'/> class for event watching, using default values. /// This is the default constructor.</para> /// </summary> public EventWatcherOptions() : this(null, InfiniteTimeout, 1) { } /// <summary> /// <para> Initializes a new instance of the <see cref='System.Management.EventWatcherOptions'/> class with the given /// values.</para> /// </summary> /// <param name='context'>The options context object containing provider-specific information to be passed through to the provider. </param> /// <param name=' timeout'>The timeout to wait for the next events.</param> /// <param name=' blockSize'>The number of events to wait for in each block.</param> public EventWatcherOptions(ManagementNamedValueCollection context, TimeSpan timeout, int blockSize) : base(context, timeout) { Flags = (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_RETURN_IMMEDIATELY | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_FORWARD_ONLY; BlockSize = blockSize; } /// <summary> /// <para> Returns a copy of the object.</para> /// </summary> /// <returns> /// The cloned object. /// </returns> public override object Clone() { ManagementNamedValueCollection newContext = null; if (null != Context) newContext = (ManagementNamedValueCollection)Context.Clone(); return new EventWatcherOptions(newContext, Timeout, blockSize); } }//EventWatcherOptions //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Specifies options for getting a management object.</para> /// Use this class to customize retrieval of a management object. /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to set a timeout value and list /// // all amended qualifiers in a ManagementClass object. /// class Sample_ObjectGetOptions /// { /// public static int Main(string[] args) { /// // Request amended qualifiers /// ObjectGetOptions options = /// new ObjectGetOptions(null, new TimeSpan(0,0,0,5), true); /// ManagementClass diskClass = /// new ManagementClass("root/cimv2", "Win32_Process", options); /// foreach (QualifierData qualifier in diskClass.Qualifiers) { /// Console.WriteLine(qualifier.Name + ":" + qualifier.Value); /// } /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example demonstrates how to set a timeout value and list /// ' all amended qualifiers in a ManagementClass object. /// Class Sample_ObjectGetOptions /// Overloads Public Shared Function Main(args() As String) As Integer /// ' Request amended qualifiers /// Dim options As _ /// New ObjectGetOptions(Nothing, New TimeSpan(0, 0, 0, 5), True) /// Dim diskClass As New ManagementClass( _ /// "root/cimv2", _ /// "Win32_Process", _ /// options) /// Dim qualifier As QualifierData /// For Each qualifier In diskClass.Qualifiers /// Console.WriteLine(qualifier.Name &amp; ":" &amp; qualifier.Value) /// Next qualifier /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class ObjectGetOptions : ManagementOptions { internal static ObjectGetOptions _Clone(ObjectGetOptions options) { return ObjectGetOptions._Clone(options, null); } internal static ObjectGetOptions _Clone(ObjectGetOptions options, IdentifierChangedEventHandler handler) { ObjectGetOptions optionsTmp; if (options != null) optionsTmp = new ObjectGetOptions(options.context, options.timeout, options.UseAmendedQualifiers); else optionsTmp = new ObjectGetOptions(); // Wire up change handler chain. Use supplied handler, if specified; // otherwise, default to that of the path argument. if (handler != null) optionsTmp.IdentifierChanged += handler; else if (options != null) optionsTmp.IdentifierChanged += new IdentifierChangedEventHandler(options.HandleIdentifierChange); return optionsTmp; } /// <summary> /// <para> Gets or sets a value indicating whether the objects returned from WMI should /// contain amended information. Typically, amended information is localizable information /// attached to the WMI object, such as object and property descriptions.</para> /// </summary> /// <value> /// <para><see langword='true'/> if the objects returned from WMI /// should contain amended information; otherwise, <see langword='false'/>. The /// default value is <see langword='false'/>.</para> /// </value> public bool UseAmendedQualifiers { get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) != 0) ? true : false); } set { Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) : (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS); FireIdentifierChanged(); } } /// <overload> /// <para>Initializes a new instance of the <see cref='System.Management.ObjectGetOptions'/> class.</para> /// </overload> /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ObjectGetOptions'/> class for getting a WMI object, using /// default values. This is the default constructor.</para> /// </summary> public ObjectGetOptions() : this(null, InfiniteTimeout, false) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ObjectGetOptions'/> class for getting a WMI object, using the /// specified provider-specific context.</para> /// </summary> /// <param name='context'>A provider-specific, named-value pairs context object to be passed through to the provider.</param> public ObjectGetOptions(ManagementNamedValueCollection context) : this(context, InfiniteTimeout, false) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ObjectGetOptions'/> class for getting a WMI object, /// using the given options values.</para> /// </summary> /// <param name='context'>A provider-specific, named-value pairs context object to be passed through to the provider.</param> /// <param name=' timeout'>The length of time to let the operation perform before it times out. The default is <see cref='System.Management.ManagementOptions.InfiniteTimeout'/> .</param> /// <param name=' useAmendedQualifiers'><see langword='true'/> if the returned objects should contain amended (locale-aware) qualifiers; otherwise, <see langword='false'/>. </param> public ObjectGetOptions(ManagementNamedValueCollection context, TimeSpan timeout, bool useAmendedQualifiers) : base(context, timeout) { UseAmendedQualifiers = useAmendedQualifiers; } /// <summary> /// <para> Returns a copy of the object.</para> /// </summary> /// <returns> /// <para>The cloned object.</para> /// </returns> public override object Clone() { ManagementNamedValueCollection newContext = null; if (null != Context) newContext = (ManagementNamedValueCollection)Context.Clone(); return new ObjectGetOptions(newContext, Timeout, UseAmendedQualifiers); } } //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Specifies options for committing management /// object changes.</para> /// <para>Use this class to customize how values are saved to a management object.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to specify a PutOptions using /// // PutOptions object when saving a ManagementClass object to /// // the WMI respository. /// class Sample_PutOptions /// { /// public static int Main(string[] args) { /// ManagementClass newClass = new ManagementClass("root/default", /// String.Empty, /// null); /// newClass["__Class"] = "class999xc"; /// /// PutOptions options = new PutOptions(); /// options.Type = PutType.UpdateOnly; /// /// try /// { /// newClass.Put(options); //will fail if the class doesn't already exist /// } /// catch (ManagementException e) /// { /// Console.WriteLine("Couldn't update class: " + e.ErrorCode); /// } /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example demonstrates how to specify a PutOptions using /// ' PutOptions object when saving a ManagementClass object to /// ' WMI respository. /// Class Sample_PutOptions /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim newClass As New ManagementClass( _ /// "root/default", _ /// String.Empty, _ /// Nothing) /// newClass("__Class") = "class999xc" /// /// Dim options As New PutOptions() /// options.Type = PutType.UpdateOnly 'will fail if the class doesn't already exist /// /// Try /// newClass.Put(options) /// Catch e As ManagementException /// Console.WriteLine("Couldn't update class: " &amp; e.ErrorCode) /// End Try /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class PutOptions : ManagementOptions { /// <summary> /// <para> Gets or sets a value indicating whether the objects returned from WMI should /// contain amended information. Typically, amended information is localizable information /// attached to the WMI object, such as object and property descriptions.</para> /// </summary> /// <value> /// <para><see langword='true'/> if the objects returned from WMI /// should contain amended information; otherwise, <see langword='false'/>. The /// default value is <see langword='false'/>.</para> /// </value> public bool UseAmendedQualifiers { get { return (((Flags & (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) != 0) ? true : false); } set { Flags = (value == true) ? (Flags | (int)tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS) : (Flags & (int)~tag_WBEM_GENERIC_FLAG_TYPE.WBEM_FLAG_USE_AMENDED_QUALIFIERS); } } /// <summary> /// <para>Gets or sets the type of commit to be performed for the object.</para> /// </summary> /// <value> /// <para>The default value is <see cref='System.Management.PutType.UpdateOrCreate'/>.</para> /// </value> public PutType Type { get { return (((Flags & (int)tag_WBEM_CHANGE_FLAG_TYPE.WBEM_FLAG_UPDATE_ONLY) != 0) ? PutType.UpdateOnly : ((Flags & (int)tag_WBEM_CHANGE_FLAG_TYPE.WBEM_FLAG_CREATE_ONLY) != 0) ? PutType.CreateOnly : PutType.UpdateOrCreate); } set { Flags |= value switch { PutType.UpdateOnly => (int)tag_WBEM_CHANGE_FLAG_TYPE.WBEM_FLAG_UPDATE_ONLY, PutType.CreateOnly => (int)tag_WBEM_CHANGE_FLAG_TYPE.WBEM_FLAG_CREATE_ONLY, PutType.UpdateOrCreate => (int)tag_WBEM_CHANGE_FLAG_TYPE.WBEM_FLAG_CREATE_OR_UPDATE, _ => throw new ArgumentException(null, nameof(Type)), }; } } /// <overload> /// <para> Initializes a new instance of the <see cref='System.Management.PutOptions'/> class.</para> /// </overload> /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.PutOptions'/> class for put operations, using default values. /// This is the default constructor.</para> /// </summary> public PutOptions() : this(null, InfiniteTimeout, false, PutType.UpdateOrCreate) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.PutOptions'/> class for committing a WMI object, using the /// specified provider-specific context.</para> /// </summary> /// <param name='context'>A provider-specific, named-value pairs context object to be passed through to the provider.</param> public PutOptions(ManagementNamedValueCollection context) : this(context, InfiniteTimeout, false, PutType.UpdateOrCreate) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.PutOptions'/> class for committing a WMI object, using /// the specified option values.</para> /// </summary> /// <param name='context'>A provider-specific, named-value pairs object to be passed through to the provider. </param> /// <param name=' timeout'>The length of time to let the operation perform before it times out. The default is <see cref='System.Management.ManagementOptions.InfiniteTimeout'/> .</param> /// <param name=' useAmendedQualifiers'><see langword='true'/> if the returned objects should contain amended (locale-aware) qualifiers; otherwise, <see langword='false'/>. </param> /// <param name=' putType'> The type of commit to be performed (update or create).</param> public PutOptions(ManagementNamedValueCollection context, TimeSpan timeout, bool useAmendedQualifiers, PutType putType) : base(context, timeout) { UseAmendedQualifiers = useAmendedQualifiers; Type = putType; } /// <summary> /// <para> Returns a copy of the object.</para> /// </summary> /// <returns> /// <para>The cloned object.</para> /// </returns> public override object Clone() { ManagementNamedValueCollection newContext = null; if (null != Context) newContext = (ManagementNamedValueCollection)Context.Clone(); return new PutOptions(newContext, Timeout, UseAmendedQualifiers, Type); } } //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Specifies options for deleting a management /// object.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to specify a timeout value /// // when deleting a ManagementClass object. /// class Sample_DeleteOptions /// { /// public static int Main(string[] args) { /// ManagementClass newClass = new ManagementClass(); /// newClass["__CLASS"] = "ClassToDelete"; /// newClass.Put(); /// /// // Set deletion options: delete operation timeout value /// DeleteOptions opt = new DeleteOptions(null, new TimeSpan(0,0,0,5)); /// /// ManagementClass dummyClassToDelete = /// new ManagementClass("ClassToDelete"); /// dummyClassToDelete.Delete(opt); /// /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This sample demonstrates how to specify a timeout value /// ' when deleting a ManagementClass object. /// Class Sample_DeleteOptions /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim newClass As New ManagementClass() /// newClass("__CLASS") = "ClassToDelete" /// newClass.Put() /// /// ' Set deletion options: delete operation timeout value /// Dim opt As New DeleteOptions(Nothing, New TimeSpan(0, 0, 0, 5)) /// /// Dim dummyClassToDelete As New ManagementClass("ClassToDelete") /// dummyClassToDelete.Delete(opt) /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class DeleteOptions : ManagementOptions { /// <overload> /// <para>Initializes a new instance of the <see cref='System.Management.DeleteOptions'/> class.</para> /// </overload> /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.DeleteOptions'/> class for the delete operation, using default values. /// This is the default constructor.</para> /// </summary> public DeleteOptions() : base() { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.DeleteOptions'/> class for a delete operation, using /// the specified values.</para> /// </summary> /// <param name='context'>A provider-specific, named-value pairs object to be passed through to the provider. </param> /// <param name='timeout'>The length of time to let the operation perform before it times out. The default value is <see cref='System.Management.ManagementOptions.InfiniteTimeout'/> . Setting this parameter will invoke the operation semisynchronously.</param> public DeleteOptions(ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout) { } /// <summary> /// <para> Returns a copy of the object.</para> /// </summary> /// <returns> /// <para>A cloned object.</para> /// </returns> public override object Clone() { ManagementNamedValueCollection newContext = null; if (null != Context) newContext = (ManagementNamedValueCollection)Context.Clone(); return new DeleteOptions(newContext, Timeout); } } //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Specifies options for invoking a management method.</para> /// <para>Use this class to customize the execution of a method on a management /// object.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to stop a system service. /// class Sample_InvokeMethodOptions /// { /// public static int Main(string[] args) { /// ManagementObject service = /// new ManagementObject("win32_service=\"winmgmt\""); /// InvokeMethodOptions options = new InvokeMethodOptions(); /// options.Timeout = new TimeSpan(0,0,0,5); /// /// ManagementBaseObject outParams = service.InvokeMethod("StopService", null, options); /// /// Console.WriteLine("Return Status = " + outParams["ReturnValue"]); /// /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This sample demonstrates how to stop a system service. /// Class Sample_InvokeMethodOptions /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim service As New ManagementObject("win32_service=""winmgmt""") /// Dim options As New InvokeMethodOptions() /// options.Timeout = New TimeSpan(0, 0, 0, 5) /// /// Dim outParams As ManagementBaseObject = service.InvokeMethod( _ /// "StopService", _ /// Nothing, _ /// options) /// /// Console.WriteLine("Return Status = " &amp; _ /// outParams("ReturnValue").ToString()) /// /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class InvokeMethodOptions : ManagementOptions { /// <overload> /// <para>Initializes a new instance of the <see cref='System.Management.InvokeMethodOptions'/> class.</para> /// </overload> /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.InvokeMethodOptions'/> class for the <see cref='System.Management.ManagementObject.InvokeMethod(string, ManagementBaseObject, InvokeMethodOptions) '/> operation, using default values. /// This is the default constructor.</para> /// </summary> public InvokeMethodOptions() : base() { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.InvokeMethodOptions'/> class for an invoke operation using /// the specified values.</para> /// </summary> /// <param name=' context'>A provider-specific, named-value pairs object to be passed through to the provider. </param> /// <param name='timeout'>The length of time to let the operation perform before it times out. The default value is <see cref='System.Management.ManagementOptions.InfiniteTimeout'/> . Setting this parameter will invoke the operation semisynchronously.</param> public InvokeMethodOptions(ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout) { } /// <summary> /// <para> Returns a copy of the object.</para> /// </summary> /// <returns> /// <para>The cloned object.</para> /// </returns> public override object Clone() { ManagementNamedValueCollection newContext = null; if (null != Context) newContext = (ManagementNamedValueCollection)Context.Clone(); return new InvokeMethodOptions(newContext, Timeout); } } //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Specifies all settings required to make a WMI connection.</para> /// <para>Use this class to customize a connection to WMI made via a /// ManagementScope object.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to connect to remote machine /// // using supplied credentials. /// class Sample_ConnectionOptions /// { /// public static int Main(string[] args) { /// ConnectionOptions options = new ConnectionOptions(); /// options.Username = "domain\\username"; /// options.Password = "password"; /// ManagementScope scope = new ManagementScope( /// "\\\\servername\\root\\cimv2", /// options); /// try { /// scope.Connect(); /// ManagementObject disk = new ManagementObject( /// scope, /// new ManagementPath("Win32_logicaldisk='c:'"), /// null); /// disk.Get(); /// } /// catch (Exception e) { /// Console.WriteLine("Failed to connect: " + e.Message); /// } /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example demonstrates how to connect to remote machine /// ' using supplied credentials. /// Class Sample_ConnectionOptions /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim options As New ConnectionOptions() /// options.Username = "domain\username" /// options.Password = "password" /// Dim scope As New ManagementScope("\\servername\root\cimv2", options) /// Try /// scope.Connect() /// Dim disk As New ManagementObject(scope, _ /// New ManagementPath("Win32_logicaldisk='c:'"), Nothing) /// disk.Get() /// Catch e As UnauthorizedAccessException /// Console.WriteLine(("Failed to connect: " + e.Message)) /// End Try /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class ConnectionOptions : ManagementOptions { internal const string DEFAULTLOCALE = null; internal const string DEFAULTAUTHORITY = null; internal const ImpersonationLevel DEFAULTIMPERSONATION = ImpersonationLevel.Impersonate; internal const AuthenticationLevel DEFAULTAUTHENTICATION = AuthenticationLevel.Unchanged; internal const bool DEFAULTENABLEPRIVILEGES = false; //Fields private string locale; private string username; private SecureString securePassword; private string authority; private ImpersonationLevel impersonation; private AuthenticationLevel authentication; private bool enablePrivileges; // //Properties // /// <summary> /// <para>Gets or sets the locale to be used for the connection operation.</para> /// </summary> /// <value> /// <para>The default value is DEFAULTLOCALE.</para> /// </value> public string Locale { get { return (null != locale) ? locale : string.Empty; } set { if (locale != value) { locale = value; FireIdentifierChanged(); } } } /// <summary> /// <para>Gets or sets the user name to be used for the connection operation.</para> /// </summary> /// <value> /// <para>Null if the connection will use the currently logged-on user; otherwise, a string representing the user name. The default value is null.</para> /// </value> /// <remarks> /// <para>If the user name is from a domain other than the current /// domain, the string may contain the domain name and user name, separated by a backslash:</para> /// <c> /// <para>string username = "EnterDomainHere\\EnterUsernameHere";</para> /// </c> /// </remarks> public string Username { get { return username; } set { if (username != value) { username = value; FireIdentifierChanged(); } } } /// <summary> /// <para>Sets the password for the specified user. The value can be set, but not retrieved.</para> /// </summary> /// <value> /// <para> The default value is null. If the user name is also /// null, the credentials used will be those of the currently logged-on user.</para> /// </value> /// <remarks> /// <para> A blank string ("") specifies a valid /// zero-length password.</para> /// </remarks> public string Password { set { if (value != null) { if (securePassword == null) { securePassword = new SecureString(); for (int i = 0; i < value.Length; i++) { securePassword.AppendChar(value[i]); } } else { SecureString tempStr = new SecureString(); for (int i = 0; i < value.Length; i++) { tempStr.AppendChar(value[i]); } securePassword.Clear(); securePassword = tempStr.Copy(); FireIdentifierChanged(); tempStr.Dispose(); } } else { if (securePassword != null) { securePassword.Dispose(); securePassword = null; FireIdentifierChanged(); } } } } /// <summary> /// <para>Sets the secure password for the specified user. The value can be set, but not retrieved.</para> /// </summary> /// <value> /// <para> The default value is null. If the user name is also /// null, the credentials used will be those of the currently logged-on user.</para> /// </value> /// <remarks> /// <para> A blank securestring ("") specifies a valid /// zero-length password.</para> /// </remarks> public SecureString SecurePassword { set { if (value != null) { if (securePassword == null) { securePassword = value.Copy(); } else { securePassword.Clear(); securePassword = value.Copy(); FireIdentifierChanged(); } } else { if (securePassword != null) { securePassword.Dispose(); securePassword = null; FireIdentifierChanged(); } } } } /// <summary> /// <para>Gets or sets the authority to be used to authenticate the specified user.</para> /// </summary> /// <value> /// <para>If not null, this property can contain the name of the /// Windows NT/Windows 2000 domain in which to obtain the user to /// authenticate.</para> /// </value> /// <remarks> /// <para> /// The property must be passed /// as follows: If it begins with the string "Kerberos:", Kerberos /// authentication will be used and this property should contain a Kerberos principal name. For /// example, Kerberos:&lt;principal name&gt;.</para> /// <para>If the property value begins with the string "NTLMDOMAIN:", NTLM /// authentication will be used and the property should contain a NTLM domain name. /// For example, NTLMDOMAIN:&lt;domain name&gt;. </para> /// <para>If the property is null, NTLM authentication will be used and the NTLM domain /// of the current user will be used.</para> /// </remarks> public string Authority { get { return (null != authority) ? authority : string.Empty; } set { if (authority != value) { authority = value; FireIdentifierChanged(); } } } /// <summary> /// <para>Gets or sets the COM impersonation level to be used for operations in this connection.</para> /// </summary> /// <value> /// <para>The COM impersonation level to be used for operations in /// this connection. The default value is <see cref='System.Management.ImpersonationLevel.Impersonate' qualify='true'/>, which indicates that the WMI provider can /// impersonate the client when performing the requested operations in this connection.</para> /// </value> /// <remarks> /// <para>The <see cref='System.Management.ImpersonationLevel.Impersonate' qualify='true'/> setting is advantageous when the provider is /// a trusted application or service. It eliminates the need for the provider to /// perform client identity and access checks for the requested operations. However, /// note that if for some reason the provider cannot be trusted, allowing it to /// impersonate the client may constitute a security threat. In such cases, it is /// recommended that this property be set by the client to a lower value, such as /// <see cref='System.Management.ImpersonationLevel. Identify' qualify='true'/>. Note that this may cause failure of the /// provider to perform the requested operations, for lack of sufficient permissions /// or inability to perform access checks.</para> /// </remarks> public ImpersonationLevel Impersonation { get { return impersonation; } set { if (impersonation != value) { impersonation = value; FireIdentifierChanged(); } } } /// <summary> /// <para>Gets or sets the COM authentication level to be used for operations in this connection.</para> /// </summary> /// <value> /// <para>The COM authentication level to be used for operations /// in this connection. The default value is <see cref='System.Management.AuthenticationLevel.Unchanged' qualify='true'/>, which indicates that the /// client will use the authentication level requested by the server, according to /// the standard DCOM negotiation process.</para> /// </value> /// <remarks> /// <para>On Windows 2000 and below, the WMI service will request /// Connect level authentication, while on Windows XP and higher it will request /// Packet level authentication. If the client requires a specific authentication /// setting, this property can be used to control the authentication level on this /// particular connection. For example, the property can be set to <see cref='System.Management.AuthenticationLevel.PacketPrivacy' qualify='true'/> /// if the /// client requires all communication to be encrypted.</para> /// </remarks> public AuthenticationLevel Authentication { get { return authentication; } set { if (authentication != value) { authentication = value; FireIdentifierChanged(); } } } /// <summary> /// <para>Gets or sets a value indicating whether user privileges need to be enabled for /// the connection operation. This property should only be used when the operation /// performed requires a certain user privilege to be enabled /// (for example, a machine reboot).</para> /// </summary> /// <value> /// <para><see langword='true'/> if user privileges need to be /// enabled for the connection operation; otherwise, <see langword='false'/>. The /// default value is <see langword='false'/>.</para> /// </value> public bool EnablePrivileges { get { return enablePrivileges; } set { if (enablePrivileges != value) { enablePrivileges = value; FireIdentifierChanged(); } } } // //Constructors // //default /// <overload> /// <para>Initializes a new instance of the <see cref='System.Management.ConnectionOptions'/> class.</para> /// </overload> /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ConnectionOptions'/> class for the connection operation, using default values. This is the /// default constructor.</para> /// </summary> public ConnectionOptions() : this(DEFAULTLOCALE, null, (string)null, DEFAULTAUTHORITY, DEFAULTIMPERSONATION, DEFAULTAUTHENTICATION, DEFAULTENABLEPRIVILEGES, null, InfiniteTimeout) { } //parameterized /// <summary> /// <para> Initializes a new instance of the <see cref='System.Management.ConnectionOptions'/> class to be used for a WMI /// connection, using the specified values.</para> /// </summary> /// <param name='locale'>The locale to be used for the connection.</param> /// <param name=' username'>The user name to be used for the connection. If null, the credentials of the currently logged-on user are used.</param> /// <param name=' password'>The password for the given user name. If the user name is also null, the credentials used will be those of the currently logged-on user.</param> /// <param name=' authority'><para>The authority to be used to authenticate the specified user.</para></param> /// <param name=' impersonation'>The COM impersonation level to be used for the connection.</param> /// <param name=' authentication'>The COM authentication level to be used for the connection.</param> /// <param name=' enablePrivileges'><see langword='true'/>to enable special user privileges; otherwise, <see langword='false'/> . This parameter should only be used when performing an operation that requires special Windows NT user privileges.</param> /// <param name=' context'>A provider-specific, named value pairs object to be passed through to the provider.</param> /// <param name=' timeout'>Reserved for future use.</param> public ConnectionOptions(string locale, string username, string password, string authority, ImpersonationLevel impersonation, AuthenticationLevel authentication, bool enablePrivileges, ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout) { if (locale != null) this.locale = locale; this.username = username; this.enablePrivileges = enablePrivileges; if (password != null) { this.securePassword = new SecureString(); for (int i = 0; i < password.Length; i++) { securePassword.AppendChar(password[i]); } } if (authority != null) this.authority = authority; if (impersonation != 0) this.impersonation = impersonation; if (authentication != 0) this.authentication = authentication; } //parameterized /// <summary> /// <para> Initializes a new instance of the <see cref='System.Management.ConnectionOptions'/> class to be used for a WMI /// connection, using the specified values.</para> /// </summary> /// <param name='locale'>The locale to be used for the connection.</param> /// <param name='username'>The user name to be used for the connection. If null, the credentials of the currently logged-on user are used.</param> /// <param name='password'>The secure password for the given user name. If the user name is also null, the credentials used will be those of the currently logged-on user.</param> /// <param name='authority'><para>The authority to be used to authenticate the specified user.</para></param> /// <param name='impersonation'>The COM impersonation level to be used for the connection.</param> /// <param name='authentication'>The COM authentication level to be used for the connection.</param> /// <param name='enablePrivileges'><see langword='true'/>to enable special user privileges; otherwise, <see langword='false'/> . This parameter should only be used when performing an operation that requires special Windows NT user privileges.</param> /// <param name='context'>A provider-specific, named value pairs object to be passed through to the provider.</param> /// <param name='timeout'>Reserved for future use.</param> public ConnectionOptions(string locale, string username, SecureString password, string authority, ImpersonationLevel impersonation, AuthenticationLevel authentication, bool enablePrivileges, ManagementNamedValueCollection context, TimeSpan timeout) : base(context, timeout) { if (locale != null) this.locale = locale; this.username = username; this.enablePrivileges = enablePrivileges; if (password != null) { this.securePassword = password.Copy(); } if (authority != null) this.authority = authority; if (impersonation != 0) this.impersonation = impersonation; if (authentication != 0) this.authentication = authentication; } /// <summary> /// <para> Returns a copy of the object.</para> /// </summary> /// <returns> /// <para>The cloned object.</para> /// </returns> public override object Clone() { ManagementNamedValueCollection newContext = null; if (null != Context) newContext = (ManagementNamedValueCollection)Context.Clone(); return new ConnectionOptions(locale, username, GetSecurePassword(), authority, impersonation, authentication, enablePrivileges, newContext, Timeout); } // //Methods // internal IntPtr GetPassword() { if (securePassword != null) { try { return System.Runtime.InteropServices.Marshal.SecureStringToBSTR(securePassword); } catch (OutOfMemoryException) { return IntPtr.Zero; } } else return IntPtr.Zero; } internal SecureString GetSecurePassword() { if (securePassword != null) return securePassword.Copy(); else return null; } internal ConnectionOptions(ManagementNamedValueCollection context, TimeSpan timeout, int flags) : base(context, timeout, flags) { } internal ConnectionOptions(ManagementNamedValueCollection context) : base(context, InfiniteTimeout) { } internal static ConnectionOptions _Clone(ConnectionOptions options) { return ConnectionOptions._Clone(options, null); } internal static ConnectionOptions _Clone(ConnectionOptions options, IdentifierChangedEventHandler handler) { ConnectionOptions optionsTmp; if (options != null) { optionsTmp = new ConnectionOptions(options.Context, options.Timeout, options.Flags); optionsTmp.locale = options.locale; optionsTmp.username = options.username; optionsTmp.enablePrivileges = options.enablePrivileges; if (options.securePassword != null) { optionsTmp.securePassword = options.securePassword.Copy(); } else optionsTmp.securePassword = null; if (options.authority != null) optionsTmp.authority = options.authority; if (options.impersonation != 0) optionsTmp.impersonation = options.impersonation; if (options.authentication != 0) optionsTmp.authentication = options.authentication; } else optionsTmp = new ConnectionOptions(); // Wire up change handler chain. Use supplied handler, if specified; // otherwise, default to that of the path argument. if (handler != null) optionsTmp.IdentifierChanged += handler; else if (options != null) optionsTmp.IdentifierChanged += new IdentifierChangedEventHandler(options.HandleIdentifierChange); return optionsTmp; } }//ConnectionOptions }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Runtime/tests/System/Reflection/AssemblyProductAttributeTests.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.Reflection.Tests { public class AssemblyProductAttributeTests { [Theory] [InlineData(null)] [InlineData("")] [InlineData("product")] [InlineData(".NET Core")] public void Ctor_String(string product) { var attribute = new AssemblyProductAttribute(product); Assert.Equal(product, attribute.Product); } } }
// 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.Reflection.Tests { public class AssemblyProductAttributeTests { [Theory] [InlineData(null)] [InlineData("")] [InlineData("product")] [InlineData(".NET Core")] public void Ctor_String(string product) { var attribute = new AssemblyProductAttribute(product); Assert.Equal(product, attribute.Product); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Data.Common/src/System/Data/DataKey.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; namespace System.Data { internal readonly struct DataKey : IEquatable<DataKey> { private const int maxColumns = 32; private readonly DataColumn[] _columns; internal DataKey(DataColumn[] columns, bool copyColumns) { if (columns == null) { throw ExceptionBuilder.ArgumentNull(nameof(columns)); } if (columns.Length == 0) { throw ExceptionBuilder.KeyNoColumns(); } if (columns.Length > maxColumns) { throw ExceptionBuilder.KeyTooManyColumns(maxColumns); } for (int i = 0; i < columns.Length; i++) { if (columns[i] == null) { throw ExceptionBuilder.ArgumentNull("column"); } } for (int i = 0; i < columns.Length; i++) { for (int j = 0; j < i; j++) { if (columns[i] == columns[j]) { throw ExceptionBuilder.KeyDuplicateColumns(columns[i].ColumnName); } } } if (copyColumns) { // Need to make a copy of all columns _columns = new DataColumn[columns.Length]; for (int i = 0; i < columns.Length; i++) { _columns[i] = columns[i]; } } else { // take ownership of the array passed in _columns = columns; } CheckState(); } internal DataColumn[] ColumnsReference => _columns; internal bool HasValue => null != _columns; internal DataTable Table => _columns[0].Table!; internal void CheckState() { DataTable? table = _columns[0].Table; if (table == null) { throw ExceptionBuilder.ColumnNotInAnyTable(); } for (int i = 1; i < _columns.Length; i++) { if (_columns[i].Table == null) { throw ExceptionBuilder.ColumnNotInAnyTable(); } if (_columns[i].Table != table) { throw ExceptionBuilder.KeyTableMismatch(); } } } //check to see if this.columns && key2's columns are equal regardless of order internal bool ColumnsEqual(DataKey key) => ColumnsEqual(_columns, key._columns); //check to see if columns1 && columns2 are equal regardless of order internal static bool ColumnsEqual(DataColumn[] column1, DataColumn[] column2) { if (column1 == column2) { return true; } else if (column1 == null || column2 == null) { return false; } else if (column1.Length != column2.Length) { return false; } else { int i, j; for (i = 0; i < column1.Length; i++) { bool check = false; for (j = 0; j < column2.Length; j++) { if (column1[i].Equals(column2[j])) { check = true; break; } } if (!check) { return false; } } } return true; } internal bool ContainsColumn(DataColumn column) { for (int i = 0; i < _columns.Length; i++) { if (column == _columns[i]) { return true; } } return false; } public override int GetHashCode() { Debug.Fail("don't put DataKey into a Hashtable"); return base.GetHashCode(); } public override bool Equals(object? value) { Debug.Fail("need to directly call Equals(DataKey)"); return Equals((DataKey)value); } public bool Equals(DataKey value) { //check to see if this.columns && key2's columns are equal... DataColumn[] column1 = _columns; DataColumn[] column2 = value._columns; if (column1 == column2) { return true; } else if (column1 == null || column2 == null) { return false; } else { return column1.AsSpan().SequenceEqual(column2); } } internal string[] GetColumnNames() { string[] values = new string[_columns.Length]; for (int i = 0; i < _columns.Length; ++i) { values[i] = _columns[i].ColumnName; } return values; } internal IndexField[] GetIndexDesc() { IndexField[] indexDesc = new IndexField[_columns.Length]; for (int i = 0; i < _columns.Length; i++) { indexDesc[i] = new IndexField(_columns[i], false); } return indexDesc; } internal object[] GetKeyValues(int record) { object[] values = new object[_columns.Length]; for (int i = 0; i < _columns.Length; i++) { values[i] = _columns[i][record]; } return values; } internal Index GetSortIndex() => GetSortIndex(DataViewRowState.CurrentRows); internal Index GetSortIndex(DataViewRowState recordStates) { IndexField[] indexDesc = GetIndexDesc(); return _columns[0].Table!.GetIndex(indexDesc, recordStates, null); } internal bool RecordsEqual(int record1, int record2) { for (int i = 0; i < _columns.Length; i++) { if (_columns[i].Compare(record1, record2) != 0) { return false; } } return true; } internal DataColumn[] ToArray() { DataColumn[] values = new DataColumn[_columns.Length]; for (int i = 0; i < _columns.Length; ++i) { values[i] = _columns[i]; } return values; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; namespace System.Data { internal readonly struct DataKey : IEquatable<DataKey> { private const int maxColumns = 32; private readonly DataColumn[] _columns; internal DataKey(DataColumn[] columns, bool copyColumns) { if (columns == null) { throw ExceptionBuilder.ArgumentNull(nameof(columns)); } if (columns.Length == 0) { throw ExceptionBuilder.KeyNoColumns(); } if (columns.Length > maxColumns) { throw ExceptionBuilder.KeyTooManyColumns(maxColumns); } for (int i = 0; i < columns.Length; i++) { if (columns[i] == null) { throw ExceptionBuilder.ArgumentNull("column"); } } for (int i = 0; i < columns.Length; i++) { for (int j = 0; j < i; j++) { if (columns[i] == columns[j]) { throw ExceptionBuilder.KeyDuplicateColumns(columns[i].ColumnName); } } } if (copyColumns) { // Need to make a copy of all columns _columns = new DataColumn[columns.Length]; for (int i = 0; i < columns.Length; i++) { _columns[i] = columns[i]; } } else { // take ownership of the array passed in _columns = columns; } CheckState(); } internal DataColumn[] ColumnsReference => _columns; internal bool HasValue => null != _columns; internal DataTable Table => _columns[0].Table!; internal void CheckState() { DataTable? table = _columns[0].Table; if (table == null) { throw ExceptionBuilder.ColumnNotInAnyTable(); } for (int i = 1; i < _columns.Length; i++) { if (_columns[i].Table == null) { throw ExceptionBuilder.ColumnNotInAnyTable(); } if (_columns[i].Table != table) { throw ExceptionBuilder.KeyTableMismatch(); } } } //check to see if this.columns && key2's columns are equal regardless of order internal bool ColumnsEqual(DataKey key) => ColumnsEqual(_columns, key._columns); //check to see if columns1 && columns2 are equal regardless of order internal static bool ColumnsEqual(DataColumn[] column1, DataColumn[] column2) { if (column1 == column2) { return true; } else if (column1 == null || column2 == null) { return false; } else if (column1.Length != column2.Length) { return false; } else { int i, j; for (i = 0; i < column1.Length; i++) { bool check = false; for (j = 0; j < column2.Length; j++) { if (column1[i].Equals(column2[j])) { check = true; break; } } if (!check) { return false; } } } return true; } internal bool ContainsColumn(DataColumn column) { for (int i = 0; i < _columns.Length; i++) { if (column == _columns[i]) { return true; } } return false; } public override int GetHashCode() { Debug.Fail("don't put DataKey into a Hashtable"); return base.GetHashCode(); } public override bool Equals(object? value) { Debug.Fail("need to directly call Equals(DataKey)"); return Equals((DataKey)value); } public bool Equals(DataKey value) { //check to see if this.columns && key2's columns are equal... DataColumn[] column1 = _columns; DataColumn[] column2 = value._columns; if (column1 == column2) { return true; } else if (column1 == null || column2 == null) { return false; } else { return column1.AsSpan().SequenceEqual(column2); } } internal string[] GetColumnNames() { string[] values = new string[_columns.Length]; for (int i = 0; i < _columns.Length; ++i) { values[i] = _columns[i].ColumnName; } return values; } internal IndexField[] GetIndexDesc() { IndexField[] indexDesc = new IndexField[_columns.Length]; for (int i = 0; i < _columns.Length; i++) { indexDesc[i] = new IndexField(_columns[i], false); } return indexDesc; } internal object[] GetKeyValues(int record) { object[] values = new object[_columns.Length]; for (int i = 0; i < _columns.Length; i++) { values[i] = _columns[i][record]; } return values; } internal Index GetSortIndex() => GetSortIndex(DataViewRowState.CurrentRows); internal Index GetSortIndex(DataViewRowState recordStates) { IndexField[] indexDesc = GetIndexDesc(); return _columns[0].Table!.GetIndex(indexDesc, recordStates, null); } internal bool RecordsEqual(int record1, int record2) { for (int i = 0; i < _columns.Length; i++) { if (_columns[i].Compare(record1, record2) != 0) { return false; } } return true; } internal DataColumn[] ToArray() { DataColumn[] values = new DataColumn[_columns.Length]; for (int i = 0; i < _columns.Length; ++i) { values[i] = _columns[i]; } return values; } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b61515/b61515.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RC2CryptoServiceProvider.NotSupported.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.Diagnostics.CodeAnalysis; using System.Runtime.Versioning; namespace System.Security.Cryptography { [Obsolete(Obsoletions.DerivedCryptographicTypesMessage, DiagnosticId = Obsoletions.DerivedCryptographicTypesDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] [EditorBrowsable(EditorBrowsableState.Never)] public sealed partial class RC2CryptoServiceProvider : RC2 { [SuppressMessage("Microsoft.Security", "CA5351", Justification = "This is the implementation of RC2CryptoServiceProvider")] [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] public RC2CryptoServiceProvider() { throw new PlatformNotSupportedException(); } public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) => default!; public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV) => default!; public override void GenerateIV() { } public override void GenerateKey() { } public bool UseSalt { get { return false; } [SupportedOSPlatform("windows")] set { } } } }
// 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.Diagnostics.CodeAnalysis; using System.Runtime.Versioning; namespace System.Security.Cryptography { [Obsolete(Obsoletions.DerivedCryptographicTypesMessage, DiagnosticId = Obsoletions.DerivedCryptographicTypesDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] [EditorBrowsable(EditorBrowsableState.Never)] public sealed partial class RC2CryptoServiceProvider : RC2 { [SuppressMessage("Microsoft.Security", "CA5351", Justification = "This is the implementation of RC2CryptoServiceProvider")] [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] public RC2CryptoServiceProvider() { throw new PlatformNotSupportedException(); } public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) => default!; public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV) => default!; public override void GenerateIV() { } public override void GenerateKey() { } public bool UseSalt { get { return false; } [SupportedOSPlatform("windows")] set { } } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/Common/src/System/Net/Http/aspnetcore/Http3/QPack/HeaderField.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.Text; namespace System.Net.Http.QPack { internal readonly struct HeaderField { // https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-4.1.1.3-1 // public for internal use in aspnetcore public const int RfcOverhead = 32; public HeaderField(byte[] name, byte[] value) { Debug.Assert(name.Length > 0); Name = name; Value = value; } public byte[] Name { get; } public byte[] Value { get; } public int Length => GetLength(Name.Length, Value.Length); public static int GetLength(int nameLength, int valueLength) => nameLength + valueLength + RfcOverhead; public override string ToString() { if (Name != null) { return Encoding.ASCII.GetString(Name) + ": " + Encoding.ASCII.GetString(Value); } else { return "<empty>"; } } } }
// 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.Text; namespace System.Net.Http.QPack { internal readonly struct HeaderField { // https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-4.1.1.3-1 // public for internal use in aspnetcore public const int RfcOverhead = 32; public HeaderField(byte[] name, byte[] value) { Debug.Assert(name.Length > 0); Name = name; Value = value; } public byte[] Name { get; } public byte[] Value { get; } public int Length => GetLength(Name.Length, Value.Length); public static int GetLength(int nameLength, int valueLength) => nameLength + valueLength + RfcOverhead; public override string ToString() { if (Name != null) { return Encoding.ASCII.GetString(Name) + ": " + Encoding.ASCII.GetString(Value); } else { return "<empty>"; } } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/Directed/coverage/oldtests/lclfldrem_cs_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="lclfldrem.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="lclfldrem.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/CompareLessThanScalar.Vector64.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 CompareLessThanScalar_Vector64_Single() { var test = new SimpleBinaryOpTest__CompareLessThanScalar_Vector64_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 SimpleBinaryOpTest__CompareLessThanScalar_Vector64_Single { 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(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); 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<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* 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<Single> _fld1; public Vector64<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<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareLessThanScalar_Vector64_Single testClass) { var result = AdvSimd.Arm64.CompareLessThanScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareLessThanScalar_Vector64_Single testClass) { fixed (Vector64<Single>* pFld1 = &_fld1) fixed (Vector64<Single>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.CompareLessThanScalar( AdvSimd.LoadVector64((Single*)(pFld1)), AdvSimd.LoadVector64((Single*)(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<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector64<Single> _clsVar1; private static Vector64<Single> _clsVar2; private Vector64<Single> _fld1; private Vector64<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareLessThanScalar_Vector64_Single() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); } public SimpleBinaryOpTest__CompareLessThanScalar_Vector64_Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<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, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.CompareLessThanScalar( Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.CompareLessThanScalar( AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.CompareLessThanScalar), new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.CompareLessThanScalar), new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.CompareLessThanScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Single>* pClsVar1 = &_clsVar1) fixed (Vector64<Single>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.CompareLessThanScalar( AdvSimd.LoadVector64((Single*)(pClsVar1)), AdvSimd.LoadVector64((Single*)(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<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.CompareLessThanScalar(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((Single*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.CompareLessThanScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareLessThanScalar_Vector64_Single(); var result = AdvSimd.Arm64.CompareLessThanScalar(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__CompareLessThanScalar_Vector64_Single(); fixed (Vector64<Single>* pFld1 = &test._fld1) fixed (Vector64<Single>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.CompareLessThanScalar( AdvSimd.LoadVector64((Single*)(pFld1)), AdvSimd.LoadVector64((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.CompareLessThanScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Single>* pFld1 = &_fld1) fixed (Vector64<Single>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.CompareLessThanScalar( AdvSimd.LoadVector64((Single*)(pFld1)), AdvSimd.LoadVector64((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.CompareLessThanScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.CompareLessThanScalar( AdvSimd.LoadVector64((Single*)(&test._fld1)), AdvSimd.LoadVector64((Single*)(&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<Single> op1, Vector64<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(Helpers.CompareLessThan(left[0], right[0])) != BitConverter.SingleToInt32Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.CompareLessThanScalar)}<Single>(Vector64<Single>, Vector64<Single>): {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 CompareLessThanScalar_Vector64_Single() { var test = new SimpleBinaryOpTest__CompareLessThanScalar_Vector64_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 SimpleBinaryOpTest__CompareLessThanScalar_Vector64_Single { 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(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); 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<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* 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<Single> _fld1; public Vector64<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<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareLessThanScalar_Vector64_Single testClass) { var result = AdvSimd.Arm64.CompareLessThanScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareLessThanScalar_Vector64_Single testClass) { fixed (Vector64<Single>* pFld1 = &_fld1) fixed (Vector64<Single>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.CompareLessThanScalar( AdvSimd.LoadVector64((Single*)(pFld1)), AdvSimd.LoadVector64((Single*)(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<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector64<Single> _clsVar1; private static Vector64<Single> _clsVar2; private Vector64<Single> _fld1; private Vector64<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareLessThanScalar_Vector64_Single() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); } public SimpleBinaryOpTest__CompareLessThanScalar_Vector64_Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<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, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.CompareLessThanScalar( Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.CompareLessThanScalar( AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.CompareLessThanScalar), new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.CompareLessThanScalar), new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.CompareLessThanScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Single>* pClsVar1 = &_clsVar1) fixed (Vector64<Single>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.CompareLessThanScalar( AdvSimd.LoadVector64((Single*)(pClsVar1)), AdvSimd.LoadVector64((Single*)(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<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.CompareLessThanScalar(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((Single*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.CompareLessThanScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareLessThanScalar_Vector64_Single(); var result = AdvSimd.Arm64.CompareLessThanScalar(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__CompareLessThanScalar_Vector64_Single(); fixed (Vector64<Single>* pFld1 = &test._fld1) fixed (Vector64<Single>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.CompareLessThanScalar( AdvSimd.LoadVector64((Single*)(pFld1)), AdvSimd.LoadVector64((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.CompareLessThanScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Single>* pFld1 = &_fld1) fixed (Vector64<Single>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.CompareLessThanScalar( AdvSimd.LoadVector64((Single*)(pFld1)), AdvSimd.LoadVector64((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.CompareLessThanScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.CompareLessThanScalar( AdvSimd.LoadVector64((Single*)(&test._fld1)), AdvSimd.LoadVector64((Single*)(&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<Single> op1, Vector64<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(Helpers.CompareLessThan(left[0], right[0])) != BitConverter.SingleToInt32Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.CompareLessThanScalar)}<Single>(Vector64<Single>, Vector64<Single>): {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,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMGroupsSet.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.DirectoryServices; using System.Runtime.InteropServices; namespace System.DirectoryServices.AccountManagement { internal sealed class SAMGroupsSet : ResultSet { internal SAMGroupsSet(UnsafeNativeMethods.IADsMembers iADsMembers, SAMStoreCtx storeCtx, DirectoryEntry ctxBase) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMGroupsSet", "SAMGroupsSet: creating for path={0}", ctxBase.Path); _groupsEnumerator = ((IEnumerable)iADsMembers).GetEnumerator(); _storeCtx = storeCtx; _ctxBase = ctxBase; } // Return the principal we're positioned at as a Principal object. // Need to use our StoreCtx's GetAsPrincipal to convert the native object to a Principal internal override object CurrentAsPrincipal { get { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMGroupsSet", "CurrentAsPrincipal"); Debug.Assert(_current != null); return SAMUtils.DirectoryEntryAsPrincipal(_current, _storeCtx); } } // Advance the enumerator to the next principal in the result set, pulling in additional pages // of results (or ranges of attribute values) as needed. // Returns true if successful, false if no more results to return. internal override bool MoveNext() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMGroupsSet", "MoveNext"); _atBeginning = false; bool f = _groupsEnumerator.MoveNext(); if (f) { // Got a group. Create a DirectoryEntry for it. // Clone the ctxBase to pick up its credentials, then build an appropriate path. UnsafeNativeMethods.IADs nativeMember = (UnsafeNativeMethods.IADs)_groupsEnumerator.Current; // We do this, rather than using the DirectoryEntry constructor that takes a native IADs object, // is so the credentials get transferred to the new DirectoryEntry. If we just use the native // object constructor, the native object will have the right credentials, but the DirectoryEntry // will have default (null) credentials, which it'll use anytime it needs to use credentials. DirectoryEntry de = SDSUtils.BuildDirectoryEntry( nativeMember.ADsPath, _storeCtx.Credentials, _storeCtx.AuthTypes); _current = de; } return f; } // Resets the enumerator to before the first result in the set. This potentially can be an expensive // operation, e.g., if doing a paged search, may need to re-retrieve the first page of results. // As a special case, if the ResultSet is already at the very beginning, this is guaranteed to be // a no-op. internal override void Reset() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMGroupsSet", "Reset"); if (!_atBeginning) { _groupsEnumerator.Reset(); _current = null; _atBeginning = true; } } // // Private fields // private readonly IEnumerator _groupsEnumerator; private readonly SAMStoreCtx _storeCtx; private readonly DirectoryEntry _ctxBase; private bool _atBeginning = true; private DirectoryEntry _current; } } // #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.DirectoryServices; using System.Runtime.InteropServices; namespace System.DirectoryServices.AccountManagement { internal sealed class SAMGroupsSet : ResultSet { internal SAMGroupsSet(UnsafeNativeMethods.IADsMembers iADsMembers, SAMStoreCtx storeCtx, DirectoryEntry ctxBase) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMGroupsSet", "SAMGroupsSet: creating for path={0}", ctxBase.Path); _groupsEnumerator = ((IEnumerable)iADsMembers).GetEnumerator(); _storeCtx = storeCtx; _ctxBase = ctxBase; } // Return the principal we're positioned at as a Principal object. // Need to use our StoreCtx's GetAsPrincipal to convert the native object to a Principal internal override object CurrentAsPrincipal { get { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMGroupsSet", "CurrentAsPrincipal"); Debug.Assert(_current != null); return SAMUtils.DirectoryEntryAsPrincipal(_current, _storeCtx); } } // Advance the enumerator to the next principal in the result set, pulling in additional pages // of results (or ranges of attribute values) as needed. // Returns true if successful, false if no more results to return. internal override bool MoveNext() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMGroupsSet", "MoveNext"); _atBeginning = false; bool f = _groupsEnumerator.MoveNext(); if (f) { // Got a group. Create a DirectoryEntry for it. // Clone the ctxBase to pick up its credentials, then build an appropriate path. UnsafeNativeMethods.IADs nativeMember = (UnsafeNativeMethods.IADs)_groupsEnumerator.Current; // We do this, rather than using the DirectoryEntry constructor that takes a native IADs object, // is so the credentials get transferred to the new DirectoryEntry. If we just use the native // object constructor, the native object will have the right credentials, but the DirectoryEntry // will have default (null) credentials, which it'll use anytime it needs to use credentials. DirectoryEntry de = SDSUtils.BuildDirectoryEntry( nativeMember.ADsPath, _storeCtx.Credentials, _storeCtx.AuthTypes); _current = de; } return f; } // Resets the enumerator to before the first result in the set. This potentially can be an expensive // operation, e.g., if doing a paged search, may need to re-retrieve the first page of results. // As a special case, if the ResultSet is already at the very beginning, this is guaranteed to be // a no-op. internal override void Reset() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMGroupsSet", "Reset"); if (!_atBeginning) { _groupsEnumerator.Reset(); _current = null; _atBeginning = true; } } // // Private fields // private readonly IEnumerator _groupsEnumerator; private readonly SAMStoreCtx _storeCtx; private readonly DirectoryEntry _ctxBase; private bool _atBeginning = true; private DirectoryEntry _current; } } // #endif
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociationAttribute.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.ComponentModel.DataAnnotations { /// <summary> /// Used to mark an Entity member as an association /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] [Obsolete("AssociationAttribute has been deprecated and is not supported.")] public sealed class AssociationAttribute : Attribute { /// <summary> /// Full form of constructor /// </summary> /// <param name="name">The name of the association. For bi-directional associations, /// the name must be the same on both sides of the association</param> /// <param name="thisKey">Comma separated list of the property names of the key values /// on this side of the association</param> /// <param name="otherKey">Comma separated list of the property names of the key values /// on the other side of the association</param> public AssociationAttribute(string name, string thisKey, string otherKey) { Name = name; ThisKey = thisKey; OtherKey = otherKey; } /// <summary> /// Gets the name of the association. For bi-directional associations, the name must /// be the same on both sides of the association /// </summary> public string Name { get; } /// <summary> /// Gets a comma separated list of the property names of the key values /// on this side of the association /// </summary> public string ThisKey { get; } /// <summary> /// Gets a comma separated list of the property names of the key values /// on the other side of the association /// </summary> public string OtherKey { get; } /// <summary> /// Gets or sets a value indicating whether this association member represents /// the foreign key side of an association /// </summary> public bool IsForeignKey { get; set; } /// <summary> /// Gets the collection of individual key members specified in the ThisKey string. /// </summary> public IEnumerable<string> ThisKeyMembers => GetKeyMembers(ThisKey); /// <summary> /// Gets the collection of individual key members specified in the OtherKey string. /// </summary> public IEnumerable<string> OtherKeyMembers => GetKeyMembers(OtherKey); /// <summary> /// Parses the comma delimited key specified /// </summary> /// <param name="key">The key to parse</param> /// <returns>Array of individual key members</returns> private static string[] GetKeyMembers(string? key) { if (key == null) { return Array.Empty<string>(); } return key.Replace(" ", string.Empty).Split(','); } } }
// 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.ComponentModel.DataAnnotations { /// <summary> /// Used to mark an Entity member as an association /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] [Obsolete("AssociationAttribute has been deprecated and is not supported.")] public sealed class AssociationAttribute : Attribute { /// <summary> /// Full form of constructor /// </summary> /// <param name="name">The name of the association. For bi-directional associations, /// the name must be the same on both sides of the association</param> /// <param name="thisKey">Comma separated list of the property names of the key values /// on this side of the association</param> /// <param name="otherKey">Comma separated list of the property names of the key values /// on the other side of the association</param> public AssociationAttribute(string name, string thisKey, string otherKey) { Name = name; ThisKey = thisKey; OtherKey = otherKey; } /// <summary> /// Gets the name of the association. For bi-directional associations, the name must /// be the same on both sides of the association /// </summary> public string Name { get; } /// <summary> /// Gets a comma separated list of the property names of the key values /// on this side of the association /// </summary> public string ThisKey { get; } /// <summary> /// Gets a comma separated list of the property names of the key values /// on the other side of the association /// </summary> public string OtherKey { get; } /// <summary> /// Gets or sets a value indicating whether this association member represents /// the foreign key side of an association /// </summary> public bool IsForeignKey { get; set; } /// <summary> /// Gets the collection of individual key members specified in the ThisKey string. /// </summary> public IEnumerable<string> ThisKeyMembers => GetKeyMembers(ThisKey); /// <summary> /// Gets the collection of individual key members specified in the OtherKey string. /// </summary> public IEnumerable<string> OtherKeyMembers => GetKeyMembers(OtherKey); /// <summary> /// Parses the comma delimited key specified /// </summary> /// <param name="key">The key to parse</param> /// <returns>Array of individual key members</returns> private static string[] GetKeyMembers(string? key) { if (key == null) { return Array.Empty<string>(); } return key.Replace(" ", string.Empty).Split(','); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Private.CoreLib/src/System/Threading/ApartmentState.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.Threading { public enum ApartmentState { /*========================================================================= ** Constants for thread apartment states. =========================================================================*/ STA = 0, MTA = 1, Unknown = 2 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Threading { public enum ApartmentState { /*========================================================================= ** Constants for thread apartment states. =========================================================================*/ STA = 0, MTA = 1, Unknown = 2 } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Collections.Specialized/tests/StringDictionary/StringDictionary.SetItemTests.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.Collections.Specialized.Tests { public class StringDictionaryItemSetTests { [Theory] [InlineData(0)] [InlineData(5)] public void Item_Set(int count) { StringDictionary stringDictionary = Helpers.CreateStringDictionary(count); for (int i = 0; i < stringDictionary.Count; i++) { string key = "Key_" + i; string value = "Value" + i * 2; if (i == 0) { stringDictionary[key.ToUpperInvariant()] = value.ToUpperInvariant(); Assert.False(stringDictionary.ContainsValue(value)); Assert.True(stringDictionary.ContainsValue(value.ToUpperInvariant())); Assert.False(stringDictionary.ContainsValue(value.ToLowerInvariant())); } else if (i == 1) { stringDictionary[key.ToLowerInvariant()] = value.ToLowerInvariant(); Assert.False(stringDictionary.ContainsValue(value)); Assert.False(stringDictionary.ContainsValue(value.ToUpperInvariant())); Assert.True(stringDictionary.ContainsValue(value.ToLowerInvariant())); } else { stringDictionary[key] = value; Assert.True(stringDictionary.ContainsValue(value)); Assert.False(stringDictionary.ContainsValue(value.ToUpperInvariant())); Assert.False(stringDictionary.ContainsValue(value.ToLowerInvariant())); } Assert.True(stringDictionary.ContainsKey(key)); Assert.Equal(count, stringDictionary.Count); } stringDictionary["new-key"] = "new-value"; Assert.Equal(count + 1, stringDictionary.Count); Assert.True(stringDictionary.ContainsKey("new-key")); Assert.True(stringDictionary.ContainsValue("new-value")); Assert.Equal("new-value", stringDictionary["new-key"]); stringDictionary["new-null-key"] = null; Assert.Equal(count + 2, stringDictionary.Count); Assert.True(stringDictionary.ContainsKey("new-null-key")); Assert.True(stringDictionary.ContainsValue(null)); Assert.Null(stringDictionary["new-null-key"]); } [Fact] public void Item_Set_IsCaseInsensitive() { StringDictionary stringDictionary = new StringDictionary(); stringDictionary["KEY"] = "value1"; stringDictionary["kEy"] = "value2"; stringDictionary["key"] = "value3"; Assert.Equal(1, stringDictionary.Count); Assert.Equal("value3", stringDictionary["key"]); } [Theory] [InlineData(0)] [InlineData(5)] public void Item_Set_NullKey_ThrowsArgumentNullException(int count) { StringDictionary stringDictionary = Helpers.CreateStringDictionary(count); AssertExtensions.Throws<ArgumentNullException>("key", () => stringDictionary[null] = "value"); } } }
// 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.Collections.Specialized.Tests { public class StringDictionaryItemSetTests { [Theory] [InlineData(0)] [InlineData(5)] public void Item_Set(int count) { StringDictionary stringDictionary = Helpers.CreateStringDictionary(count); for (int i = 0; i < stringDictionary.Count; i++) { string key = "Key_" + i; string value = "Value" + i * 2; if (i == 0) { stringDictionary[key.ToUpperInvariant()] = value.ToUpperInvariant(); Assert.False(stringDictionary.ContainsValue(value)); Assert.True(stringDictionary.ContainsValue(value.ToUpperInvariant())); Assert.False(stringDictionary.ContainsValue(value.ToLowerInvariant())); } else if (i == 1) { stringDictionary[key.ToLowerInvariant()] = value.ToLowerInvariant(); Assert.False(stringDictionary.ContainsValue(value)); Assert.False(stringDictionary.ContainsValue(value.ToUpperInvariant())); Assert.True(stringDictionary.ContainsValue(value.ToLowerInvariant())); } else { stringDictionary[key] = value; Assert.True(stringDictionary.ContainsValue(value)); Assert.False(stringDictionary.ContainsValue(value.ToUpperInvariant())); Assert.False(stringDictionary.ContainsValue(value.ToLowerInvariant())); } Assert.True(stringDictionary.ContainsKey(key)); Assert.Equal(count, stringDictionary.Count); } stringDictionary["new-key"] = "new-value"; Assert.Equal(count + 1, stringDictionary.Count); Assert.True(stringDictionary.ContainsKey("new-key")); Assert.True(stringDictionary.ContainsValue("new-value")); Assert.Equal("new-value", stringDictionary["new-key"]); stringDictionary["new-null-key"] = null; Assert.Equal(count + 2, stringDictionary.Count); Assert.True(stringDictionary.ContainsKey("new-null-key")); Assert.True(stringDictionary.ContainsValue(null)); Assert.Null(stringDictionary["new-null-key"]); } [Fact] public void Item_Set_IsCaseInsensitive() { StringDictionary stringDictionary = new StringDictionary(); stringDictionary["KEY"] = "value1"; stringDictionary["kEy"] = "value2"; stringDictionary["key"] = "value3"; Assert.Equal(1, stringDictionary.Count); Assert.Equal("value3", stringDictionary["key"]); } [Theory] [InlineData(0)] [InlineData(5)] public void Item_Set_NullKey_ThrowsArgumentNullException(int count) { StringDictionary stringDictionary = Helpers.CreateStringDictionary(count); AssertExtensions.Throws<ArgumentNullException>("key", () => stringDictionary[null] = "value"); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/Interop/PInvoke/BestFitMapping/Assembly_True_True/AssemblyInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; [assembly: BestFitMapping(true, ThrowOnUnmappableChar = 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.Runtime.InteropServices; [assembly: BestFitMapping(true, ThrowOnUnmappableChar = true)]
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Memory/tests/ReadOnlyMemory/ToArray.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.MemoryTests { public static partial class ReadOnlyMemoryTests { [Fact] public static void ToArray1() { int[] a = { 91, 92, 93 }; var memory = new ReadOnlyMemory<int>(a); int[] copy = memory.ToArray(); Assert.Equal<int>(a, copy); Assert.NotSame(a, copy); } [Fact] public static void ToArrayWithIndex() { int[] a = { 91, 92, 93, 94, 95 }; var memory = new Memory<int>(a); int[] copy = memory.Slice(2).ToArray(); Assert.Equal<int>(new int[] { 93, 94, 95 }, copy); } [Fact] public static void ToArrayWithIndexAndLength() { int[] a = { 91, 92, 93 }; var memory = new Memory<int>(a, 1, 1); int[] copy = memory.ToArray(); Assert.Equal<int>(new int[] { 92 }, copy); } [Fact] public static void ToArrayEmpty() { ReadOnlyMemory<int> memory = ReadOnlyMemory<int>.Empty; int[] copy = memory.ToArray(); Assert.Equal(0, copy.Length); } [Fact] public static void ToArrayDefault() { ReadOnlyMemory<int> memory = default; int[] copy = memory.ToArray(); Assert.Equal(0, copy.Length); } } }
// 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.MemoryTests { public static partial class ReadOnlyMemoryTests { [Fact] public static void ToArray1() { int[] a = { 91, 92, 93 }; var memory = new ReadOnlyMemory<int>(a); int[] copy = memory.ToArray(); Assert.Equal<int>(a, copy); Assert.NotSame(a, copy); } [Fact] public static void ToArrayWithIndex() { int[] a = { 91, 92, 93, 94, 95 }; var memory = new Memory<int>(a); int[] copy = memory.Slice(2).ToArray(); Assert.Equal<int>(new int[] { 93, 94, 95 }, copy); } [Fact] public static void ToArrayWithIndexAndLength() { int[] a = { 91, 92, 93 }; var memory = new Memory<int>(a, 1, 1); int[] copy = memory.ToArray(); Assert.Equal<int>(new int[] { 92 }, copy); } [Fact] public static void ToArrayEmpty() { ReadOnlyMemory<int> memory = ReadOnlyMemory<int>.Empty; int[] copy = memory.ToArray(); Assert.Equal(0, copy.Length); } [Fact] public static void ToArrayDefault() { ReadOnlyMemory<int> memory = default; int[] copy = memory.ToArray(); Assert.Equal(0, copy.Length); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/UInt16Converter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Text.Json.Serialization.Converters { internal sealed class UInt16Converter : JsonConverter<ushort> { public UInt16Converter() { IsInternalConverterForNumberType = true; } public override ushort Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetUInt16(); } public override void Write(Utf8JsonWriter writer, ushort value, JsonSerializerOptions options) { // For performance, lift up the writer implementation. writer.WriteNumberValue((long)value); } internal override ushort ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetUInt16WithQuotes(); } internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, ushort value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) { writer.WritePropertyName(value); } internal override ushort ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != 0) { return reader.GetUInt16WithQuotes(); } return reader.GetUInt16(); } internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, ushort value, JsonNumberHandling handling) { if ((JsonNumberHandling.WriteAsString & handling) != 0) { writer.WriteNumberValueAsString(value); } else { // For performance, lift up the writer implementation. writer.WriteNumberValue((long)value); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Text.Json.Serialization.Converters { internal sealed class UInt16Converter : JsonConverter<ushort> { public UInt16Converter() { IsInternalConverterForNumberType = true; } public override ushort Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetUInt16(); } public override void Write(Utf8JsonWriter writer, ushort value, JsonSerializerOptions options) { // For performance, lift up the writer implementation. writer.WriteNumberValue((long)value); } internal override ushort ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetUInt16WithQuotes(); } internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, ushort value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) { writer.WritePropertyName(value); } internal override ushort ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != 0) { return reader.GetUInt16WithQuotes(); } return reader.GetUInt16(); } internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, ushort value, JsonNumberHandling handling) { if ((JsonNumberHandling.WriteAsString & handling) != 0) { writer.WriteNumberValueAsString(value); } else { // For performance, lift up the writer implementation. writer.WriteNumberValue((long)value); } } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Runtime/tests/System/DoubleTests.GenericMath.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.Runtime.Versioning; using Xunit; namespace System.Tests { [RequiresPreviewFeaturesAttribute] public class DoubleTests_GenericMath { [Theory] [MemberData(nameof(DoubleTests.Parse_Valid_TestData), MemberType = typeof(DoubleTests))] public static void ParseValidStringTest(string value, NumberStyles style, IFormatProvider provider, double expected) { bool isDefaultProvider = provider == null || provider == NumberFormatInfo.CurrentInfo; double result; if ((style & ~(NumberStyles.Float | NumberStyles.AllowThousands)) == 0 && style != NumberStyles.None) { // Use Parse(string) or Parse(string, IFormatProvider) if (isDefaultProvider) { Assert.True(NumberHelper<double>.TryParse(value, null, out result)); Assert.Equal(expected, result); Assert.Equal(expected, NumberHelper<double>.Parse(value, null)); } Assert.Equal(expected, NumberHelper<double>.Parse(value, provider)); } // Use Parse(string, NumberStyles, IFormatProvider) Assert.True(NumberHelper<double>.TryParse(value, style, provider, out result)); Assert.Equal(expected, result); Assert.Equal(expected, NumberHelper<double>.Parse(value, style, provider)); if (isDefaultProvider) { // Use Parse(string, NumberStyles) or Parse(string, NumberStyles, IFormatProvider) Assert.True(NumberHelper<double>.TryParse(value, style, NumberFormatInfo.CurrentInfo, out result)); Assert.Equal(expected, result); Assert.Equal(expected, NumberHelper<double>.Parse(value, style, null)); Assert.Equal(expected, NumberHelper<double>.Parse(value, style, NumberFormatInfo.CurrentInfo)); } } [Theory] [MemberData(nameof(DoubleTests.Parse_Invalid_TestData), MemberType = typeof(DoubleTests))] public static void ParseInvalidStringTest(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { bool isDefaultProvider = provider == null || provider == NumberFormatInfo.CurrentInfo; double result; if ((style & ~(NumberStyles.Float | NumberStyles.AllowThousands)) == 0 && style != NumberStyles.None && (style & NumberStyles.AllowLeadingWhite) == (style & NumberStyles.AllowTrailingWhite)) { // Use Parse(string) or Parse(string, IFormatProvider) if (isDefaultProvider) { Assert.False(NumberHelper<double>.TryParse(value, null, out result)); Assert.Equal(default(double), result); Assert.Throws(exceptionType, () => NumberHelper<double>.Parse(value, null)); } Assert.Throws(exceptionType, () => NumberHelper<double>.Parse(value, provider)); } // Use Parse(string, NumberStyles, IFormatProvider) Assert.False(NumberHelper<double>.TryParse(value, style, provider, out result)); Assert.Equal(default(double), result); Assert.Throws(exceptionType, () => NumberHelper<double>.Parse(value, style, provider)); if (isDefaultProvider) { // Use Parse(string, NumberStyles) or Parse(string, NumberStyles, IFormatProvider) Assert.False(NumberHelper<double>.TryParse(value, style, NumberFormatInfo.CurrentInfo, out result)); Assert.Equal(default(double), result); Assert.Throws(exceptionType, () => NumberHelper<double>.Parse(value, style, null)); Assert.Throws(exceptionType, () => NumberHelper<double>.Parse(value, style, NumberFormatInfo.CurrentInfo)); } } [Theory] [MemberData(nameof(DoubleTests.Parse_ValidWithOffsetCount_TestData), MemberType = typeof(DoubleTests))] public static void ParseValidSpanTest(string value, int offset, int count, NumberStyles style, IFormatProvider provider, double expected) { bool isDefaultProvider = provider == null || provider == NumberFormatInfo.CurrentInfo; double result; if ((style & ~(NumberStyles.Float | NumberStyles.AllowThousands)) == 0 && style != NumberStyles.None) { // Use Parse(string) or Parse(string, IFormatProvider) if (isDefaultProvider) { Assert.True(NumberHelper<double>.TryParse(value.AsSpan(offset, count), null, out result)); Assert.Equal(expected, result); Assert.Equal(expected, NumberHelper<double>.Parse(value.AsSpan(offset, count), null)); } Assert.Equal(expected, NumberHelper<double>.Parse(value.AsSpan(offset, count), provider: provider)); } Assert.Equal(expected, NumberHelper<double>.Parse(value.AsSpan(offset, count), style, provider)); Assert.True(NumberHelper<double>.TryParse(value.AsSpan(offset, count), style, provider, out result)); Assert.Equal(expected, result); } [Theory] [MemberData(nameof(DoubleTests.Parse_Invalid_TestData), MemberType = typeof(DoubleTests))] public static void ParseInvalidSpanTest(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { if (value != null) { Assert.Throws(exceptionType, () => NumberHelper<double>.Parse(value.AsSpan(), style, provider)); Assert.False(NumberHelper<double>.TryParse(value.AsSpan(), style, provider, out double result)); Assert.Equal(0, result); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; using System.Runtime.Versioning; using Xunit; namespace System.Tests { [RequiresPreviewFeaturesAttribute] public class DoubleTests_GenericMath { [Theory] [MemberData(nameof(DoubleTests.Parse_Valid_TestData), MemberType = typeof(DoubleTests))] public static void ParseValidStringTest(string value, NumberStyles style, IFormatProvider provider, double expected) { bool isDefaultProvider = provider == null || provider == NumberFormatInfo.CurrentInfo; double result; if ((style & ~(NumberStyles.Float | NumberStyles.AllowThousands)) == 0 && style != NumberStyles.None) { // Use Parse(string) or Parse(string, IFormatProvider) if (isDefaultProvider) { Assert.True(NumberHelper<double>.TryParse(value, null, out result)); Assert.Equal(expected, result); Assert.Equal(expected, NumberHelper<double>.Parse(value, null)); } Assert.Equal(expected, NumberHelper<double>.Parse(value, provider)); } // Use Parse(string, NumberStyles, IFormatProvider) Assert.True(NumberHelper<double>.TryParse(value, style, provider, out result)); Assert.Equal(expected, result); Assert.Equal(expected, NumberHelper<double>.Parse(value, style, provider)); if (isDefaultProvider) { // Use Parse(string, NumberStyles) or Parse(string, NumberStyles, IFormatProvider) Assert.True(NumberHelper<double>.TryParse(value, style, NumberFormatInfo.CurrentInfo, out result)); Assert.Equal(expected, result); Assert.Equal(expected, NumberHelper<double>.Parse(value, style, null)); Assert.Equal(expected, NumberHelper<double>.Parse(value, style, NumberFormatInfo.CurrentInfo)); } } [Theory] [MemberData(nameof(DoubleTests.Parse_Invalid_TestData), MemberType = typeof(DoubleTests))] public static void ParseInvalidStringTest(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { bool isDefaultProvider = provider == null || provider == NumberFormatInfo.CurrentInfo; double result; if ((style & ~(NumberStyles.Float | NumberStyles.AllowThousands)) == 0 && style != NumberStyles.None && (style & NumberStyles.AllowLeadingWhite) == (style & NumberStyles.AllowTrailingWhite)) { // Use Parse(string) or Parse(string, IFormatProvider) if (isDefaultProvider) { Assert.False(NumberHelper<double>.TryParse(value, null, out result)); Assert.Equal(default(double), result); Assert.Throws(exceptionType, () => NumberHelper<double>.Parse(value, null)); } Assert.Throws(exceptionType, () => NumberHelper<double>.Parse(value, provider)); } // Use Parse(string, NumberStyles, IFormatProvider) Assert.False(NumberHelper<double>.TryParse(value, style, provider, out result)); Assert.Equal(default(double), result); Assert.Throws(exceptionType, () => NumberHelper<double>.Parse(value, style, provider)); if (isDefaultProvider) { // Use Parse(string, NumberStyles) or Parse(string, NumberStyles, IFormatProvider) Assert.False(NumberHelper<double>.TryParse(value, style, NumberFormatInfo.CurrentInfo, out result)); Assert.Equal(default(double), result); Assert.Throws(exceptionType, () => NumberHelper<double>.Parse(value, style, null)); Assert.Throws(exceptionType, () => NumberHelper<double>.Parse(value, style, NumberFormatInfo.CurrentInfo)); } } [Theory] [MemberData(nameof(DoubleTests.Parse_ValidWithOffsetCount_TestData), MemberType = typeof(DoubleTests))] public static void ParseValidSpanTest(string value, int offset, int count, NumberStyles style, IFormatProvider provider, double expected) { bool isDefaultProvider = provider == null || provider == NumberFormatInfo.CurrentInfo; double result; if ((style & ~(NumberStyles.Float | NumberStyles.AllowThousands)) == 0 && style != NumberStyles.None) { // Use Parse(string) or Parse(string, IFormatProvider) if (isDefaultProvider) { Assert.True(NumberHelper<double>.TryParse(value.AsSpan(offset, count), null, out result)); Assert.Equal(expected, result); Assert.Equal(expected, NumberHelper<double>.Parse(value.AsSpan(offset, count), null)); } Assert.Equal(expected, NumberHelper<double>.Parse(value.AsSpan(offset, count), provider: provider)); } Assert.Equal(expected, NumberHelper<double>.Parse(value.AsSpan(offset, count), style, provider)); Assert.True(NumberHelper<double>.TryParse(value.AsSpan(offset, count), style, provider, out result)); Assert.Equal(expected, result); } [Theory] [MemberData(nameof(DoubleTests.Parse_Invalid_TestData), MemberType = typeof(DoubleTests))] public static void ParseInvalidSpanTest(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { if (value != null) { Assert.Throws(exceptionType, () => NumberHelper<double>.Parse(value.AsSpan(), style, provider)); Assert.False(NumberHelper<double>.TryParse(value.AsSpan(), style, provider, out double result)); Assert.Equal(0, result); } } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/Assignment.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.CSharp.RuntimeBinder.Semantics { internal sealed class ExprAssignment : Expr { private Expr _lhs; public ExprAssignment(Expr lhs, Expr rhs) : base(ExpressionKind.Assignment) { LHS = lhs; RHS = rhs; Flags = EXPRFLAG.EXF_ASSGOP; } public Expr LHS { get => _lhs; set => Type = (_lhs = value).Type; } public Expr RHS { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed class ExprAssignment : Expr { private Expr _lhs; public ExprAssignment(Expr lhs, Expr rhs) : base(ExpressionKind.Assignment) { LHS = lhs; RHS = rhs; Flags = EXPRFLAG.EXF_ASSGOP; } public Expr LHS { get => _lhs; set => Type = (_lhs = value).Type; } public Expr RHS { get; set; } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyAddBySelectedScalar.Vector64.Int16.Vector128.Int16.7.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 MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7() { var test = new SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7(); 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 SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] inArray3, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int16, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int16> _fld1; public Vector64<Int16> _fld2; public Vector128<Int16> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7 testClass) { var result = AdvSimd.MultiplyAddBySelectedScalar(_fld1, _fld2, _fld3, 7); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7 testClass) { fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) fixed (Vector128<Int16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)), 7 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly byte Imm = 7; private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Int16[] _data3 = new Int16[Op3ElementCount]; private static Vector64<Int16> _clsVar1; private static Vector64<Int16> _clsVar2; private static Vector128<Int16> _clsVar3; private Vector64<Int16> _fld1; private Vector64<Int16> _fld2; private Vector128<Int16> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyAddBySelectedScalar( Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyAddBySelectedScalar), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>), typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr), (byte)7 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyAddBySelectedScalar), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>), typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)), (byte)7 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyAddBySelectedScalar( _clsVar1, _clsVar2, _clsVar3, 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int16>* pClsVar1 = &_clsVar1) fixed (Vector64<Int16>* pClsVar2 = &_clsVar2) fixed (Vector128<Int16>* pClsVar3 = &_clsVar3) { var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(pClsVar1)), AdvSimd.LoadVector64((Int16*)(pClsVar2)), AdvSimd.LoadVector128((Int16*)(pClsVar3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr); var result = AdvSimd.MultiplyAddBySelectedScalar(op1, op2, op3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)); var result = AdvSimd.MultiplyAddBySelectedScalar(op1, op2, op3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7(); var result = AdvSimd.MultiplyAddBySelectedScalar(test._fld1, test._fld2, test._fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7(); fixed (Vector64<Int16>* pFld1 = &test._fld1) fixed (Vector64<Int16>* pFld2 = &test._fld2) fixed (Vector128<Int16>* pFld3 = &test._fld3) { var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyAddBySelectedScalar(_fld1, _fld2, _fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) fixed (Vector128<Int16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyAddBySelectedScalar(test._fld1, test._fld2, test._fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(&test._fld1)), AdvSimd.LoadVector64((Int16*)(&test._fld2)), AdvSimd.LoadVector128((Int16*)(&test._fld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int16> op1, Vector64<Int16> op2, Vector128<Int16> op3, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] inArray3 = new Int16[Op3ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] inArray3 = new Int16[Op3ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] secondOp, Int16[] thirdOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyAdd(firstOp[i], secondOp[i], thirdOp[Imm]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyAddBySelectedScalar)}<Int16>(Vector64<Int16>, Vector64<Int16>, Vector128<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7() { var test = new SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7(); 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 SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] inArray3, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int16, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int16> _fld1; public Vector64<Int16> _fld2; public Vector128<Int16> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7 testClass) { var result = AdvSimd.MultiplyAddBySelectedScalar(_fld1, _fld2, _fld3, 7); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7 testClass) { fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) fixed (Vector128<Int16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)), 7 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly byte Imm = 7; private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Int16[] _data3 = new Int16[Op3ElementCount]; private static Vector64<Int16> _clsVar1; private static Vector64<Int16> _clsVar2; private static Vector128<Int16> _clsVar3; private Vector64<Int16> _fld1; private Vector64<Int16> _fld2; private Vector128<Int16> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyAddBySelectedScalar( Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyAddBySelectedScalar), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>), typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr), (byte)7 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyAddBySelectedScalar), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>), typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)), (byte)7 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyAddBySelectedScalar( _clsVar1, _clsVar2, _clsVar3, 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int16>* pClsVar1 = &_clsVar1) fixed (Vector64<Int16>* pClsVar2 = &_clsVar2) fixed (Vector128<Int16>* pClsVar3 = &_clsVar3) { var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(pClsVar1)), AdvSimd.LoadVector64((Int16*)(pClsVar2)), AdvSimd.LoadVector128((Int16*)(pClsVar3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr); var result = AdvSimd.MultiplyAddBySelectedScalar(op1, op2, op3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)); var result = AdvSimd.MultiplyAddBySelectedScalar(op1, op2, op3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7(); var result = AdvSimd.MultiplyAddBySelectedScalar(test._fld1, test._fld2, test._fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7(); fixed (Vector64<Int16>* pFld1 = &test._fld1) fixed (Vector64<Int16>* pFld2 = &test._fld2) fixed (Vector128<Int16>* pFld3 = &test._fld3) { var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyAddBySelectedScalar(_fld1, _fld2, _fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) fixed (Vector128<Int16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyAddBySelectedScalar(test._fld1, test._fld2, test._fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(&test._fld1)), AdvSimd.LoadVector64((Int16*)(&test._fld2)), AdvSimd.LoadVector128((Int16*)(&test._fld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int16> op1, Vector64<Int16> op2, Vector128<Int16> op3, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] inArray3 = new Int16[Op3ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] inArray3 = new Int16[Op3ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] secondOp, Int16[] thirdOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyAdd(firstOp[i], secondOp[i], thirdOp[Imm]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyAddBySelectedScalar)}<Int16>(Vector64<Int16>, Vector64<Int16>, Vector128<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Private.CoreLib/src/Internal/Console.Android.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; namespace Internal { public static partial class Console { public static unsafe void Write(string s) { Interop.Logcat.AndroidLogPrint(Interop.Logcat.LogLevel.Debug, "DOTNET", s ?? string.Empty); } public static partial class Error { public static unsafe void Write(string s) { Interop.Logcat.AndroidLogPrint(Interop.Logcat.LogLevel.Error, "DOTNET", s ?? string.Empty); } } } }
// 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; namespace Internal { public static partial class Console { public static unsafe void Write(string s) { Interop.Logcat.AndroidLogPrint(Interop.Logcat.LogLevel.Debug, "DOTNET", s ?? string.Empty); } public static partial class Error { public static unsafe void Write(string s) { Interop.Logcat.AndroidLogPrint(Interop.Logcat.LogLevel.Error, "DOTNET", s ?? string.Empty); } } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LsaNtStatusToWinError.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; internal static partial class Interop { internal static partial class Advapi32 { [GeneratedDllImport(Interop.Libraries.Advapi32, SetLastError = false)] internal static partial uint LsaNtStatusToWinError(uint 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; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Advapi32 { [GeneratedDllImport(Interop.Libraries.Advapi32, SetLastError = false)] internal static partial uint LsaNtStatusToWinError(uint status); } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/Methodical/Invoke/25params/25param2a_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="25param2a.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="25param2a.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Security.Permissions/src/System/Security/Policy/FileCodeGroup.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Policy { #if NETCOREAPP [Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] #endif public sealed partial class FileCodeGroup : CodeGroup { public FileCodeGroup(IMembershipCondition membershipCondition, Permissions.FileIOPermissionAccess access) : base(default(IMembershipCondition), default(PolicyStatement)) { } public override string AttributeString { get { return null; } } public override string MergeLogic { get { return null; } } public override string PermissionSetName { get { return null; } } public override CodeGroup Copy() { return default(CodeGroup); } protected override void CreateXml(SecurityElement element, PolicyLevel level) { } public override bool Equals(object o) => base.Equals(o); public override int GetHashCode() => base.GetHashCode(); protected override void ParseXml(SecurityElement e, PolicyLevel level) { } public override PolicyStatement Resolve(Evidence evidence) { return default(PolicyStatement); } public override CodeGroup ResolveMatchingCodeGroups(Evidence evidence) { return default(CodeGroup); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Policy { #if NETCOREAPP [Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] #endif public sealed partial class FileCodeGroup : CodeGroup { public FileCodeGroup(IMembershipCondition membershipCondition, Permissions.FileIOPermissionAccess access) : base(default(IMembershipCondition), default(PolicyStatement)) { } public override string AttributeString { get { return null; } } public override string MergeLogic { get { return null; } } public override string PermissionSetName { get { return null; } } public override CodeGroup Copy() { return default(CodeGroup); } protected override void CreateXml(SecurityElement element, PolicyLevel level) { } public override bool Equals(object o) => base.Equals(o); public override int GetHashCode() => base.GetHashCode(); protected override void ParseXml(SecurityElement e, PolicyLevel level) { } public override PolicyStatement Resolve(Evidence evidence) { return default(PolicyStatement); } public override CodeGroup ResolveMatchingCodeGroups(Evidence evidence) { return default(CodeGroup); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderMap.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Formats.Cbor; using System.Runtime.Versioning; namespace System.Security.Cryptography.Cose { public sealed class CoseHeaderMap : IEnumerable<(CoseHeaderLabel Label, ReadOnlyMemory<byte> EncodedValue)> { private static readonly byte[] s_emptyBstrEncoded = new byte[] { 0x40 }; public bool IsReadOnly { get; internal set; } private readonly Dictionary<CoseHeaderLabel, ReadOnlyMemory<byte>> _headerParameters = new Dictionary<CoseHeaderLabel, ReadOnlyMemory<byte>>(); public CoseHeaderMap() : this (isReadOnly: false) { } internal CoseHeaderMap(bool isReadOnly) { IsReadOnly = isReadOnly; } public bool TryGetEncodedValue(CoseHeaderLabel label, out ReadOnlyMemory<byte> encodedValue) => _headerParameters.TryGetValue(label, out encodedValue); public ReadOnlyMemory<byte> GetEncodedValue(CoseHeaderLabel label) { if (TryGetEncodedValue(label, out ReadOnlyMemory<byte> encodedValue)) { return encodedValue; } throw new InvalidOperationException(SR.Format(SR.CoseHeaderMapLabelDoeNotExist, label.LabelName)); } public int GetValueAsInt32(CoseHeaderLabel label) { var reader = new CborReader(GetEncodedValue(label)); int retVal = reader.ReadInt32(); Debug.Assert(reader.BytesRemaining == 0); return retVal; } public string GetValueAsString(CoseHeaderLabel label) { var reader = new CborReader(GetEncodedValue(label)); string retVal = reader.ReadTextString(); Debug.Assert(reader.BytesRemaining == 0); return retVal; } public ReadOnlySpan<byte> GetValueAsBytes(CoseHeaderLabel label) { var reader = new CborReader(GetEncodedValue(label)); ReadOnlySpan<byte> retVal = reader.ReadByteString(); Debug.Assert(reader.BytesRemaining == 0); return retVal; } public void SetEncodedValue(CoseHeaderLabel label, ReadOnlySpan<byte> encodedValue) => SetEncodedValue(label, new ReadOnlyMemory<byte>(encodedValue.ToArray())); internal void SetEncodedValue(CoseHeaderLabel label, ReadOnlyMemory<byte> encodedValue) { ValidateIsReadOnly(); ValidateHeaderValue(label, null, encodedValue); _headerParameters[label] = encodedValue; } public void SetValue(CoseHeaderLabel label, int value) { ValidateIsReadOnly(); ValidateHeaderValue(label, value < 0 ? CborReaderState.NegativeInteger : CborReaderState.UnsignedInteger, null); var writer = new CborWriter(); writer.WriteInt32(value); _headerParameters[label] = writer.Encode(); } public void SetValue(CoseHeaderLabel label, string value) { ValidateIsReadOnly(); ValidateHeaderValue(label, CborReaderState.TextString, null); var writer = new CborWriter(); writer.WriteTextString(value); _headerParameters[label] = writer.Encode(); } public void SetValue(CoseHeaderLabel label, ReadOnlySpan<byte> value) { ValidateIsReadOnly(); ValidateHeaderValue(label, CborReaderState.ByteString, null); var writer = new CborWriter(); writer.WriteByteString(value); _headerParameters[label] = writer.Encode(); } public void Remove(CoseHeaderLabel label) { ValidateIsReadOnly(); _headerParameters.Remove(label); } private void ValidateIsReadOnly() { if (IsReadOnly) { throw new InvalidOperationException(SR.CoseHeaderMapDecodedMapIsReadOnlyCannotSetValue); } } private void ValidateHeaderValue(CoseHeaderLabel label, CborReaderState? state, ReadOnlyMemory<byte>? encodedValue) { if (state != null) { Debug.Assert(encodedValue == null); if (label.LabelAsString == null) { // all known headers are integers. ValidateKnownHeaderValue(label.LabelAsInt32, state, null); } } else { Debug.Assert(encodedValue != null); var reader = new CborReader(encodedValue.Value); if (label.LabelAsString == null) { // all known headers are integers. ValidateKnownHeaderValue(label.LabelAsInt32, reader.PeekState(), reader); } else { reader.SkipValue(); } if (reader.BytesRemaining != 0) { throw new InvalidOperationException(SR.Format(SR.CoseHeaderMapCborEncodedValueNotValid, label)); } } static void ValidateKnownHeaderValue(int label, CborReaderState? initialState, CborReader? reader) { switch (label) { case KnownHeaders.Alg: if (initialState != CborReaderState.NegativeInteger && initialState != CborReaderState.UnsignedInteger && initialState != CborReaderState.TextString) { throw new InvalidOperationException(SR.Format(SR.CoseHeaderMapHeaderDoesNotAcceptSpecifiedValue, label)); } reader?.SkipValue(); break; case KnownHeaders.Crit: reader?.SkipValue(); // TODO break; case KnownHeaders.CounterSignature: reader?.SkipValue(); // TODO break; case KnownHeaders.ContentType: if (initialState != CborReaderState.TextString && initialState != CborReaderState.UnsignedInteger) { throw new InvalidOperationException(SR.Format(SR.CoseHeaderMapHeaderDoesNotAcceptSpecifiedValue, label)); } reader?.SkipValue(); break; case KnownHeaders.Kid: case KnownHeaders.IV: case KnownHeaders.PartialIV: if (initialState != CborReaderState.ByteString) { throw new InvalidOperationException(SR.Format(SR.CoseHeaderMapHeaderDoesNotAcceptSpecifiedValue, label)); } reader?.SkipValue(); break; default: reader?.SkipValue(); break; } } } internal byte[] Encode(bool mustReturnEmptyBstrIfEmpty = false, int? algHeaderValueToSlip = null) { bool shouldSlipAlgHeader = algHeaderValueToSlip.HasValue; if (_headerParameters.Count == 0 && mustReturnEmptyBstrIfEmpty && !shouldSlipAlgHeader) { return s_emptyBstrEncoded; } int mapLength = _headerParameters.Count; if (shouldSlipAlgHeader) { mapLength++; } var writer = new CborWriter(); writer.WriteStartMap(mapLength); if (shouldSlipAlgHeader) { Debug.Assert(!TryGetEncodedValue(CoseHeaderLabel.Algorithm, out _)); writer.WriteInt32(KnownHeaders.Alg); writer.WriteInt32(algHeaderValueToSlip!.Value); } foreach ((CoseHeaderLabel Label, ReadOnlyMemory<byte> EncodedValue) header in this) { CoseHeaderLabel label = header.Label; if (label.LabelAsString == null) { writer.WriteInt32(label.LabelAsInt32); } else { writer.WriteTextString(label.LabelAsString); } writer.WriteEncodedValue(header.EncodedValue.Span); } writer.WriteEndMap(); return writer.Encode(); } public Enumerator GetEnumerator() => new Enumerator(_headerParameters.GetEnumerator()); IEnumerator<(CoseHeaderLabel Label, ReadOnlyMemory<byte> EncodedValue)> IEnumerable<(CoseHeaderLabel Label, ReadOnlyMemory<byte> EncodedValue)>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public struct Enumerator : IEnumerator<(CoseHeaderLabel Label, ReadOnlyMemory<byte> EncodedValue)> { private Dictionary<CoseHeaderLabel, ReadOnlyMemory<byte>>.Enumerator _dictionaryEnumerator; internal Enumerator(Dictionary<CoseHeaderLabel, ReadOnlyMemory<byte>>.Enumerator dictionaryEnumerator) { _dictionaryEnumerator = dictionaryEnumerator; } public readonly (CoseHeaderLabel Label, ReadOnlyMemory<byte> EncodedValue) Current => (_dictionaryEnumerator.Current.Key, _dictionaryEnumerator.Current.Value); object IEnumerator.Current => Current; public void Dispose() => _dictionaryEnumerator.Dispose(); public bool MoveNext() => _dictionaryEnumerator.MoveNext(); public void Reset() => ((IEnumerator)_dictionaryEnumerator).Reset(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Formats.Cbor; using System.Runtime.Versioning; namespace System.Security.Cryptography.Cose { public sealed class CoseHeaderMap : IEnumerable<(CoseHeaderLabel Label, ReadOnlyMemory<byte> EncodedValue)> { private static readonly byte[] s_emptyBstrEncoded = new byte[] { 0x40 }; public bool IsReadOnly { get; internal set; } private readonly Dictionary<CoseHeaderLabel, ReadOnlyMemory<byte>> _headerParameters = new Dictionary<CoseHeaderLabel, ReadOnlyMemory<byte>>(); public CoseHeaderMap() : this (isReadOnly: false) { } internal CoseHeaderMap(bool isReadOnly) { IsReadOnly = isReadOnly; } public bool TryGetEncodedValue(CoseHeaderLabel label, out ReadOnlyMemory<byte> encodedValue) => _headerParameters.TryGetValue(label, out encodedValue); public ReadOnlyMemory<byte> GetEncodedValue(CoseHeaderLabel label) { if (TryGetEncodedValue(label, out ReadOnlyMemory<byte> encodedValue)) { return encodedValue; } throw new InvalidOperationException(SR.Format(SR.CoseHeaderMapLabelDoeNotExist, label.LabelName)); } public int GetValueAsInt32(CoseHeaderLabel label) { var reader = new CborReader(GetEncodedValue(label)); int retVal = reader.ReadInt32(); Debug.Assert(reader.BytesRemaining == 0); return retVal; } public string GetValueAsString(CoseHeaderLabel label) { var reader = new CborReader(GetEncodedValue(label)); string retVal = reader.ReadTextString(); Debug.Assert(reader.BytesRemaining == 0); return retVal; } public ReadOnlySpan<byte> GetValueAsBytes(CoseHeaderLabel label) { var reader = new CborReader(GetEncodedValue(label)); ReadOnlySpan<byte> retVal = reader.ReadByteString(); Debug.Assert(reader.BytesRemaining == 0); return retVal; } public void SetEncodedValue(CoseHeaderLabel label, ReadOnlySpan<byte> encodedValue) => SetEncodedValue(label, new ReadOnlyMemory<byte>(encodedValue.ToArray())); internal void SetEncodedValue(CoseHeaderLabel label, ReadOnlyMemory<byte> encodedValue) { ValidateIsReadOnly(); ValidateHeaderValue(label, null, encodedValue); _headerParameters[label] = encodedValue; } public void SetValue(CoseHeaderLabel label, int value) { ValidateIsReadOnly(); ValidateHeaderValue(label, value < 0 ? CborReaderState.NegativeInteger : CborReaderState.UnsignedInteger, null); var writer = new CborWriter(); writer.WriteInt32(value); _headerParameters[label] = writer.Encode(); } public void SetValue(CoseHeaderLabel label, string value) { ValidateIsReadOnly(); ValidateHeaderValue(label, CborReaderState.TextString, null); var writer = new CborWriter(); writer.WriteTextString(value); _headerParameters[label] = writer.Encode(); } public void SetValue(CoseHeaderLabel label, ReadOnlySpan<byte> value) { ValidateIsReadOnly(); ValidateHeaderValue(label, CborReaderState.ByteString, null); var writer = new CborWriter(); writer.WriteByteString(value); _headerParameters[label] = writer.Encode(); } public void Remove(CoseHeaderLabel label) { ValidateIsReadOnly(); _headerParameters.Remove(label); } private void ValidateIsReadOnly() { if (IsReadOnly) { throw new InvalidOperationException(SR.CoseHeaderMapDecodedMapIsReadOnlyCannotSetValue); } } private void ValidateHeaderValue(CoseHeaderLabel label, CborReaderState? state, ReadOnlyMemory<byte>? encodedValue) { if (state != null) { Debug.Assert(encodedValue == null); if (label.LabelAsString == null) { // all known headers are integers. ValidateKnownHeaderValue(label.LabelAsInt32, state, null); } } else { Debug.Assert(encodedValue != null); var reader = new CborReader(encodedValue.Value); if (label.LabelAsString == null) { // all known headers are integers. ValidateKnownHeaderValue(label.LabelAsInt32, reader.PeekState(), reader); } else { reader.SkipValue(); } if (reader.BytesRemaining != 0) { throw new InvalidOperationException(SR.Format(SR.CoseHeaderMapCborEncodedValueNotValid, label)); } } static void ValidateKnownHeaderValue(int label, CborReaderState? initialState, CborReader? reader) { switch (label) { case KnownHeaders.Alg: if (initialState != CborReaderState.NegativeInteger && initialState != CborReaderState.UnsignedInteger && initialState != CborReaderState.TextString) { throw new InvalidOperationException(SR.Format(SR.CoseHeaderMapHeaderDoesNotAcceptSpecifiedValue, label)); } reader?.SkipValue(); break; case KnownHeaders.Crit: reader?.SkipValue(); // TODO break; case KnownHeaders.CounterSignature: reader?.SkipValue(); // TODO break; case KnownHeaders.ContentType: if (initialState != CborReaderState.TextString && initialState != CborReaderState.UnsignedInteger) { throw new InvalidOperationException(SR.Format(SR.CoseHeaderMapHeaderDoesNotAcceptSpecifiedValue, label)); } reader?.SkipValue(); break; case KnownHeaders.Kid: case KnownHeaders.IV: case KnownHeaders.PartialIV: if (initialState != CborReaderState.ByteString) { throw new InvalidOperationException(SR.Format(SR.CoseHeaderMapHeaderDoesNotAcceptSpecifiedValue, label)); } reader?.SkipValue(); break; default: reader?.SkipValue(); break; } } } internal byte[] Encode(bool mustReturnEmptyBstrIfEmpty = false, int? algHeaderValueToSlip = null) { bool shouldSlipAlgHeader = algHeaderValueToSlip.HasValue; if (_headerParameters.Count == 0 && mustReturnEmptyBstrIfEmpty && !shouldSlipAlgHeader) { return s_emptyBstrEncoded; } int mapLength = _headerParameters.Count; if (shouldSlipAlgHeader) { mapLength++; } var writer = new CborWriter(); writer.WriteStartMap(mapLength); if (shouldSlipAlgHeader) { Debug.Assert(!TryGetEncodedValue(CoseHeaderLabel.Algorithm, out _)); writer.WriteInt32(KnownHeaders.Alg); writer.WriteInt32(algHeaderValueToSlip!.Value); } foreach ((CoseHeaderLabel Label, ReadOnlyMemory<byte> EncodedValue) header in this) { CoseHeaderLabel label = header.Label; if (label.LabelAsString == null) { writer.WriteInt32(label.LabelAsInt32); } else { writer.WriteTextString(label.LabelAsString); } writer.WriteEncodedValue(header.EncodedValue.Span); } writer.WriteEndMap(); return writer.Encode(); } public Enumerator GetEnumerator() => new Enumerator(_headerParameters.GetEnumerator()); IEnumerator<(CoseHeaderLabel Label, ReadOnlyMemory<byte> EncodedValue)> IEnumerable<(CoseHeaderLabel Label, ReadOnlyMemory<byte> EncodedValue)>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public struct Enumerator : IEnumerator<(CoseHeaderLabel Label, ReadOnlyMemory<byte> EncodedValue)> { private Dictionary<CoseHeaderLabel, ReadOnlyMemory<byte>>.Enumerator _dictionaryEnumerator; internal Enumerator(Dictionary<CoseHeaderLabel, ReadOnlyMemory<byte>>.Enumerator dictionaryEnumerator) { _dictionaryEnumerator = dictionaryEnumerator; } public readonly (CoseHeaderLabel Label, ReadOnlyMemory<byte> EncodedValue) Current => (_dictionaryEnumerator.Current.Key, _dictionaryEnumerator.Current.Value); object IEnumerator.Current => Current; public void Dispose() => _dictionaryEnumerator.Dispose(); public bool MoveNext() => _dictionaryEnumerator.MoveNext(); public void Reset() => ((IEnumerator)_dictionaryEnumerator).Reset(); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Private.Xml/tests/XmlSchema/TestFiles/TestData/XmlSchemaValidatorAPI/GetExpectedParticles.xsd
<?xml version="1.0" encoding="utf-8" ?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:temp="uri:tempuri"> <xs:element name="BasicElement" type="xs:string" /> <xs:element name="NoTypeElement" /> <xs:element name="SequenceElement"> <xs:complexType> <xs:sequence> <xs:element name="elem1" /> <xs:element name="elem2" /> </xs:sequence> <xs:attribute name="attr1" /> <xs:attribute name="attr2" /> </xs:complexType> </xs:element> <xs:element name="ChoiceElement"> <xs:complexType> <xs:choice> <xs:element name="elem1" /> <xs:element name="elem2" /> </xs:choice> <xs:attribute name="attr1" /> <xs:attribute name="attr2" /> </xs:complexType> </xs:element> <xs:element name="AllElement"> <xs:complexType> <xs:all> <xs:element name="elem1" /> <xs:element name="elem2" /> </xs:all> <xs:attribute name="attr1" /> <xs:attribute name="attr2" /> </xs:complexType> </xs:element> <xs:element name="NestedElement"> <xs:complexType> <xs:sequence> <xs:element name="foo"> <xs:complexType> <xs:sequence> <xs:element name="bar" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="ReferenceElement"> <xs:complexType> <xs:sequence> <xs:element ref="NestedElement" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="MinOccurs0Element"> <xs:complexType> <xs:sequence> <xs:element name="foo" minOccurs="0" /> <xs:element name="bar" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="MaxOccurs0Element"> <xs:complexType> <xs:sequence> <xs:element name="foo" maxOccurs="0" /> <xs:element name="bar" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="SequenceWildcardElement"> <xs:complexType> <xs:sequence> <xs:any namespace="uri:tempuri" processContents="strict" /> <xs:element name="foo" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="ChoiceWildcardElement"> <xs:complexType> <xs:choice> <xs:any namespace="uri:tempuri" processContents="strict" /> <xs:element name="foo" /> </xs:choice> </xs:complexType> </xs:element> <xs:group name="SequenceGroup"> <xs:sequence> <xs:element name="g1" /> <xs:element name="g2" /> </xs:sequence> </xs:group> <xs:group name="ChoiceGroup"> <xs:choice> <xs:element name="g1" /> <xs:element name="g2" /> </xs:choice> </xs:group> <xs:element name="SequenceGroupElement"> <xs:complexType> <xs:sequence> <xs:group ref="ChoiceGroup" /> <xs:element name="foo" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="ChoiceGroupElement"> <xs:complexType> <xs:choice> <xs:group ref="SequenceGroup" /> <xs:element name="foo" /> </xs:choice> </xs:complexType> </xs:element> <xs:complexType name="SequenceType"> <xs:sequence> <xs:element name="elem1" /> <xs:element name="elem2" minOccurs="0" /> </xs:sequence> </xs:complexType> <xs:complexType name="ChoiceType"> <xs:choice> <xs:element name="elem1" /> <xs:element name="elem2" /> </xs:choice> </xs:complexType> <xs:complexType name="AllType"> <xs:all> <xs:element name="elem1" /> <xs:element name="elem2" minOccurs="0"/> </xs:all> </xs:complexType> <xs:element name="SequenceExtensionElement"> <xs:complexType> <xs:complexContent> <xs:extension base="SequenceType"> <xs:sequence> <xs:element name="extended" /> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="ChoiceExtensionElement"> <xs:complexType> <xs:complexContent> <xs:extension base="ChoiceType"> <xs:choice> <xs:element name="ext1" /> <xs:element name="ext2" /> </xs:choice> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="SequenceRestrictionElement"> <xs:complexType> <xs:complexContent> <xs:restriction base="SequenceType"> <xs:sequence> <xs:element name="elem1" /> <xs:element name="elem2" maxOccurs="0"/> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="ChoiceRestrictionElement"> <xs:complexType> <xs:complexContent> <xs:restriction base="ChoiceType"> <xs:choice> <xs:element name="elem1" /> <xs:element name="elem2" maxOccurs="0"/> </xs:choice> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="AllRestrictionElement"> <xs:complexType> <xs:complexContent> <xs:restriction base="AllType"> <xs:all> <xs:element name="elem1" /> <xs:element name="elem2" maxOccurs="0"/> </xs:all> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> </xs:schema>
<?xml version="1.0" encoding="utf-8" ?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:temp="uri:tempuri"> <xs:element name="BasicElement" type="xs:string" /> <xs:element name="NoTypeElement" /> <xs:element name="SequenceElement"> <xs:complexType> <xs:sequence> <xs:element name="elem1" /> <xs:element name="elem2" /> </xs:sequence> <xs:attribute name="attr1" /> <xs:attribute name="attr2" /> </xs:complexType> </xs:element> <xs:element name="ChoiceElement"> <xs:complexType> <xs:choice> <xs:element name="elem1" /> <xs:element name="elem2" /> </xs:choice> <xs:attribute name="attr1" /> <xs:attribute name="attr2" /> </xs:complexType> </xs:element> <xs:element name="AllElement"> <xs:complexType> <xs:all> <xs:element name="elem1" /> <xs:element name="elem2" /> </xs:all> <xs:attribute name="attr1" /> <xs:attribute name="attr2" /> </xs:complexType> </xs:element> <xs:element name="NestedElement"> <xs:complexType> <xs:sequence> <xs:element name="foo"> <xs:complexType> <xs:sequence> <xs:element name="bar" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="ReferenceElement"> <xs:complexType> <xs:sequence> <xs:element ref="NestedElement" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="MinOccurs0Element"> <xs:complexType> <xs:sequence> <xs:element name="foo" minOccurs="0" /> <xs:element name="bar" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="MaxOccurs0Element"> <xs:complexType> <xs:sequence> <xs:element name="foo" maxOccurs="0" /> <xs:element name="bar" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="SequenceWildcardElement"> <xs:complexType> <xs:sequence> <xs:any namespace="uri:tempuri" processContents="strict" /> <xs:element name="foo" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="ChoiceWildcardElement"> <xs:complexType> <xs:choice> <xs:any namespace="uri:tempuri" processContents="strict" /> <xs:element name="foo" /> </xs:choice> </xs:complexType> </xs:element> <xs:group name="SequenceGroup"> <xs:sequence> <xs:element name="g1" /> <xs:element name="g2" /> </xs:sequence> </xs:group> <xs:group name="ChoiceGroup"> <xs:choice> <xs:element name="g1" /> <xs:element name="g2" /> </xs:choice> </xs:group> <xs:element name="SequenceGroupElement"> <xs:complexType> <xs:sequence> <xs:group ref="ChoiceGroup" /> <xs:element name="foo" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="ChoiceGroupElement"> <xs:complexType> <xs:choice> <xs:group ref="SequenceGroup" /> <xs:element name="foo" /> </xs:choice> </xs:complexType> </xs:element> <xs:complexType name="SequenceType"> <xs:sequence> <xs:element name="elem1" /> <xs:element name="elem2" minOccurs="0" /> </xs:sequence> </xs:complexType> <xs:complexType name="ChoiceType"> <xs:choice> <xs:element name="elem1" /> <xs:element name="elem2" /> </xs:choice> </xs:complexType> <xs:complexType name="AllType"> <xs:all> <xs:element name="elem1" /> <xs:element name="elem2" minOccurs="0"/> </xs:all> </xs:complexType> <xs:element name="SequenceExtensionElement"> <xs:complexType> <xs:complexContent> <xs:extension base="SequenceType"> <xs:sequence> <xs:element name="extended" /> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="ChoiceExtensionElement"> <xs:complexType> <xs:complexContent> <xs:extension base="ChoiceType"> <xs:choice> <xs:element name="ext1" /> <xs:element name="ext2" /> </xs:choice> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="SequenceRestrictionElement"> <xs:complexType> <xs:complexContent> <xs:restriction base="SequenceType"> <xs:sequence> <xs:element name="elem1" /> <xs:element name="elem2" maxOccurs="0"/> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="ChoiceRestrictionElement"> <xs:complexType> <xs:complexContent> <xs:restriction base="ChoiceType"> <xs:choice> <xs:element name="elem1" /> <xs:element name="elem2" maxOccurs="0"/> </xs:choice> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> <xs:element name="AllRestrictionElement"> <xs:complexType> <xs:complexContent> <xs:restriction base="AllType"> <xs:all> <xs:element name="elem1" /> <xs:element name="elem2" maxOccurs="0"/> </xs:all> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> </xs:schema>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/CopiedFieldRvaNode.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.Immutable; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using Internal.Text; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Debug = System.Diagnostics.Debug; namespace ILCompiler.DependencyAnalysis.ReadyToRun { public class CopiedFieldRvaNode : ObjectNode, ISymbolDefinitionNode { private int _rva; private EcmaModule _module; public CopiedFieldRvaNode(EcmaModule module, int rva) { _rva = rva; _module = module; } public override ObjectNodeSection Section => ObjectNodeSection.TextSection; public override bool IsShareable => false; public override int ClassCode => 223495; public override bool StaticDependenciesAreComputed => true; public int Offset => 0; public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { if (relocsOnly) { return new ObjectData( data: Array.Empty<byte>(), relocs: Array.Empty<Relocation>(), alignment: 1, definedSymbols: new ISymbolDefinitionNode[] { this }); } ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly); byte[] rvaData = GetRvaData(factory.Target.PointerSize, out int requiredAlignment); builder.RequireInitialAlignment(requiredAlignment); builder.AddSymbol(this); builder.EmitBytes(rvaData); return builder.ToObjectData(); } private unsafe byte[] GetRvaData(int targetPointerSize, out int requiredAlignment) { int size = 0; requiredAlignment = targetPointerSize; MetadataReader metadataReader = _module.MetadataReader; BlobReader metadataBlob = new BlobReader(_module.PEReader.GetMetadata().Pointer, _module.PEReader.GetMetadata().Length); metadataBlob.Offset = metadataReader.GetTableMetadataOffset(TableIndex.FieldRva); bool compressedFieldRef = 6 == metadataReader.GetTableRowSize(TableIndex.FieldRva); for (int i = 1; i <= metadataReader.GetTableRowCount(TableIndex.FieldRva); i++) { int currentFieldRva = metadataBlob.ReadInt32(); int currentFieldRid; if (compressedFieldRef) { currentFieldRid = metadataBlob.ReadUInt16(); } else { currentFieldRid = metadataBlob.ReadInt32(); } if (currentFieldRva != _rva) continue; EcmaField field = (EcmaField)_module.GetField(MetadataTokens.FieldDefinitionHandle(currentFieldRid)); Debug.Assert(field.HasRva); int currentSize = field.FieldType.GetElementSize().AsInt; requiredAlignment = Math.Max(requiredAlignment, (field.FieldType as MetadataType)?.GetClassLayout().PackingSize ?? 1); if (currentSize > size) { // We need to handle overlapping fields by reusing blobs based on the rva, and just update // the size and contents size = currentSize; } } Debug.Assert(size > 0); PEMemoryBlock block = _module.PEReader.GetSectionData(_rva); if (block.Length < size) throw new BadImageFormatException(); byte[] result = new byte[AlignmentHelper.AlignUp(size, targetPointerSize)]; block.GetContent(0, size).CopyTo(result); return result; } protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(nameMangler.CompilationUnitPrefix); sb.Append($"_FieldRvaData_{_module.Assembly.GetName().Name}_{_rva}"); } public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { int result = _module.CompareTo(((CopiedFieldRvaNode)other)._module); if (result != 0) return result; return _rva - ((CopiedFieldRvaNode)other)._rva; } } }
// 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.Immutable; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using Internal.Text; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Debug = System.Diagnostics.Debug; namespace ILCompiler.DependencyAnalysis.ReadyToRun { public class CopiedFieldRvaNode : ObjectNode, ISymbolDefinitionNode { private int _rva; private EcmaModule _module; public CopiedFieldRvaNode(EcmaModule module, int rva) { _rva = rva; _module = module; } public override ObjectNodeSection Section => ObjectNodeSection.TextSection; public override bool IsShareable => false; public override int ClassCode => 223495; public override bool StaticDependenciesAreComputed => true; public int Offset => 0; public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { if (relocsOnly) { return new ObjectData( data: Array.Empty<byte>(), relocs: Array.Empty<Relocation>(), alignment: 1, definedSymbols: new ISymbolDefinitionNode[] { this }); } ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly); byte[] rvaData = GetRvaData(factory.Target.PointerSize, out int requiredAlignment); builder.RequireInitialAlignment(requiredAlignment); builder.AddSymbol(this); builder.EmitBytes(rvaData); return builder.ToObjectData(); } private unsafe byte[] GetRvaData(int targetPointerSize, out int requiredAlignment) { int size = 0; requiredAlignment = targetPointerSize; MetadataReader metadataReader = _module.MetadataReader; BlobReader metadataBlob = new BlobReader(_module.PEReader.GetMetadata().Pointer, _module.PEReader.GetMetadata().Length); metadataBlob.Offset = metadataReader.GetTableMetadataOffset(TableIndex.FieldRva); bool compressedFieldRef = 6 == metadataReader.GetTableRowSize(TableIndex.FieldRva); for (int i = 1; i <= metadataReader.GetTableRowCount(TableIndex.FieldRva); i++) { int currentFieldRva = metadataBlob.ReadInt32(); int currentFieldRid; if (compressedFieldRef) { currentFieldRid = metadataBlob.ReadUInt16(); } else { currentFieldRid = metadataBlob.ReadInt32(); } if (currentFieldRva != _rva) continue; EcmaField field = (EcmaField)_module.GetField(MetadataTokens.FieldDefinitionHandle(currentFieldRid)); Debug.Assert(field.HasRva); int currentSize = field.FieldType.GetElementSize().AsInt; requiredAlignment = Math.Max(requiredAlignment, (field.FieldType as MetadataType)?.GetClassLayout().PackingSize ?? 1); if (currentSize > size) { // We need to handle overlapping fields by reusing blobs based on the rva, and just update // the size and contents size = currentSize; } } Debug.Assert(size > 0); PEMemoryBlock block = _module.PEReader.GetSectionData(_rva); if (block.Length < size) throw new BadImageFormatException(); byte[] result = new byte[AlignmentHelper.AlignUp(size, targetPointerSize)]; block.GetContent(0, size).CopyTo(result); return result; } protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(nameMangler.CompilationUnitPrefix); sb.Append($"_FieldRvaData_{_module.Assembly.GetName().Name}_{_rva}"); } public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { int result = _module.CompareTo(((CopiedFieldRvaNode)other)._module); if (result != 0) return result; return _rva - ((CopiedFieldRvaNode)other)._rva; } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/HardwareIntrinsics/General/Vector64/CreateScalar.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\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 CreateScalarUInt32() { var test = new VectorCreate__CreateScalarUInt32(); // 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__CreateScalarUInt32 { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); UInt32 value = TestLibrary.Generator.GetUInt32(); Vector64<UInt32> result = Vector64.CreateScalar(value); ValidateResult(result, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); UInt32 value = TestLibrary.Generator.GetUInt32(); object result = typeof(Vector64) .GetMethod(nameof(Vector64.CreateScalar), new Type[] { typeof(UInt32) }) .Invoke(null, new object[] { value }); ValidateResult((Vector64<UInt32>)(result), value); } private void ValidateResult(Vector64<UInt32> result, UInt32 expectedValue, [CallerMemberName] string method = "") { UInt32[] resultElements = new UInt32[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref resultElements[0]), result); ValidateResult(resultElements, expectedValue, method); } private void ValidateResult(UInt32[] resultElements, UInt32 expectedValue, [CallerMemberName] string method = "") { bool succeeded = true; if (resultElements[0] != expectedValue) { succeeded = false; } else { for (var i = 1; i < ElementCount; i++) { if (resultElements[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64.CreateScalar(UInt32): {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 CreateScalarUInt32() { var test = new VectorCreate__CreateScalarUInt32(); // 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__CreateScalarUInt32 { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); UInt32 value = TestLibrary.Generator.GetUInt32(); Vector64<UInt32> result = Vector64.CreateScalar(value); ValidateResult(result, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); UInt32 value = TestLibrary.Generator.GetUInt32(); object result = typeof(Vector64) .GetMethod(nameof(Vector64.CreateScalar), new Type[] { typeof(UInt32) }) .Invoke(null, new object[] { value }); ValidateResult((Vector64<UInt32>)(result), value); } private void ValidateResult(Vector64<UInt32> result, UInt32 expectedValue, [CallerMemberName] string method = "") { UInt32[] resultElements = new UInt32[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref resultElements[0]), result); ValidateResult(resultElements, expectedValue, method); } private void ValidateResult(UInt32[] resultElements, UInt32 expectedValue, [CallerMemberName] string method = "") { bool succeeded = true; if (resultElements[0] != expectedValue) { succeeded = false; } else { for (var i = 1; i < ElementCount; i++) { if (resultElements[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64.CreateScalar(UInt32): {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,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdLifetime.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.Versioning; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace Microsoft.Extensions.Hosting.Systemd { [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("maccatalyst")] [UnsupportedOSPlatform("tvos")] public partial class SystemdLifetime : IHostLifetime, IDisposable { private CancellationTokenRegistration _applicationStartedRegistration; private CancellationTokenRegistration _applicationStoppingRegistration; public SystemdLifetime(IHostEnvironment environment!!, IHostApplicationLifetime applicationLifetime!!, ISystemdNotifier systemdNotifier!!, ILoggerFactory loggerFactory) { Environment = environment; ApplicationLifetime = applicationLifetime; SystemdNotifier = systemdNotifier; Logger = loggerFactory.CreateLogger("Microsoft.Hosting.Lifetime"); } private IHostApplicationLifetime ApplicationLifetime { get; } private IHostEnvironment Environment { get; } private ILogger Logger { get; } private ISystemdNotifier SystemdNotifier { get; } public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } public Task WaitForStartAsync(CancellationToken cancellationToken) { _applicationStartedRegistration = ApplicationLifetime.ApplicationStarted.Register(state => { ((SystemdLifetime)state).OnApplicationStarted(); }, this); _applicationStoppingRegistration = ApplicationLifetime.ApplicationStopping.Register(state => { ((SystemdLifetime)state).OnApplicationStopping(); }, this); RegisterShutdownHandlers(); return Task.CompletedTask; } private partial void RegisterShutdownHandlers(); private void OnApplicationStarted() { Logger.LogInformation("Application started. Hosting environment: {EnvironmentName}; Content root path: {ContentRoot}", Environment.EnvironmentName, Environment.ContentRootPath); SystemdNotifier.Notify(ServiceState.Ready); } private void OnApplicationStopping() { Logger.LogInformation("Application is shutting down..."); SystemdNotifier.Notify(ServiceState.Stopping); } public void Dispose() { UnregisterShutdownHandlers(); _applicationStartedRegistration.Dispose(); _applicationStoppingRegistration.Dispose(); } private partial void UnregisterShutdownHandlers(); } }
// 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.Versioning; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace Microsoft.Extensions.Hosting.Systemd { [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("maccatalyst")] [UnsupportedOSPlatform("tvos")] public partial class SystemdLifetime : IHostLifetime, IDisposable { private CancellationTokenRegistration _applicationStartedRegistration; private CancellationTokenRegistration _applicationStoppingRegistration; public SystemdLifetime(IHostEnvironment environment!!, IHostApplicationLifetime applicationLifetime!!, ISystemdNotifier systemdNotifier!!, ILoggerFactory loggerFactory) { Environment = environment; ApplicationLifetime = applicationLifetime; SystemdNotifier = systemdNotifier; Logger = loggerFactory.CreateLogger("Microsoft.Hosting.Lifetime"); } private IHostApplicationLifetime ApplicationLifetime { get; } private IHostEnvironment Environment { get; } private ILogger Logger { get; } private ISystemdNotifier SystemdNotifier { get; } public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } public Task WaitForStartAsync(CancellationToken cancellationToken) { _applicationStartedRegistration = ApplicationLifetime.ApplicationStarted.Register(state => { ((SystemdLifetime)state).OnApplicationStarted(); }, this); _applicationStoppingRegistration = ApplicationLifetime.ApplicationStopping.Register(state => { ((SystemdLifetime)state).OnApplicationStopping(); }, this); RegisterShutdownHandlers(); return Task.CompletedTask; } private partial void RegisterShutdownHandlers(); private void OnApplicationStarted() { Logger.LogInformation("Application started. Hosting environment: {EnvironmentName}; Content root path: {ContentRoot}", Environment.EnvironmentName, Environment.ContentRootPath); SystemdNotifier.Notify(ServiceState.Ready); } private void OnApplicationStopping() { Logger.LogInformation("Application is shutting down..."); SystemdNotifier.Notify(ServiceState.Stopping); } public void Dispose() { UnregisterShutdownHandlers(); _applicationStartedRegistration.Dispose(); _applicationStoppingRegistration.Dispose(); } private partial void UnregisterShutdownHandlers(); } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Resources.Reader/tests/System.Resources.Reader.Tests.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <TestRuntime>true</TestRuntime> </PropertyGroup> <ItemGroup> <Compile Include="ResourceReaderUnitTest.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <TestRuntime>true</TestRuntime> </PropertyGroup> <ItemGroup> <Compile Include="ResourceReaderUnitTest.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/UpdateConfigHost.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.Specialized; using System.Configuration.Internal; using System.Diagnostics; using System.IO; namespace System.Configuration { // Configuration host that intercepts calls to filename functions // to support SaveAs to an alternate file stream. internal sealed class UpdateConfigHost : DelegatingConfigHost { private HybridDictionary _streams; // oldStreamname -> StreamUpdate internal UpdateConfigHost(IInternalConfigHost host) { // Delegate to the host provided. Host = host; } // Add a stream to the list of streams to intercept. // // Parameters: // alwaysIntercept - If true, then don't check whether the old stream and the new stream are the same. // SaveAs() will set this to true if oldStreamname is actually referring to a stream // on a remote machine. internal void AddStreamname(string oldStreamname, string newStreamname, bool alwaysIntercept) { // After reviewing all the code paths, oldStreamname shouldn't be Null or Empty. // It actually doesn't make much sense if we're asked to intercept an null or empty stream. Debug.Assert(!string.IsNullOrEmpty(oldStreamname)); if (string.IsNullOrEmpty(oldStreamname)) return; if (!alwaysIntercept && StringUtil.EqualsIgnoreCase(oldStreamname, newStreamname)) return; if (_streams == null) _streams = new HybridDictionary(true); _streams[oldStreamname] = new StreamUpdate(newStreamname); } // Get the new stream name for a stream if a new name exists, otherwise // return the original stream name. internal string GetNewStreamname(string oldStreamname) { StreamUpdate streamUpdate = GetStreamUpdate(oldStreamname, false); return streamUpdate != null ? streamUpdate.NewStreamname : oldStreamname; } // Get the StreamUpdate for a stream. // If alwaysIntercept is true, then the StreamUpdate is // always returned if it exists. // If alwaysIntercept is false, then only return the StreamUpdate // if the new stream has been successfully written to. private StreamUpdate GetStreamUpdate(string oldStreamname, bool alwaysIntercept) { if (_streams == null) return null; StreamUpdate streamUpdate = (StreamUpdate)_streams[oldStreamname]; if ((streamUpdate != null) && !alwaysIntercept && !streamUpdate.WriteCompleted) streamUpdate = null; return streamUpdate; } public override object GetStreamVersion(string streamName) { StreamUpdate streamUpdate = GetStreamUpdate(streamName, false); return streamUpdate != null ? InternalConfigHost.StaticGetStreamVersion(streamUpdate.NewStreamname) : Host.GetStreamVersion(streamName); } public override Stream OpenStreamForRead(string streamName) { StreamUpdate streamUpdate = GetStreamUpdate(streamName, false); return streamUpdate != null ? InternalConfigHost.StaticOpenStreamForRead(streamUpdate.NewStreamname) : Host.OpenStreamForRead(streamName); } public override Stream OpenStreamForWrite(string streamName, string templateStreamName, ref object writeContext) { // Always attempt to write to the new stream name if it exists. StreamUpdate streamUpdate = GetStreamUpdate(streamName, true); if (streamUpdate != null) { return InternalConfigHost.StaticOpenStreamForWrite( streamUpdate.NewStreamname, templateStreamName, ref writeContext); } return Host.OpenStreamForWrite(streamName, templateStreamName, ref writeContext); } public override void WriteCompleted(string streamName, bool success, object writeContext) { StreamUpdate streamUpdate = GetStreamUpdate(streamName, true); if (streamUpdate != null) { InternalConfigHost.StaticWriteCompleted(streamUpdate.NewStreamname, success, writeContext); // Mark the write as having successfully completed, so that subsequent calls // to Read() will use the new stream name. if (success) streamUpdate.WriteCompleted = true; } else { Host.WriteCompleted(streamName, success, writeContext); } } public override bool IsConfigRecordRequired(string configPath) { return true; } public override void DeleteStream(string streamName) { StreamUpdate streamUpdate = GetStreamUpdate(streamName, false); if (streamUpdate != null) InternalConfigHost.StaticDeleteStream(streamUpdate.NewStreamname); else Host.DeleteStream(streamName); } public override bool IsFile(string streamName) { StreamUpdate streamUpdate = GetStreamUpdate(streamName, false); return streamUpdate != null ? InternalConfigHost.StaticIsFile(streamUpdate.NewStreamname) : Host.IsFile(streamName); } } }
// 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.Specialized; using System.Configuration.Internal; using System.Diagnostics; using System.IO; namespace System.Configuration { // Configuration host that intercepts calls to filename functions // to support SaveAs to an alternate file stream. internal sealed class UpdateConfigHost : DelegatingConfigHost { private HybridDictionary _streams; // oldStreamname -> StreamUpdate internal UpdateConfigHost(IInternalConfigHost host) { // Delegate to the host provided. Host = host; } // Add a stream to the list of streams to intercept. // // Parameters: // alwaysIntercept - If true, then don't check whether the old stream and the new stream are the same. // SaveAs() will set this to true if oldStreamname is actually referring to a stream // on a remote machine. internal void AddStreamname(string oldStreamname, string newStreamname, bool alwaysIntercept) { // After reviewing all the code paths, oldStreamname shouldn't be Null or Empty. // It actually doesn't make much sense if we're asked to intercept an null or empty stream. Debug.Assert(!string.IsNullOrEmpty(oldStreamname)); if (string.IsNullOrEmpty(oldStreamname)) return; if (!alwaysIntercept && StringUtil.EqualsIgnoreCase(oldStreamname, newStreamname)) return; if (_streams == null) _streams = new HybridDictionary(true); _streams[oldStreamname] = new StreamUpdate(newStreamname); } // Get the new stream name for a stream if a new name exists, otherwise // return the original stream name. internal string GetNewStreamname(string oldStreamname) { StreamUpdate streamUpdate = GetStreamUpdate(oldStreamname, false); return streamUpdate != null ? streamUpdate.NewStreamname : oldStreamname; } // Get the StreamUpdate for a stream. // If alwaysIntercept is true, then the StreamUpdate is // always returned if it exists. // If alwaysIntercept is false, then only return the StreamUpdate // if the new stream has been successfully written to. private StreamUpdate GetStreamUpdate(string oldStreamname, bool alwaysIntercept) { if (_streams == null) return null; StreamUpdate streamUpdate = (StreamUpdate)_streams[oldStreamname]; if ((streamUpdate != null) && !alwaysIntercept && !streamUpdate.WriteCompleted) streamUpdate = null; return streamUpdate; } public override object GetStreamVersion(string streamName) { StreamUpdate streamUpdate = GetStreamUpdate(streamName, false); return streamUpdate != null ? InternalConfigHost.StaticGetStreamVersion(streamUpdate.NewStreamname) : Host.GetStreamVersion(streamName); } public override Stream OpenStreamForRead(string streamName) { StreamUpdate streamUpdate = GetStreamUpdate(streamName, false); return streamUpdate != null ? InternalConfigHost.StaticOpenStreamForRead(streamUpdate.NewStreamname) : Host.OpenStreamForRead(streamName); } public override Stream OpenStreamForWrite(string streamName, string templateStreamName, ref object writeContext) { // Always attempt to write to the new stream name if it exists. StreamUpdate streamUpdate = GetStreamUpdate(streamName, true); if (streamUpdate != null) { return InternalConfigHost.StaticOpenStreamForWrite( streamUpdate.NewStreamname, templateStreamName, ref writeContext); } return Host.OpenStreamForWrite(streamName, templateStreamName, ref writeContext); } public override void WriteCompleted(string streamName, bool success, object writeContext) { StreamUpdate streamUpdate = GetStreamUpdate(streamName, true); if (streamUpdate != null) { InternalConfigHost.StaticWriteCompleted(streamUpdate.NewStreamname, success, writeContext); // Mark the write as having successfully completed, so that subsequent calls // to Read() will use the new stream name. if (success) streamUpdate.WriteCompleted = true; } else { Host.WriteCompleted(streamName, success, writeContext); } } public override bool IsConfigRecordRequired(string configPath) { return true; } public override void DeleteStream(string streamName) { StreamUpdate streamUpdate = GetStreamUpdate(streamName, false); if (streamUpdate != null) InternalConfigHost.StaticDeleteStream(streamUpdate.NewStreamname); else Host.DeleteStream(streamName); } public override bool IsFile(string streamName) { StreamUpdate streamUpdate = GetStreamUpdate(streamName, false); return streamUpdate != null ? InternalConfigHost.StaticIsFile(streamUpdate.NewStreamname) : Host.IsFile(streamName); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWithMapTyped.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; namespace System.Runtime.Serialization.Formatters.Binary { internal sealed class BinaryObjectWithMapTyped : IStreamable { internal BinaryHeaderEnum _binaryHeaderEnum; internal int _objectId; internal string? _name; internal int _numMembers; internal string[]? _memberNames; internal BinaryTypeEnum[]? _binaryTypeEnumA; internal object?[]? _typeInformationA; internal int[]? _memberAssemIds; internal int _assemId; internal BinaryObjectWithMapTyped() { } internal BinaryObjectWithMapTyped(BinaryHeaderEnum binaryHeaderEnum) { _binaryHeaderEnum = binaryHeaderEnum; } internal void Set(int objectId, string name, int numMembers, string[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, object?[] typeInformationA, int[] memberAssemIds, int assemId) { _objectId = objectId; _assemId = assemId; _name = name; _numMembers = numMembers; _memberNames = memberNames; _binaryTypeEnumA = binaryTypeEnumA; _typeInformationA = typeInformationA; _memberAssemIds = memberAssemIds; _assemId = assemId; _binaryHeaderEnum = assemId > 0 ? BinaryHeaderEnum.ObjectWithMapTypedAssemId : BinaryHeaderEnum.ObjectWithMapTyped; } public void Write(BinaryFormatterWriter output) { Debug.Assert(_name != null && _memberNames != null && _binaryTypeEnumA != null && _typeInformationA != null && _memberAssemIds != null); output.WriteByte((byte)_binaryHeaderEnum); output.WriteInt32(_objectId); output.WriteString(_name); output.WriteInt32(_numMembers); for (int i = 0; i < _numMembers; i++) { output.WriteString(_memberNames[i]); } for (int i = 0; i < _numMembers; i++) { output.WriteByte((byte)_binaryTypeEnumA[i]); } for (int i = 0; i < _numMembers; i++) { BinaryTypeConverter.WriteTypeInfo(_binaryTypeEnumA[i], _typeInformationA[i], _memberAssemIds[i], output); } if (_assemId > 0) { output.WriteInt32(_assemId); } } public void Read(BinaryParser input) { // binaryHeaderEnum has already been read _objectId = input.ReadInt32(); _name = input.ReadString(); _numMembers = input.ReadInt32(); _memberNames = new string[_numMembers]; _binaryTypeEnumA = new BinaryTypeEnum[_numMembers]; _typeInformationA = new object[_numMembers]; _memberAssemIds = new int[_numMembers]; for (int i = 0; i < _numMembers; i++) { _memberNames[i] = input.ReadString(); } for (int i = 0; i < _numMembers; i++) { _binaryTypeEnumA[i] = (BinaryTypeEnum)input.ReadByte(); } for (int i = 0; i < _numMembers; i++) { if (_binaryTypeEnumA[i] != BinaryTypeEnum.ObjectUrt && _binaryTypeEnumA[i] != BinaryTypeEnum.ObjectUser) { _typeInformationA[i] = BinaryTypeConverter.ReadTypeInfo(_binaryTypeEnumA[i], input, out _memberAssemIds[i]); } else { BinaryTypeConverter.ReadTypeInfo(_binaryTypeEnumA[i], input, out _memberAssemIds[i]); } } if (_binaryHeaderEnum == BinaryHeaderEnum.ObjectWithMapTypedAssemId) { _assemId = input.ReadInt32(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; namespace System.Runtime.Serialization.Formatters.Binary { internal sealed class BinaryObjectWithMapTyped : IStreamable { internal BinaryHeaderEnum _binaryHeaderEnum; internal int _objectId; internal string? _name; internal int _numMembers; internal string[]? _memberNames; internal BinaryTypeEnum[]? _binaryTypeEnumA; internal object?[]? _typeInformationA; internal int[]? _memberAssemIds; internal int _assemId; internal BinaryObjectWithMapTyped() { } internal BinaryObjectWithMapTyped(BinaryHeaderEnum binaryHeaderEnum) { _binaryHeaderEnum = binaryHeaderEnum; } internal void Set(int objectId, string name, int numMembers, string[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, object?[] typeInformationA, int[] memberAssemIds, int assemId) { _objectId = objectId; _assemId = assemId; _name = name; _numMembers = numMembers; _memberNames = memberNames; _binaryTypeEnumA = binaryTypeEnumA; _typeInformationA = typeInformationA; _memberAssemIds = memberAssemIds; _assemId = assemId; _binaryHeaderEnum = assemId > 0 ? BinaryHeaderEnum.ObjectWithMapTypedAssemId : BinaryHeaderEnum.ObjectWithMapTyped; } public void Write(BinaryFormatterWriter output) { Debug.Assert(_name != null && _memberNames != null && _binaryTypeEnumA != null && _typeInformationA != null && _memberAssemIds != null); output.WriteByte((byte)_binaryHeaderEnum); output.WriteInt32(_objectId); output.WriteString(_name); output.WriteInt32(_numMembers); for (int i = 0; i < _numMembers; i++) { output.WriteString(_memberNames[i]); } for (int i = 0; i < _numMembers; i++) { output.WriteByte((byte)_binaryTypeEnumA[i]); } for (int i = 0; i < _numMembers; i++) { BinaryTypeConverter.WriteTypeInfo(_binaryTypeEnumA[i], _typeInformationA[i], _memberAssemIds[i], output); } if (_assemId > 0) { output.WriteInt32(_assemId); } } public void Read(BinaryParser input) { // binaryHeaderEnum has already been read _objectId = input.ReadInt32(); _name = input.ReadString(); _numMembers = input.ReadInt32(); _memberNames = new string[_numMembers]; _binaryTypeEnumA = new BinaryTypeEnum[_numMembers]; _typeInformationA = new object[_numMembers]; _memberAssemIds = new int[_numMembers]; for (int i = 0; i < _numMembers; i++) { _memberNames[i] = input.ReadString(); } for (int i = 0; i < _numMembers; i++) { _binaryTypeEnumA[i] = (BinaryTypeEnum)input.ReadByte(); } for (int i = 0; i < _numMembers; i++) { if (_binaryTypeEnumA[i] != BinaryTypeEnum.ObjectUrt && _binaryTypeEnumA[i] != BinaryTypeEnum.ObjectUser) { _typeInformationA[i] = BinaryTypeConverter.ReadTypeInfo(_binaryTypeEnumA[i], input, out _memberAssemIds[i]); } else { BinaryTypeConverter.ReadTypeInfo(_binaryTypeEnumA[i], input, out _memberAssemIds[i]); } } if (_binaryHeaderEnum == BinaryHeaderEnum.ObjectWithMapTypedAssemId) { _assemId = input.ReadInt32(); } } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/opt/perf/doublealign/locals.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.CompilerServices; public class CMyException : System.Exception { } public class CTest { [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void UseShort(short x) { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void UseByte(byte x) { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static unsafe void CheckDoubleAlignment(double* p) { if (((int)p % sizeof(double)) != 0) throw new CMyException(); } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static unsafe void TestLocals1(short a, double b, byte c, double d) { short i16; double d1; byte i8; double d2; i16 = a; i8 = c; d1 = b; d2 = d; CheckDoubleAlignment(&d1); CheckDoubleAlignment(&d2); i16 += (short)d1; i8 += (byte)d2; UseShort(i16); UseByte(i8); } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static unsafe void TestLocals2(short a, double b, byte c, double d) { char c1; double d1; CMyException e1 = new CMyException(); byte b1; short s1; double d2; int[] a1 = new int[1]; int i1; int i2; int i3; int i4; int i5; double d3; byte b3; byte b5; double d5; sbyte b4 = 5; double d6; int i6; c1 = (char)a; b1 = b3 = c; d1 = b; d2 = d; d3 = d1 + d2; d5 = d1 * 3; i1 = a; i2 = c; i3 = a + c; i4 = a - c; i5 = i1--; i6 = i3 * i4; s1 = (short)(a + 5); b4 += (sbyte)c; byte b2 = (byte)-b1; double d4 = d3 / 2; b5 = (byte)b; d6 = b1++; CheckDoubleAlignment(&d1); CheckDoubleAlignment(&d2); CheckDoubleAlignment(&d3); CheckDoubleAlignment(&d4); CheckDoubleAlignment(&d5); CheckDoubleAlignment(&d6); b3 -= (byte)(d5 * b4 - b5); s1 += (short)(d1 + d6 - (i1 + i2 + i3 + i4 + i5 + i6)); b1 += (byte)(b3 + d2 - (i1 * 3 + i2 - i3 - i4 * i5 - (i6 >> 2))); UseShort(s1); UseByte(b1); } public static int Main() { try { TestLocals1(1, 2, 3, 4); TestLocals2(1, 2, 3, 4); } catch (CMyException) { Console.WriteLine("FAILED"); return 101; } 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. using System; using System.Runtime.CompilerServices; public class CMyException : System.Exception { } public class CTest { [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void UseShort(short x) { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static void UseByte(byte x) { } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static unsafe void CheckDoubleAlignment(double* p) { if (((int)p % sizeof(double)) != 0) throw new CMyException(); } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static unsafe void TestLocals1(short a, double b, byte c, double d) { short i16; double d1; byte i8; double d2; i16 = a; i8 = c; d1 = b; d2 = d; CheckDoubleAlignment(&d1); CheckDoubleAlignment(&d2); i16 += (short)d1; i8 += (byte)d2; UseShort(i16); UseByte(i8); } [MethodImplAttribute(MethodImplOptions.NoInlining)] private static unsafe void TestLocals2(short a, double b, byte c, double d) { char c1; double d1; CMyException e1 = new CMyException(); byte b1; short s1; double d2; int[] a1 = new int[1]; int i1; int i2; int i3; int i4; int i5; double d3; byte b3; byte b5; double d5; sbyte b4 = 5; double d6; int i6; c1 = (char)a; b1 = b3 = c; d1 = b; d2 = d; d3 = d1 + d2; d5 = d1 * 3; i1 = a; i2 = c; i3 = a + c; i4 = a - c; i5 = i1--; i6 = i3 * i4; s1 = (short)(a + 5); b4 += (sbyte)c; byte b2 = (byte)-b1; double d4 = d3 / 2; b5 = (byte)b; d6 = b1++; CheckDoubleAlignment(&d1); CheckDoubleAlignment(&d2); CheckDoubleAlignment(&d3); CheckDoubleAlignment(&d4); CheckDoubleAlignment(&d5); CheckDoubleAlignment(&d6); b3 -= (byte)(d5 * b4 - b5); s1 += (short)(d1 + d6 - (i1 + i2 + i3 + i4 + i5 + i6)); b1 += (byte)(b3 + d2 - (i1 * 3 + i2 - i3 - i4 * i5 - (i6 >> 2))); UseShort(s1); UseByte(b1); } public static int Main() { try { TestLocals1(1, 2, 3, 4); TestLocals2(1, 2, 3, 4); } catch (CMyException) { Console.WriteLine("FAILED"); return 101; } Console.WriteLine("PASSED"); return 100; } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/IL_Conformance/Old/directed/ldloc_s_r4.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 ldloc_s_r4 {} .class ldloc_s_r4 { .method public static int32 test_float32() { .locals (float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32) .zeroinit .maxstack 2 ldloc.s 0x00 ldc.r4 1 add stloc.s 0x01 ldloc.s 0x01 ldc.r4 1 add stloc.s 0x02 ldloc.s 0x02 ldc.r4 1 add stloc.s 0x03 ldloc.s 0x03 ldc.r4 1 add stloc.s 0x04 ldloc.s 0x04 ldc.r4 1 add stloc.s 0x05 ldloc.s 0x05 ldc.r4 1 add stloc.s 0x06 ldloc.s 0x06 ldc.r4 1 add stloc.s 0x07 ldloc.s 0x07 ldc.r4 1 add stloc.s 0x08 ldloc.s 0x08 ldc.r4 1 add stloc.s 0x09 ldloc.s 0x09 ldc.r4 1 add stloc.s 0x0a ldloc.s 0x0a ldc.r4 1 add stloc.s 0x0b ldloc.s 0x0b ldc.r4 1 add stloc.s 0x0c ldloc.s 0x0c ldc.r4 1 add stloc.s 0x0d ldloc.s 0x0d ldc.r4 1 add stloc.s 0x0e ldloc.s 0x0e ldc.r4 1 add stloc.s 0x0f ldloc.s 0x0f ldc.r4 1 add stloc.s 0x10 ldloc.s 0x10 ldc.r4 1 add stloc.s 0x11 ldloc.s 0x11 ldc.r4 1 add stloc.s 0x12 ldloc.s 0x12 ldc.r4 1 add stloc.s 0x13 ldloc.s 0x13 ldc.r4 1 add stloc.s 0x14 ldloc.s 0x14 ldc.r4 1 add stloc.s 0x15 ldloc.s 0x15 ldc.r4 1 add stloc.s 0x8 ldloc.s 0x8 ldc.r4 1 add stloc.s 0x17 ldloc.s 0x17 ldc.r4 1 add stloc.s 0x18 ldloc.s 0x18 ldc.r4 1 add stloc.s 0x19 ldloc.s 0x19 ldc.r4 1 add stloc.s 0x1a ldloc.s 0x1a ldc.r4 1 add stloc.s 0x1b ldloc.s 0x1b ldc.r4 1 add stloc.s 0x1c ldloc.s 0x1c ldc.r4 1 add stloc.s 0x1d ldloc.s 0x1d ldc.r4 1 add stloc.s 0x1e ldloc.s 0x1e ldc.r4 1 add stloc.s 0x1f ldloc.s 0x1f ldc.r4 1 add stloc.s 0x20 ldloc.s 0x20 ldc.r4 1 add stloc.s 0x21 ldloc.s 0x21 ldc.r4 1 add stloc.s 0x22 ldloc.s 0x22 ldc.r4 1 add stloc.s 0x23 ldloc.s 0x23 ldc.r4 1 add stloc.s 0x24 ldloc.s 0x24 ldc.r4 1 add stloc.s 0x25 ldloc.s 0x25 ldc.r4 1 add stloc.s 0x26 ldloc.s 0x26 ldc.r4 1 add stloc.s 0x27 ldloc.s 0x27 ldc.r4 1 add stloc.s 0x28 ldloc.s 0x28 ldc.r4 1 add stloc.s 0x29 ldloc.s 0x29 ldc.r4 1 add stloc.s 0x2a ldloc.s 0x2a ldc.r4 1 add stloc.s 0x2b ldloc.s 0x2b ldc.r4 1 add stloc.s 0x2c ldloc.s 0x2c ldc.r4 1 add stloc.s 0x2d ldloc.s 0x2d ldc.r4 1 add stloc.s 0x2e ldloc.s 0x2e ldc.r4 1 add stloc.s 0x2f ldloc.s 0x2f ldc.r4 1 add stloc.s 0x30 ldloc.s 0x30 ldc.r4 1 add stloc.s 0x31 ldloc.s 0x31 ldc.r4 1 add stloc.s 0x8 ldloc.s 0x8 ldc.r4 1 add stloc.s 0x33 ldloc.s 0x33 ldc.r4 1 add stloc.s 0x34 ldloc.s 0x34 ldc.r4 1 add stloc.s 0x35 ldloc.s 0x35 ldc.r4 1 add stloc.s 0x36 ldloc.s 0x36 ldc.r4 1 add stloc.s 0x37 ldloc.s 0x37 ldc.r4 1 add stloc.s 0x38 ldloc.s 0x38 ldc.r4 1 add stloc.s 0x39 ldloc.s 0x39 ldc.r4 1 add stloc.s 0x3a ldloc.s 0x3a ldc.r4 1 add stloc.s 0x3b ldloc.s 0x3b ldc.r4 1 add stloc.s 0x3c ldloc.s 0x3c ldc.r4 1 add stloc.s 0x3d ldloc.s 0x3d ldc.r4 1 add stloc.s 0x3e ldloc.s 0x3e ldc.r4 1 add stloc.s 0x3f ldloc.s 0x3f ldc.r4 1 add stloc.s 0x40 ldloc.s 0x40 ldc.r4 1 add stloc.s 0x41 ldloc.s 0x41 ldc.r4 1 add stloc.s 0x42 ldloc.s 0x42 ldc.r4 1 add stloc.s 0x43 ldloc.s 0x43 ldc.r4 1 add stloc.s 0x44 ldloc.s 0x44 ldc.r4 1 add stloc.s 0x45 ldloc.s 0x45 ldc.r4 1 add stloc.s 0x46 ldloc.s 0x46 ldc.r4 1 add stloc.s 0x47 ldloc.s 0x47 ldc.r4 1 add stloc.s 0x48 ldloc.s 0x48 ldc.r4 1 add stloc.s 0x49 ldloc.s 0x49 ldc.r4 1 add stloc.s 0x4a ldloc.s 0x4a ldc.r4 1 add stloc.s 0x4b ldloc.s 0x4b ldc.r4 1 add stloc.s 0x4c ldloc.s 0x4c ldc.r4 1 add stloc.s 0x4d ldloc.s 0x4d ldc.r4 1 add stloc.s 0x4e ldloc.s 0x4e ldc.r4 1 add stloc.s 0x4f ldloc.s 0x4f ldc.r4 1 add stloc.s 0x50 ldloc.s 0x50 ldc.r4 1 add stloc.s 0x51 ldloc.s 0x51 ldc.r4 1 add stloc.s 0x52 ldloc.s 0x52 ldc.r4 1 add stloc.s 0x53 ldloc.s 0x53 ldc.r4 1 add stloc.s 0x54 ldloc.s 0x54 ldc.r4 1 add stloc.s 0x55 ldloc.s 0x55 ldc.r4 1 add stloc.s 0x56 ldloc.s 0x56 ldc.r4 1 add stloc.s 0x57 ldloc.s 0x57 ldc.r4 1 add stloc.s 0x58 ldloc.s 0x58 ldc.r4 1 add stloc.s 0x59 ldloc.s 0x59 ldc.r4 1 add stloc.s 0x5a ldloc.s 0x5a ldc.r4 1 add stloc.s 0x5b ldloc.s 0x5b ldc.r4 1 add stloc.s 0x5c ldloc.s 0x5c ldc.r4 1 add stloc.s 0x5d ldloc.s 0x5d ldc.r4 1 add stloc.s 0x5e ldloc.s 0x5e ldc.r4 1 add stloc.s 0x5f ldloc.s 0x5f ldc.r4 1 add stloc.s 0x60 ldloc.s 0x60 ldc.r4 1 add stloc.s 0x61 ldloc.s 0x61 ldc.r4 1 add stloc.s 0x62 ldloc.s 0x62 ldc.r4 1 add stloc.s 0x63 ldloc.s 0x63 ldc.r4 1 add stloc.s 0x64 ldloc.s 0x64 ldc.r4 1 add stloc.s 0x65 ldloc.s 0x65 ldc.r4 1 add stloc.s 0x66 ldloc.s 0x66 ldc.r4 1 add stloc.s 0x67 ldloc.s 0x67 ldc.r4 1 add stloc.s 0x68 ldloc.s 0x68 ldc.r4 1 add stloc.s 0x69 ldloc.s 0x69 ldc.r4 1 add stloc.s 0x6a ldloc.s 0x6a ldc.r4 1 add stloc.s 0x6b ldloc.s 0x6b ldc.r4 1 add stloc.s 0x6c ldloc.s 0x6c ldc.r4 1 add stloc.s 0x6d ldloc.s 0x6d ldc.r4 1 add stloc.s 0x6e ldloc.s 0x6e ldc.r4 1 add stloc.s 0x6f ldloc.s 0x6f ldc.r4 1 add stloc.s 0x70 ldloc.s 0x70 ldc.r4 1 add stloc.s 0x71 ldloc.s 0x71 ldc.r4 1 add stloc.s 0x72 ldloc.s 0x72 ldc.r4 1 add stloc.s 0x73 ldloc.s 0x73 ldc.r4 1 add stloc.s 0x74 ldloc.s 0x74 ldc.r4 1 add stloc.s 0x75 ldloc.s 0x75 ldc.r4 1 add stloc.s 0x76 ldloc.s 0x76 ldc.r4 1 add stloc.s 0x77 ldloc.s 0x77 ldc.r4 1 add stloc.s 0x78 ldloc.s 0x78 ldc.r4 1 add stloc.s 0x79 ldloc.s 0x79 ldc.r4 1 add stloc.s 0x7a ldloc.s 0x7a ldc.r4 1 add stloc.s 0x7b ldloc.s 0x7b ldc.r4 1 add stloc.s 0x7c ldloc.s 0x7c ldc.r4 1 add stloc.s 0x7d ldloc.s 0x7d ldc.r4 1 add stloc.s 0x7e ldloc.s 0x7e ldc.r4 1 add stloc.s 0x7f ldloc.s 0x7f ldc.r4 1 add stloc.s 0x80 ldloc.s 0x80 ldc.r4 1 add stloc.s 0x81 ldloc.s 0x81 ldc.r4 1 add stloc.s 0x82 ldloc.s 0x82 ldc.r4 1 add stloc.s 0x83 ldloc.s 0x83 ldc.r4 1 add stloc.s 0x84 ldloc.s 0x84 ldc.r4 1 add stloc.s 0x85 ldloc.s 0x85 ldc.r4 1 add stloc.s 0x86 ldloc.s 0x86 ldc.r4 1 add stloc.s 0x87 ldloc.s 0x87 ldc.r4 1 add stloc.s 0x88 ldloc.s 0x88 ldc.r4 1 add stloc.s 0x89 ldloc.s 0x89 ldc.r4 1 add stloc.s 0x8a ldloc.s 0x8a ldc.r4 1 add stloc.s 0x8b ldloc.s 0x8b ldc.r4 1 add stloc.s 0x8c ldloc.s 0x8c ldc.r4 1 add stloc.s 0x8d ldloc.s 0x8d ldc.r4 1 add stloc.s 0x8e ldloc.s 0x8e ldc.r4 1 add stloc.s 0x8f ldloc.s 0x8f ldc.r4 1 add stloc.s 0x90 ldloc.s 0x90 ldc.r4 1 add stloc.s 0x91 ldloc.s 0x91 ldc.r4 1 add stloc.s 0x92 ldloc.s 0x92 ldc.r4 1 add stloc.s 0x93 ldloc.s 0x93 ldc.r4 1 add stloc.s 0x94 ldloc.s 0x94 ldc.r4 1 add stloc.s 0x95 ldloc.s 0x95 ldc.r4 1 add stloc.s 0x96 ldloc.s 0x96 ldc.r4 1 add stloc.s 0x97 ldloc.s 0x97 ldc.r4 1 add stloc.s 0x98 ldloc.s 0x98 ldc.r4 1 add stloc.s 0x99 ldloc.s 0x99 ldc.r4 1 add stloc.s 0x9a ldloc.s 0x9a ldc.r4 1 add stloc.s 0x9b ldloc.s 0x9b ldc.r4 1 add stloc.s 0x9c ldloc.s 0x9c ldc.r4 1 add stloc.s 0x9d ldloc.s 0x9d ldc.r4 1 add stloc.s 0x9e ldloc.s 0x9e ldc.r4 1 add stloc.s 0x9f ldloc.s 0x9f ldc.r4 1 add stloc.s 0xa0 ldloc.s 0xa0 ldc.r4 1 add stloc.s 0xa1 ldloc.s 0xa1 ldc.r4 1 add stloc.s 0xa2 ldloc.s 0xa2 ldc.r4 1 add stloc.s 0xa3 ldloc.s 0xa3 ldc.r4 1 add stloc.s 0xa4 ldloc.s 0xa4 ldc.r4 1 add stloc.s 0xa5 ldloc.s 0xa5 ldc.r4 1 add stloc.s 0xa6 ldloc.s 0xa6 ldc.r4 1 add stloc.s 0xa7 ldloc.s 0xa7 ldc.r4 1 add stloc.s 0xa8 ldloc.s 0xa8 ldc.r4 1 add stloc.s 0xa9 ldloc.s 0xa9 ldc.r4 1 add stloc.s 0xaa ldloc.s 0xaa ldc.r4 1 add stloc.s 0xab ldloc.s 0xab ldc.r4 1 add stloc.s 0xac ldloc.s 0xac ldc.r4 1 add stloc.s 0xad ldloc.s 0xad ldc.r4 1 add stloc.s 0xae ldloc.s 0xae ldc.r4 1 add stloc.s 0xaf ldloc.s 0xaf ldc.r4 1 add stloc.s 0xb0 ldloc.s 0xb0 ldc.r4 1 add stloc.s 0xb1 ldloc.s 0xb1 ldc.r4 1 add stloc.s 0xb2 ldloc.s 0xb2 ldc.r4 1 add stloc.s 0xb3 ldloc.s 0xb3 ldc.r4 1 add stloc.s 0xb4 ldloc.s 0xb4 ldc.r4 1 add stloc.s 0xb5 ldloc.s 0xb5 ldc.r4 1 add stloc.s 0xb6 ldloc.s 0xb6 ldc.r4 1 add stloc.s 0xb7 ldloc.s 0xb7 ldc.r4 1 add stloc.s 0xb8 ldloc.s 0xb8 ldc.r4 1 add stloc.s 0xb9 ldloc.s 0xb9 ldc.r4 1 add stloc.s 0xba ldloc.s 0xba ldc.r4 1 add stloc.s 0xbb ldloc.s 0xbb ldc.r4 1 add stloc.s 0xbc ldloc.s 0xbc ldc.r4 1 add stloc.s 0xbd ldloc.s 0xbd ldc.r4 1 add stloc.s 0xbe ldloc.s 0xbe ldc.r4 1 add stloc.s 0xbf ldloc.s 0xbf ldc.r4 1 add stloc.s 0xc0 ldloc.s 0xc0 ldc.r4 1 add stloc.s 0xc1 ldloc.s 0xc1 ldc.r4 1 add stloc.s 0xc2 ldloc.s 0xc2 ldc.r4 1 add stloc.s 0xc3 ldloc.s 0xc3 ldc.r4 1 add stloc.s 0xc4 ldloc.s 0xc4 ldc.r4 1 add stloc.s 0xc5 ldloc.s 0xc5 ldc.r4 1 add stloc.s 0xc6 ldloc.s 0xc6 ldc.r4 1 add stloc.s 0xc7 ldloc.s 0xc7 ldc.r4 1 add stloc.s 0xc8 ldloc.s 0xc8 ldc.r4 1 add stloc.s 0xc9 ldloc.s 0xc9 ldc.r4 1 add stloc.s 0xca ldloc.s 0xca ldc.r4 1 add stloc.s 0xcb ldloc.s 0xcb ldc.r4 1 add stloc.s 0xcc ldloc.s 0xcc ldc.r4 1 add stloc.s 0xcd ldloc.s 0xcd ldc.r4 1 add stloc.s 0xce ldloc.s 0xce ldc.r4 1 add stloc.s 0xcf ldloc.s 0xcf ldc.r4 1 add stloc.s 0xd0 ldloc.s 0xd0 ldc.r4 1 add stloc.s 0xd1 ldloc.s 0xd1 ldc.r4 1 add stloc.s 0xd2 ldloc.s 0xd2 ldc.r4 1 add stloc.s 0xd3 ldloc.s 0xd3 ldc.r4 1 add stloc.s 0xd4 ldloc.s 0xd4 ldc.r4 1 add stloc.s 0xd5 ldloc.s 0xd5 ldc.r4 1 add stloc.s 0xd6 ldloc.s 0xd6 ldc.r4 1 add stloc.s 0xd7 ldloc.s 0xd7 ldc.r4 1 add stloc.s 0xd8 ldloc.s 0xd8 ldc.r4 1 add stloc.s 0xd9 ldloc.s 0xd9 ldc.r4 1 add stloc.s 0xda ldloc.s 0xda ldc.r4 1 add stloc.s 0xdb ldloc.s 0xdb ldc.r4 1 add stloc.s 0xdc ldloc.s 0xdc ldc.r4 1 add stloc.s 0xdd ldloc.s 0xdd ldc.r4 1 add stloc.s 0xde ldloc.s 0xde ldc.r4 1 add stloc.s 0xdf ldloc.s 0xdf ldc.r4 1 add stloc.s 0xe0 ldloc.s 0xe0 ldc.r4 1 add stloc.s 0xe1 ldloc.s 0xe1 ldc.r4 1 add stloc.s 0xe2 ldloc.s 0xe2 ldc.r4 1 add stloc.s 0xe3 ldloc.s 0xe3 ldc.r4 1 add stloc.s 0xe4 ldloc.s 0xe4 ldc.r4 1 add stloc.s 0xe5 ldloc.s 0xe5 ldc.r4 1 add stloc.s 0xe6 ldloc.s 0xe6 ldc.r4 1 add stloc.s 0xe7 ldloc.s 0xe7 ldc.r4 1 add stloc.s 0xe8 ldloc.s 0xe8 ldc.r4 1 add stloc.s 0xe9 ldloc.s 0xe9 ldc.r4 1 add stloc.s 0xea ldloc.s 0xea ldc.r4 1 add stloc.s 0xeb ldloc.s 0xeb ldc.r4 1 add stloc.s 0xec ldloc.s 0xec ldc.r4 1 add stloc.s 0xed ldloc.s 0xed ldc.r4 1 add stloc.s 0xee ldloc.s 0xee ldc.r4 1 add stloc.s 0xef ldloc.s 0xef ldc.r4 1 add stloc.s 0xf0 ldloc.s 0xf0 ldc.r4 1 add stloc.s 0xf1 ldloc.s 0xf1 ldc.r4 1 add stloc.s 0xf2 ldloc.s 0xf2 ldc.r4 1 add stloc.s 0xf3 ldloc.s 0xf3 ldc.r4 1 add stloc.s 0xf4 ldloc.s 0xf4 ldc.r4 1 add stloc.s 0xf5 ldloc.s 0xf5 ldc.r4 1 add stloc.s 0xf6 ldloc.s 0xf6 ldc.r4 1 add stloc.s 0xf7 ldloc.s 0xf7 ldc.r4 1 add stloc.s 0xf8 ldloc.s 0xf8 ldc.r4 1 add stloc.s 0xf9 ldloc.s 0xf9 ldc.r4 1 add stloc.s 0xfa ldloc.s 0xfa ldc.r4 1 add stloc.s 0xfb ldloc.s 0xfb ldc.r4 1 add stloc.s 0xfc ldloc.s 0xfc ldc.r4 1 add stloc.s 0xfd ldloc.s 0xfd ldc.r4 1 add stloc.s 0xfe ldloc.s 0xfe ldc.r4 1 add stloc.s 0xff ldloc.s 0xff ldc.r4 1 add stloc.s 0x00 ldloc 0 ldc.r4 256 ceq brfalse FAIL ldc.i4.1 ret FAIL: ldc.i4 0 ret } .method public static int32 main(class [mscorlib]System.String[]) { .entrypoint .maxstack 2 call int32 ldloc_s_r4::test_float32() ldc.i4.1 ceq brfalse FAIL ldc.i4 100 ret FAIL: ldc.i4 0x0 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 ldloc_s_r4 {} .class ldloc_s_r4 { .method public static int32 test_float32() { .locals (float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32, float32) .zeroinit .maxstack 2 ldloc.s 0x00 ldc.r4 1 add stloc.s 0x01 ldloc.s 0x01 ldc.r4 1 add stloc.s 0x02 ldloc.s 0x02 ldc.r4 1 add stloc.s 0x03 ldloc.s 0x03 ldc.r4 1 add stloc.s 0x04 ldloc.s 0x04 ldc.r4 1 add stloc.s 0x05 ldloc.s 0x05 ldc.r4 1 add stloc.s 0x06 ldloc.s 0x06 ldc.r4 1 add stloc.s 0x07 ldloc.s 0x07 ldc.r4 1 add stloc.s 0x08 ldloc.s 0x08 ldc.r4 1 add stloc.s 0x09 ldloc.s 0x09 ldc.r4 1 add stloc.s 0x0a ldloc.s 0x0a ldc.r4 1 add stloc.s 0x0b ldloc.s 0x0b ldc.r4 1 add stloc.s 0x0c ldloc.s 0x0c ldc.r4 1 add stloc.s 0x0d ldloc.s 0x0d ldc.r4 1 add stloc.s 0x0e ldloc.s 0x0e ldc.r4 1 add stloc.s 0x0f ldloc.s 0x0f ldc.r4 1 add stloc.s 0x10 ldloc.s 0x10 ldc.r4 1 add stloc.s 0x11 ldloc.s 0x11 ldc.r4 1 add stloc.s 0x12 ldloc.s 0x12 ldc.r4 1 add stloc.s 0x13 ldloc.s 0x13 ldc.r4 1 add stloc.s 0x14 ldloc.s 0x14 ldc.r4 1 add stloc.s 0x15 ldloc.s 0x15 ldc.r4 1 add stloc.s 0x8 ldloc.s 0x8 ldc.r4 1 add stloc.s 0x17 ldloc.s 0x17 ldc.r4 1 add stloc.s 0x18 ldloc.s 0x18 ldc.r4 1 add stloc.s 0x19 ldloc.s 0x19 ldc.r4 1 add stloc.s 0x1a ldloc.s 0x1a ldc.r4 1 add stloc.s 0x1b ldloc.s 0x1b ldc.r4 1 add stloc.s 0x1c ldloc.s 0x1c ldc.r4 1 add stloc.s 0x1d ldloc.s 0x1d ldc.r4 1 add stloc.s 0x1e ldloc.s 0x1e ldc.r4 1 add stloc.s 0x1f ldloc.s 0x1f ldc.r4 1 add stloc.s 0x20 ldloc.s 0x20 ldc.r4 1 add stloc.s 0x21 ldloc.s 0x21 ldc.r4 1 add stloc.s 0x22 ldloc.s 0x22 ldc.r4 1 add stloc.s 0x23 ldloc.s 0x23 ldc.r4 1 add stloc.s 0x24 ldloc.s 0x24 ldc.r4 1 add stloc.s 0x25 ldloc.s 0x25 ldc.r4 1 add stloc.s 0x26 ldloc.s 0x26 ldc.r4 1 add stloc.s 0x27 ldloc.s 0x27 ldc.r4 1 add stloc.s 0x28 ldloc.s 0x28 ldc.r4 1 add stloc.s 0x29 ldloc.s 0x29 ldc.r4 1 add stloc.s 0x2a ldloc.s 0x2a ldc.r4 1 add stloc.s 0x2b ldloc.s 0x2b ldc.r4 1 add stloc.s 0x2c ldloc.s 0x2c ldc.r4 1 add stloc.s 0x2d ldloc.s 0x2d ldc.r4 1 add stloc.s 0x2e ldloc.s 0x2e ldc.r4 1 add stloc.s 0x2f ldloc.s 0x2f ldc.r4 1 add stloc.s 0x30 ldloc.s 0x30 ldc.r4 1 add stloc.s 0x31 ldloc.s 0x31 ldc.r4 1 add stloc.s 0x8 ldloc.s 0x8 ldc.r4 1 add stloc.s 0x33 ldloc.s 0x33 ldc.r4 1 add stloc.s 0x34 ldloc.s 0x34 ldc.r4 1 add stloc.s 0x35 ldloc.s 0x35 ldc.r4 1 add stloc.s 0x36 ldloc.s 0x36 ldc.r4 1 add stloc.s 0x37 ldloc.s 0x37 ldc.r4 1 add stloc.s 0x38 ldloc.s 0x38 ldc.r4 1 add stloc.s 0x39 ldloc.s 0x39 ldc.r4 1 add stloc.s 0x3a ldloc.s 0x3a ldc.r4 1 add stloc.s 0x3b ldloc.s 0x3b ldc.r4 1 add stloc.s 0x3c ldloc.s 0x3c ldc.r4 1 add stloc.s 0x3d ldloc.s 0x3d ldc.r4 1 add stloc.s 0x3e ldloc.s 0x3e ldc.r4 1 add stloc.s 0x3f ldloc.s 0x3f ldc.r4 1 add stloc.s 0x40 ldloc.s 0x40 ldc.r4 1 add stloc.s 0x41 ldloc.s 0x41 ldc.r4 1 add stloc.s 0x42 ldloc.s 0x42 ldc.r4 1 add stloc.s 0x43 ldloc.s 0x43 ldc.r4 1 add stloc.s 0x44 ldloc.s 0x44 ldc.r4 1 add stloc.s 0x45 ldloc.s 0x45 ldc.r4 1 add stloc.s 0x46 ldloc.s 0x46 ldc.r4 1 add stloc.s 0x47 ldloc.s 0x47 ldc.r4 1 add stloc.s 0x48 ldloc.s 0x48 ldc.r4 1 add stloc.s 0x49 ldloc.s 0x49 ldc.r4 1 add stloc.s 0x4a ldloc.s 0x4a ldc.r4 1 add stloc.s 0x4b ldloc.s 0x4b ldc.r4 1 add stloc.s 0x4c ldloc.s 0x4c ldc.r4 1 add stloc.s 0x4d ldloc.s 0x4d ldc.r4 1 add stloc.s 0x4e ldloc.s 0x4e ldc.r4 1 add stloc.s 0x4f ldloc.s 0x4f ldc.r4 1 add stloc.s 0x50 ldloc.s 0x50 ldc.r4 1 add stloc.s 0x51 ldloc.s 0x51 ldc.r4 1 add stloc.s 0x52 ldloc.s 0x52 ldc.r4 1 add stloc.s 0x53 ldloc.s 0x53 ldc.r4 1 add stloc.s 0x54 ldloc.s 0x54 ldc.r4 1 add stloc.s 0x55 ldloc.s 0x55 ldc.r4 1 add stloc.s 0x56 ldloc.s 0x56 ldc.r4 1 add stloc.s 0x57 ldloc.s 0x57 ldc.r4 1 add stloc.s 0x58 ldloc.s 0x58 ldc.r4 1 add stloc.s 0x59 ldloc.s 0x59 ldc.r4 1 add stloc.s 0x5a ldloc.s 0x5a ldc.r4 1 add stloc.s 0x5b ldloc.s 0x5b ldc.r4 1 add stloc.s 0x5c ldloc.s 0x5c ldc.r4 1 add stloc.s 0x5d ldloc.s 0x5d ldc.r4 1 add stloc.s 0x5e ldloc.s 0x5e ldc.r4 1 add stloc.s 0x5f ldloc.s 0x5f ldc.r4 1 add stloc.s 0x60 ldloc.s 0x60 ldc.r4 1 add stloc.s 0x61 ldloc.s 0x61 ldc.r4 1 add stloc.s 0x62 ldloc.s 0x62 ldc.r4 1 add stloc.s 0x63 ldloc.s 0x63 ldc.r4 1 add stloc.s 0x64 ldloc.s 0x64 ldc.r4 1 add stloc.s 0x65 ldloc.s 0x65 ldc.r4 1 add stloc.s 0x66 ldloc.s 0x66 ldc.r4 1 add stloc.s 0x67 ldloc.s 0x67 ldc.r4 1 add stloc.s 0x68 ldloc.s 0x68 ldc.r4 1 add stloc.s 0x69 ldloc.s 0x69 ldc.r4 1 add stloc.s 0x6a ldloc.s 0x6a ldc.r4 1 add stloc.s 0x6b ldloc.s 0x6b ldc.r4 1 add stloc.s 0x6c ldloc.s 0x6c ldc.r4 1 add stloc.s 0x6d ldloc.s 0x6d ldc.r4 1 add stloc.s 0x6e ldloc.s 0x6e ldc.r4 1 add stloc.s 0x6f ldloc.s 0x6f ldc.r4 1 add stloc.s 0x70 ldloc.s 0x70 ldc.r4 1 add stloc.s 0x71 ldloc.s 0x71 ldc.r4 1 add stloc.s 0x72 ldloc.s 0x72 ldc.r4 1 add stloc.s 0x73 ldloc.s 0x73 ldc.r4 1 add stloc.s 0x74 ldloc.s 0x74 ldc.r4 1 add stloc.s 0x75 ldloc.s 0x75 ldc.r4 1 add stloc.s 0x76 ldloc.s 0x76 ldc.r4 1 add stloc.s 0x77 ldloc.s 0x77 ldc.r4 1 add stloc.s 0x78 ldloc.s 0x78 ldc.r4 1 add stloc.s 0x79 ldloc.s 0x79 ldc.r4 1 add stloc.s 0x7a ldloc.s 0x7a ldc.r4 1 add stloc.s 0x7b ldloc.s 0x7b ldc.r4 1 add stloc.s 0x7c ldloc.s 0x7c ldc.r4 1 add stloc.s 0x7d ldloc.s 0x7d ldc.r4 1 add stloc.s 0x7e ldloc.s 0x7e ldc.r4 1 add stloc.s 0x7f ldloc.s 0x7f ldc.r4 1 add stloc.s 0x80 ldloc.s 0x80 ldc.r4 1 add stloc.s 0x81 ldloc.s 0x81 ldc.r4 1 add stloc.s 0x82 ldloc.s 0x82 ldc.r4 1 add stloc.s 0x83 ldloc.s 0x83 ldc.r4 1 add stloc.s 0x84 ldloc.s 0x84 ldc.r4 1 add stloc.s 0x85 ldloc.s 0x85 ldc.r4 1 add stloc.s 0x86 ldloc.s 0x86 ldc.r4 1 add stloc.s 0x87 ldloc.s 0x87 ldc.r4 1 add stloc.s 0x88 ldloc.s 0x88 ldc.r4 1 add stloc.s 0x89 ldloc.s 0x89 ldc.r4 1 add stloc.s 0x8a ldloc.s 0x8a ldc.r4 1 add stloc.s 0x8b ldloc.s 0x8b ldc.r4 1 add stloc.s 0x8c ldloc.s 0x8c ldc.r4 1 add stloc.s 0x8d ldloc.s 0x8d ldc.r4 1 add stloc.s 0x8e ldloc.s 0x8e ldc.r4 1 add stloc.s 0x8f ldloc.s 0x8f ldc.r4 1 add stloc.s 0x90 ldloc.s 0x90 ldc.r4 1 add stloc.s 0x91 ldloc.s 0x91 ldc.r4 1 add stloc.s 0x92 ldloc.s 0x92 ldc.r4 1 add stloc.s 0x93 ldloc.s 0x93 ldc.r4 1 add stloc.s 0x94 ldloc.s 0x94 ldc.r4 1 add stloc.s 0x95 ldloc.s 0x95 ldc.r4 1 add stloc.s 0x96 ldloc.s 0x96 ldc.r4 1 add stloc.s 0x97 ldloc.s 0x97 ldc.r4 1 add stloc.s 0x98 ldloc.s 0x98 ldc.r4 1 add stloc.s 0x99 ldloc.s 0x99 ldc.r4 1 add stloc.s 0x9a ldloc.s 0x9a ldc.r4 1 add stloc.s 0x9b ldloc.s 0x9b ldc.r4 1 add stloc.s 0x9c ldloc.s 0x9c ldc.r4 1 add stloc.s 0x9d ldloc.s 0x9d ldc.r4 1 add stloc.s 0x9e ldloc.s 0x9e ldc.r4 1 add stloc.s 0x9f ldloc.s 0x9f ldc.r4 1 add stloc.s 0xa0 ldloc.s 0xa0 ldc.r4 1 add stloc.s 0xa1 ldloc.s 0xa1 ldc.r4 1 add stloc.s 0xa2 ldloc.s 0xa2 ldc.r4 1 add stloc.s 0xa3 ldloc.s 0xa3 ldc.r4 1 add stloc.s 0xa4 ldloc.s 0xa4 ldc.r4 1 add stloc.s 0xa5 ldloc.s 0xa5 ldc.r4 1 add stloc.s 0xa6 ldloc.s 0xa6 ldc.r4 1 add stloc.s 0xa7 ldloc.s 0xa7 ldc.r4 1 add stloc.s 0xa8 ldloc.s 0xa8 ldc.r4 1 add stloc.s 0xa9 ldloc.s 0xa9 ldc.r4 1 add stloc.s 0xaa ldloc.s 0xaa ldc.r4 1 add stloc.s 0xab ldloc.s 0xab ldc.r4 1 add stloc.s 0xac ldloc.s 0xac ldc.r4 1 add stloc.s 0xad ldloc.s 0xad ldc.r4 1 add stloc.s 0xae ldloc.s 0xae ldc.r4 1 add stloc.s 0xaf ldloc.s 0xaf ldc.r4 1 add stloc.s 0xb0 ldloc.s 0xb0 ldc.r4 1 add stloc.s 0xb1 ldloc.s 0xb1 ldc.r4 1 add stloc.s 0xb2 ldloc.s 0xb2 ldc.r4 1 add stloc.s 0xb3 ldloc.s 0xb3 ldc.r4 1 add stloc.s 0xb4 ldloc.s 0xb4 ldc.r4 1 add stloc.s 0xb5 ldloc.s 0xb5 ldc.r4 1 add stloc.s 0xb6 ldloc.s 0xb6 ldc.r4 1 add stloc.s 0xb7 ldloc.s 0xb7 ldc.r4 1 add stloc.s 0xb8 ldloc.s 0xb8 ldc.r4 1 add stloc.s 0xb9 ldloc.s 0xb9 ldc.r4 1 add stloc.s 0xba ldloc.s 0xba ldc.r4 1 add stloc.s 0xbb ldloc.s 0xbb ldc.r4 1 add stloc.s 0xbc ldloc.s 0xbc ldc.r4 1 add stloc.s 0xbd ldloc.s 0xbd ldc.r4 1 add stloc.s 0xbe ldloc.s 0xbe ldc.r4 1 add stloc.s 0xbf ldloc.s 0xbf ldc.r4 1 add stloc.s 0xc0 ldloc.s 0xc0 ldc.r4 1 add stloc.s 0xc1 ldloc.s 0xc1 ldc.r4 1 add stloc.s 0xc2 ldloc.s 0xc2 ldc.r4 1 add stloc.s 0xc3 ldloc.s 0xc3 ldc.r4 1 add stloc.s 0xc4 ldloc.s 0xc4 ldc.r4 1 add stloc.s 0xc5 ldloc.s 0xc5 ldc.r4 1 add stloc.s 0xc6 ldloc.s 0xc6 ldc.r4 1 add stloc.s 0xc7 ldloc.s 0xc7 ldc.r4 1 add stloc.s 0xc8 ldloc.s 0xc8 ldc.r4 1 add stloc.s 0xc9 ldloc.s 0xc9 ldc.r4 1 add stloc.s 0xca ldloc.s 0xca ldc.r4 1 add stloc.s 0xcb ldloc.s 0xcb ldc.r4 1 add stloc.s 0xcc ldloc.s 0xcc ldc.r4 1 add stloc.s 0xcd ldloc.s 0xcd ldc.r4 1 add stloc.s 0xce ldloc.s 0xce ldc.r4 1 add stloc.s 0xcf ldloc.s 0xcf ldc.r4 1 add stloc.s 0xd0 ldloc.s 0xd0 ldc.r4 1 add stloc.s 0xd1 ldloc.s 0xd1 ldc.r4 1 add stloc.s 0xd2 ldloc.s 0xd2 ldc.r4 1 add stloc.s 0xd3 ldloc.s 0xd3 ldc.r4 1 add stloc.s 0xd4 ldloc.s 0xd4 ldc.r4 1 add stloc.s 0xd5 ldloc.s 0xd5 ldc.r4 1 add stloc.s 0xd6 ldloc.s 0xd6 ldc.r4 1 add stloc.s 0xd7 ldloc.s 0xd7 ldc.r4 1 add stloc.s 0xd8 ldloc.s 0xd8 ldc.r4 1 add stloc.s 0xd9 ldloc.s 0xd9 ldc.r4 1 add stloc.s 0xda ldloc.s 0xda ldc.r4 1 add stloc.s 0xdb ldloc.s 0xdb ldc.r4 1 add stloc.s 0xdc ldloc.s 0xdc ldc.r4 1 add stloc.s 0xdd ldloc.s 0xdd ldc.r4 1 add stloc.s 0xde ldloc.s 0xde ldc.r4 1 add stloc.s 0xdf ldloc.s 0xdf ldc.r4 1 add stloc.s 0xe0 ldloc.s 0xe0 ldc.r4 1 add stloc.s 0xe1 ldloc.s 0xe1 ldc.r4 1 add stloc.s 0xe2 ldloc.s 0xe2 ldc.r4 1 add stloc.s 0xe3 ldloc.s 0xe3 ldc.r4 1 add stloc.s 0xe4 ldloc.s 0xe4 ldc.r4 1 add stloc.s 0xe5 ldloc.s 0xe5 ldc.r4 1 add stloc.s 0xe6 ldloc.s 0xe6 ldc.r4 1 add stloc.s 0xe7 ldloc.s 0xe7 ldc.r4 1 add stloc.s 0xe8 ldloc.s 0xe8 ldc.r4 1 add stloc.s 0xe9 ldloc.s 0xe9 ldc.r4 1 add stloc.s 0xea ldloc.s 0xea ldc.r4 1 add stloc.s 0xeb ldloc.s 0xeb ldc.r4 1 add stloc.s 0xec ldloc.s 0xec ldc.r4 1 add stloc.s 0xed ldloc.s 0xed ldc.r4 1 add stloc.s 0xee ldloc.s 0xee ldc.r4 1 add stloc.s 0xef ldloc.s 0xef ldc.r4 1 add stloc.s 0xf0 ldloc.s 0xf0 ldc.r4 1 add stloc.s 0xf1 ldloc.s 0xf1 ldc.r4 1 add stloc.s 0xf2 ldloc.s 0xf2 ldc.r4 1 add stloc.s 0xf3 ldloc.s 0xf3 ldc.r4 1 add stloc.s 0xf4 ldloc.s 0xf4 ldc.r4 1 add stloc.s 0xf5 ldloc.s 0xf5 ldc.r4 1 add stloc.s 0xf6 ldloc.s 0xf6 ldc.r4 1 add stloc.s 0xf7 ldloc.s 0xf7 ldc.r4 1 add stloc.s 0xf8 ldloc.s 0xf8 ldc.r4 1 add stloc.s 0xf9 ldloc.s 0xf9 ldc.r4 1 add stloc.s 0xfa ldloc.s 0xfa ldc.r4 1 add stloc.s 0xfb ldloc.s 0xfb ldc.r4 1 add stloc.s 0xfc ldloc.s 0xfc ldc.r4 1 add stloc.s 0xfd ldloc.s 0xfd ldc.r4 1 add stloc.s 0xfe ldloc.s 0xfe ldc.r4 1 add stloc.s 0xff ldloc.s 0xff ldc.r4 1 add stloc.s 0x00 ldloc 0 ldc.r4 256 ceq brfalse FAIL ldc.i4.1 ret FAIL: ldc.i4 0 ret } .method public static int32 main(class [mscorlib]System.String[]) { .entrypoint .maxstack 2 call int32 ldloc_s_r4::test_float32() ldc.i4.1 ceq brfalse FAIL ldc.i4 100 ret FAIL: ldc.i4 0x0 ret } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Data.Common/src/System/Data/DataTableNewRowEvent.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.Data { public sealed class DataTableNewRowEventArgs : EventArgs { public DataTableNewRowEventArgs(DataRow dataRow) { Row = dataRow; } public DataRow Row { 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.Data { public sealed class DataTableNewRowEventArgs : EventArgs { public DataTableNewRowEventArgs(DataRow dataRow) { Row = dataRow; } public DataRow Row { get; } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/HardwareIntrinsics/X86/Avx2/Min.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\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 MinByte() { var test = new SimpleBinaryOpTest__MinByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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__MinByte { 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 != 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<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 Vector256<Byte> _fld1; public Vector256<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<Vector256<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MinByte testClass) { var result = Avx2.Min(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MinByte testClass) { fixed (Vector256<Byte>* pFld1 = &_fld1) fixed (Vector256<Byte>* pFld2 = &_fld2) { var result = Avx2.Min( Avx.LoadVector256((Byte*)(pFld1)), Avx.LoadVector256((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector256<Byte> _clsVar1; private static Vector256<Byte> _clsVar2; private Vector256<Byte> _fld1; private Vector256<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MinByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); } public SimpleBinaryOpTest__MinByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<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 => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Min( Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<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 = Avx2.Min( Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Byte*)(_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 = Avx2.Min( Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((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(Avx2).GetMethod(nameof(Avx2.Min), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Min), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Min), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Min( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Byte>* pClsVar1 = &_clsVar1) fixed (Vector256<Byte>* pClsVar2 = &_clsVar2) { var result = Avx2.Min( Avx.LoadVector256((Byte*)(pClsVar1)), Avx.LoadVector256((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<Vector256<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr); var result = Avx2.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 = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)); var result = Avx2.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 = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)); var result = Avx2.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__MinByte(); var result = Avx2.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__MinByte(); fixed (Vector256<Byte>* pFld1 = &test._fld1) fixed (Vector256<Byte>* pFld2 = &test._fld2) { var result = Avx2.Min( Avx.LoadVector256((Byte*)(pFld1)), Avx.LoadVector256((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Min(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Byte>* pFld1 = &_fld1) fixed (Vector256<Byte>* pFld2 = &_fld2) { var result = Avx2.Min( Avx.LoadVector256((Byte*)(pFld1)), Avx.LoadVector256((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 = Avx2.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 = Avx2.Min( Avx.LoadVector256((Byte*)(&test._fld1)), Avx.LoadVector256((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(Vector256<Byte> op1, Vector256<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<Vector256<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<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] 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(Avx2)}.{nameof(Avx2.Min)}<Byte>(Vector256<Byte>, Vector256<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\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 MinByte() { var test = new SimpleBinaryOpTest__MinByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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__MinByte { 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 != 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<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 Vector256<Byte> _fld1; public Vector256<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<Vector256<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MinByte testClass) { var result = Avx2.Min(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MinByte testClass) { fixed (Vector256<Byte>* pFld1 = &_fld1) fixed (Vector256<Byte>* pFld2 = &_fld2) { var result = Avx2.Min( Avx.LoadVector256((Byte*)(pFld1)), Avx.LoadVector256((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector256<Byte> _clsVar1; private static Vector256<Byte> _clsVar2; private Vector256<Byte> _fld1; private Vector256<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MinByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); } public SimpleBinaryOpTest__MinByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<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 => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Min( Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<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 = Avx2.Min( Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Byte*)(_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 = Avx2.Min( Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((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(Avx2).GetMethod(nameof(Avx2.Min), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Min), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Min), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Min( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Byte>* pClsVar1 = &_clsVar1) fixed (Vector256<Byte>* pClsVar2 = &_clsVar2) { var result = Avx2.Min( Avx.LoadVector256((Byte*)(pClsVar1)), Avx.LoadVector256((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<Vector256<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr); var result = Avx2.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 = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)); var result = Avx2.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 = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)); var result = Avx2.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__MinByte(); var result = Avx2.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__MinByte(); fixed (Vector256<Byte>* pFld1 = &test._fld1) fixed (Vector256<Byte>* pFld2 = &test._fld2) { var result = Avx2.Min( Avx.LoadVector256((Byte*)(pFld1)), Avx.LoadVector256((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Min(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Byte>* pFld1 = &_fld1) fixed (Vector256<Byte>* pFld2 = &_fld2) { var result = Avx2.Min( Avx.LoadVector256((Byte*)(pFld1)), Avx.LoadVector256((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 = Avx2.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 = Avx2.Min( Avx.LoadVector256((Byte*)(&test._fld1)), Avx.LoadVector256((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(Vector256<Byte> op1, Vector256<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<Vector256<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<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] 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(Avx2)}.{nameof(Avx2.Min)}<Byte>(Vector256<Byte>, Vector256<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,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Private.Xml/tests/XmlSchema/TestFiles/TestData/bug382119_red1.xsd
<?xml version="1.0" encoding="utf-8" ?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="includeCmplxType"> <xs:choice> <xs:element name="e1_inc" type="xs:string"/> <xs:element name="e2_inc" type="xs:string"/> </xs:choice> </xs:complexType> </xs:schema>
<?xml version="1.0" encoding="utf-8" ?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="includeCmplxType"> <xs:choice> <xs:element name="e1_inc" type="xs:string"/> <xs:element name="e2_inc" type="xs:string"/> </xs:choice> </xs:complexType> </xs:schema>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Diagnostics.PerformanceCounter/ref/System.Diagnostics.PerformanceCounter.netframework.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. // ------------------------------------------------------------------------------ using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(System.Diagnostics.CounterCreationData))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.CounterCreationDataCollection))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.CounterSample))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.CounterSampleCalculator))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.ICollectData))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.InstanceData))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.InstanceDataCollection))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.InstanceDataCollectionCollection))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceCounter))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceCounterCategory))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceCounterCategoryType))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceCounterInstanceLifetime))] #pragma warning disable 0618 [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceCounterManager))] #pragma warning restore 0618 [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceCounterType))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceData.CounterData))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceData.CounterSet))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceData.CounterSetInstance))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceData.CounterSetInstanceCounterDataSet))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceData.CounterSetInstanceType))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceData.CounterType))]
// 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. // ------------------------------------------------------------------------------ using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(System.Diagnostics.CounterCreationData))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.CounterCreationDataCollection))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.CounterSample))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.CounterSampleCalculator))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.ICollectData))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.InstanceData))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.InstanceDataCollection))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.InstanceDataCollectionCollection))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceCounter))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceCounterCategory))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceCounterCategoryType))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceCounterInstanceLifetime))] #pragma warning disable 0618 [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceCounterManager))] #pragma warning restore 0618 [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceCounterType))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceData.CounterData))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceData.CounterSet))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceData.CounterSetInstance))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceData.CounterSetInstanceCounterDataSet))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceData.CounterSetInstanceType))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.PerformanceData.CounterType))]
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/coreclr/pal/src/libunwind/src/s390x/Lglobal.c
#define UNW_LOCAL_ONLY #include "config.h" #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gglobal.c" #endif
#define UNW_LOCAL_ONLY #include "config.h" #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gglobal.c" #endif
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/GC/Scenarios/GCSimulator/GCSimulator_57.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <GCStressIncompatible>true</GCStressIncompatible> <CLRTestExecutionArguments>-t 1 -tp 0 -dz 17 -sdz 8517 -dc 10000 -sdc 5000 -lt 2 -f -dp 0.4 -dw 0.4</CLRTestExecutionArguments> <IsGCSimulatorTest>true</IsGCSimulatorTest> <CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="GCSimulator.cs" /> <Compile Include="lifetimefx.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <GCStressIncompatible>true</GCStressIncompatible> <CLRTestExecutionArguments>-t 1 -tp 0 -dz 17 -sdz 8517 -dc 10000 -sdc 5000 -lt 2 -f -dp 0.4 -dw 0.4</CLRTestExecutionArguments> <IsGCSimulatorTest>true</IsGCSimulatorTest> <CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="GCSimulator.cs" /> <Compile Include="lifetimefx.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Private.Xml/src/Utils/DTDs/XHTML10/no_comments/xhtml-symbol.ent
<!ENTITY fnof "&#402;"> <!ENTITY Alpha "&#913;"> <!ENTITY Beta "&#914;"> <!ENTITY Gamma "&#915;"> <!ENTITY Delta "&#916;"> <!ENTITY Epsilon "&#917;"> <!ENTITY Zeta "&#918;"> <!ENTITY Eta "&#919;"> <!ENTITY Theta "&#920;"> <!ENTITY Iota "&#921;"> <!ENTITY Kappa "&#922;"> <!ENTITY Lambda "&#923;"> <!ENTITY Mu "&#924;"> <!ENTITY Nu "&#925;"> <!ENTITY Xi "&#926;"> <!ENTITY Omicron "&#927;"> <!ENTITY Pi "&#928;"> <!ENTITY Rho "&#929;"> <!ENTITY Sigma "&#931;"> <!ENTITY Tau "&#932;"> <!ENTITY Upsilon "&#933;"> <!ENTITY Phi "&#934;"> <!ENTITY Chi "&#935;"> <!ENTITY Psi "&#936;"> <!ENTITY Omega "&#937;"> <!ENTITY alpha "&#945;"> <!ENTITY beta "&#946;"> <!ENTITY gamma "&#947;"> <!ENTITY delta "&#948;"> <!ENTITY epsilon "&#949;"> <!ENTITY zeta "&#950;"> <!ENTITY eta "&#951;"> <!ENTITY theta "&#952;"> <!ENTITY iota "&#953;"> <!ENTITY kappa "&#954;"> <!ENTITY lambda "&#955;"> <!ENTITY mu "&#956;"> <!ENTITY nu "&#957;"> <!ENTITY xi "&#958;"> <!ENTITY omicron "&#959;"> <!ENTITY pi "&#960;"> <!ENTITY rho "&#961;"> <!ENTITY sigmaf "&#962;"> <!ENTITY sigma "&#963;"> <!ENTITY tau "&#964;"> <!ENTITY upsilon "&#965;"> <!ENTITY phi "&#966;"> <!ENTITY chi "&#967;"> <!ENTITY psi "&#968;"> <!ENTITY omega "&#969;"> <!ENTITY thetasym "&#977;"> <!ENTITY upsih "&#978;"> <!ENTITY piv "&#982;"> <!ENTITY bull "&#8226;"> <!ENTITY hellip "&#8230;"> <!ENTITY prime "&#8242;"> <!ENTITY Prime "&#8243;"> <!ENTITY oline "&#8254;"> <!ENTITY frasl "&#8260;"> <!ENTITY weierp "&#8472;"> <!ENTITY image "&#8465;"> <!ENTITY real "&#8476;"> <!ENTITY trade "&#8482;"> <!ENTITY alefsym "&#8501;"> <!ENTITY larr "&#8592;"> <!ENTITY uarr "&#8593;"> <!ENTITY rarr "&#8594;"> <!ENTITY darr "&#8595;"> <!ENTITY harr "&#8596;"> <!ENTITY crarr "&#8629;"> <!ENTITY lArr "&#8656;"> <!ENTITY uArr "&#8657;"> <!ENTITY rArr "&#8658;"> <!ENTITY dArr "&#8659;"> <!ENTITY hArr "&#8660;"> <!ENTITY forall "&#8704;"> <!ENTITY part "&#8706;"> <!ENTITY exist "&#8707;"> <!ENTITY empty "&#8709;"> <!ENTITY nabla "&#8711;"> <!ENTITY isin "&#8712;"> <!ENTITY notin "&#8713;"> <!ENTITY ni "&#8715;"> <!ENTITY prod "&#8719;"> <!ENTITY sum "&#8721;"> <!ENTITY minus "&#8722;"> <!ENTITY lowast "&#8727;"> <!ENTITY radic "&#8730;"> <!ENTITY prop "&#8733;"> <!ENTITY infin "&#8734;"> <!ENTITY ang "&#8736;"> <!ENTITY and "&#8743;"> <!ENTITY or "&#8744;"> <!ENTITY cap "&#8745;"> <!ENTITY cup "&#8746;"> <!ENTITY int "&#8747;"> <!ENTITY there4 "&#8756;"> <!ENTITY sim "&#8764;"> <!ENTITY cong "&#8773;"> <!ENTITY asymp "&#8776;"> <!ENTITY ne "&#8800;"> <!ENTITY equiv "&#8801;"> <!ENTITY le "&#8804;"> <!ENTITY ge "&#8805;"> <!ENTITY sub "&#8834;"> <!ENTITY sup "&#8835;"> <!ENTITY nsub "&#8836;"> <!ENTITY sube "&#8838;"> <!ENTITY supe "&#8839;"> <!ENTITY oplus "&#8853;"> <!ENTITY otimes "&#8855;"> <!ENTITY perp "&#8869;"> <!ENTITY sdot "&#8901;"> <!ENTITY lceil "&#8968;"> <!ENTITY rceil "&#8969;"> <!ENTITY lfloor "&#8970;"> <!ENTITY rfloor "&#8971;"> <!ENTITY lang "&#9001;"> <!ENTITY rang "&#9002;"> <!ENTITY loz "&#9674;"> <!ENTITY spades "&#9824;"> <!ENTITY clubs "&#9827;"> <!ENTITY hearts "&#9829;"> <!ENTITY diams "&#9830;">
<!ENTITY fnof "&#402;"> <!ENTITY Alpha "&#913;"> <!ENTITY Beta "&#914;"> <!ENTITY Gamma "&#915;"> <!ENTITY Delta "&#916;"> <!ENTITY Epsilon "&#917;"> <!ENTITY Zeta "&#918;"> <!ENTITY Eta "&#919;"> <!ENTITY Theta "&#920;"> <!ENTITY Iota "&#921;"> <!ENTITY Kappa "&#922;"> <!ENTITY Lambda "&#923;"> <!ENTITY Mu "&#924;"> <!ENTITY Nu "&#925;"> <!ENTITY Xi "&#926;"> <!ENTITY Omicron "&#927;"> <!ENTITY Pi "&#928;"> <!ENTITY Rho "&#929;"> <!ENTITY Sigma "&#931;"> <!ENTITY Tau "&#932;"> <!ENTITY Upsilon "&#933;"> <!ENTITY Phi "&#934;"> <!ENTITY Chi "&#935;"> <!ENTITY Psi "&#936;"> <!ENTITY Omega "&#937;"> <!ENTITY alpha "&#945;"> <!ENTITY beta "&#946;"> <!ENTITY gamma "&#947;"> <!ENTITY delta "&#948;"> <!ENTITY epsilon "&#949;"> <!ENTITY zeta "&#950;"> <!ENTITY eta "&#951;"> <!ENTITY theta "&#952;"> <!ENTITY iota "&#953;"> <!ENTITY kappa "&#954;"> <!ENTITY lambda "&#955;"> <!ENTITY mu "&#956;"> <!ENTITY nu "&#957;"> <!ENTITY xi "&#958;"> <!ENTITY omicron "&#959;"> <!ENTITY pi "&#960;"> <!ENTITY rho "&#961;"> <!ENTITY sigmaf "&#962;"> <!ENTITY sigma "&#963;"> <!ENTITY tau "&#964;"> <!ENTITY upsilon "&#965;"> <!ENTITY phi "&#966;"> <!ENTITY chi "&#967;"> <!ENTITY psi "&#968;"> <!ENTITY omega "&#969;"> <!ENTITY thetasym "&#977;"> <!ENTITY upsih "&#978;"> <!ENTITY piv "&#982;"> <!ENTITY bull "&#8226;"> <!ENTITY hellip "&#8230;"> <!ENTITY prime "&#8242;"> <!ENTITY Prime "&#8243;"> <!ENTITY oline "&#8254;"> <!ENTITY frasl "&#8260;"> <!ENTITY weierp "&#8472;"> <!ENTITY image "&#8465;"> <!ENTITY real "&#8476;"> <!ENTITY trade "&#8482;"> <!ENTITY alefsym "&#8501;"> <!ENTITY larr "&#8592;"> <!ENTITY uarr "&#8593;"> <!ENTITY rarr "&#8594;"> <!ENTITY darr "&#8595;"> <!ENTITY harr "&#8596;"> <!ENTITY crarr "&#8629;"> <!ENTITY lArr "&#8656;"> <!ENTITY uArr "&#8657;"> <!ENTITY rArr "&#8658;"> <!ENTITY dArr "&#8659;"> <!ENTITY hArr "&#8660;"> <!ENTITY forall "&#8704;"> <!ENTITY part "&#8706;"> <!ENTITY exist "&#8707;"> <!ENTITY empty "&#8709;"> <!ENTITY nabla "&#8711;"> <!ENTITY isin "&#8712;"> <!ENTITY notin "&#8713;"> <!ENTITY ni "&#8715;"> <!ENTITY prod "&#8719;"> <!ENTITY sum "&#8721;"> <!ENTITY minus "&#8722;"> <!ENTITY lowast "&#8727;"> <!ENTITY radic "&#8730;"> <!ENTITY prop "&#8733;"> <!ENTITY infin "&#8734;"> <!ENTITY ang "&#8736;"> <!ENTITY and "&#8743;"> <!ENTITY or "&#8744;"> <!ENTITY cap "&#8745;"> <!ENTITY cup "&#8746;"> <!ENTITY int "&#8747;"> <!ENTITY there4 "&#8756;"> <!ENTITY sim "&#8764;"> <!ENTITY cong "&#8773;"> <!ENTITY asymp "&#8776;"> <!ENTITY ne "&#8800;"> <!ENTITY equiv "&#8801;"> <!ENTITY le "&#8804;"> <!ENTITY ge "&#8805;"> <!ENTITY sub "&#8834;"> <!ENTITY sup "&#8835;"> <!ENTITY nsub "&#8836;"> <!ENTITY sube "&#8838;"> <!ENTITY supe "&#8839;"> <!ENTITY oplus "&#8853;"> <!ENTITY otimes "&#8855;"> <!ENTITY perp "&#8869;"> <!ENTITY sdot "&#8901;"> <!ENTITY lceil "&#8968;"> <!ENTITY rceil "&#8969;"> <!ENTITY lfloor "&#8970;"> <!ENTITY rfloor "&#8971;"> <!ENTITY lang "&#9001;"> <!ENTITY rang "&#9002;"> <!ENTITY loz "&#9674;"> <!ENTITY spades "&#9824;"> <!ENTITY clubs "&#9827;"> <!ENTITY hearts "&#9829;"> <!ENTITY diams "&#9830;">
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b16335/b16335.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; class BB { public static bool[] m_static1 = new bool[7]; public BB[] Method1() { return new BB[7]; } public bool[] m_field2; } class DD { public static BB m_static2 = new BB(); public static int Main() { try { new BB().Method1()[2].m_field2 = BB.m_static1; //Normally, must throw NullReferenceException } catch (NullReferenceException) { return 100; } return 1; } } }
// 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; class BB { public static bool[] m_static1 = new bool[7]; public BB[] Method1() { return new BB[7]; } public bool[] m_field2; } class DD { public static BB m_static2 = new BB(); public static int Main() { try { new BB().Method1()[2].m_field2 = BB.m_static1; //Normally, must throw NullReferenceException } catch (NullReferenceException) { return 100; } return 1; } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.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.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.CompilerServices; namespace System.Reflection { internal sealed partial class RuntimeMethodInfo : MethodInfo { [MethodImpl(MethodImplOptions.NoInlining)] // move lazy invocation flags population out of the hot path private static InvocationFlags ComputeAndUpdateInvocationFlags(MethodInfo methodInfo, ref InvocationFlags flagsToUpdate) { InvocationFlags invocationFlags = InvocationFlags.Unknown; Type? declaringType = methodInfo.DeclaringType; if (methodInfo.ContainsGenericParameters // Method has unbound generics || IsDisallowedByRefType(methodInfo.ReturnType) // Return type is an invalid by-ref (i.e., by-ref-like or void*) || (methodInfo.CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs // Managed varargs ) { invocationFlags = InvocationFlags.NoInvoke; } else { if (declaringType != null) { if (declaringType.ContainsGenericParameters) // Enclosing type has unbound generics { invocationFlags = InvocationFlags.NoInvoke; } else if (declaringType.IsByRefLike) // Check for byref-like types { invocationFlags |= InvocationFlags.ContainsStackPointers; } } if (methodInfo.ReturnType.IsByRefLike) // Check for byref-like types for return { invocationFlags |= InvocationFlags.ContainsStackPointers; } } invocationFlags |= InvocationFlags.Initialized; flagsToUpdate = invocationFlags; // accesses are guaranteed atomic return invocationFlags; static bool IsDisallowedByRefType(Type type) { if (!type.IsByRef) return false; Type elementType = type.GetElementType()!; return elementType.IsByRefLike || elementType == typeof(void); } } [DoesNotReturn] private void ThrowNoInvokeException() { // method is on a class that contains stack pointers if ((InvocationFlags & InvocationFlags.ContainsStackPointers) != 0) { throw new NotSupportedException(); } // method is vararg else if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) { throw new NotSupportedException(); } // method is generic or on a generic class else if (DeclaringType!.ContainsGenericParameters || ContainsGenericParameters) { throw new InvalidOperationException(SR.Arg_UnboundGenParam); } // method is abstract class else if (IsAbstract) { throw new MemberAccessException(); } else if (ReturnType.IsByRef) { Type elementType = ReturnType.GetElementType()!; if (elementType.IsByRefLike) throw new NotSupportedException(SR.NotSupported_ByRefToByRefLikeReturn); if (elementType == typeof(void)) throw new NotSupportedException(SR.NotSupported_ByRefToVoidReturn); } throw new TargetException(); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override object? Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { // ContainsStackPointers means that the struct (either the declaring type or the return type) // contains pointers that point to the stack. This is either a ByRef or a TypedReference. These structs cannot // be boxed and thus cannot be invoked through reflection which only deals with boxed value type objects. if ((InvocationFlags & (InvocationFlags.NoInvoke | InvocationFlags.ContainsStackPointers)) != 0) { ThrowNoInvokeException(); } ValidateInvokeTarget(obj); // Correct number of arguments supplied int actualCount = (parameters is null) ? 0 : parameters.Length; if (ArgumentTypes.Length != actualCount) { throw new TargetParameterCountException(SR.Arg_ParmCnt); } StackAllocedArguments stackArgs = default; // try to avoid intermediate array allocation if possible Span<object?> arguments = default; if (actualCount != 0) { arguments = CheckArguments(ref stackArgs, parameters!, binder, invokeAttr, culture, ArgumentTypes); } object? retValue = InvokeWorker(obj, invokeAttr, arguments); // copy out. This should be made only if ByRef are present. // n.b. cannot use Span<T>.CopyTo, as parameters.GetType() might not actually be typeof(object[]) for (int index = 0; index < arguments.Length; index++) { parameters![index] = arguments[index]; } return retValue; } } }
// 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.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.CompilerServices; namespace System.Reflection { internal sealed partial class RuntimeMethodInfo : MethodInfo { [MethodImpl(MethodImplOptions.NoInlining)] // move lazy invocation flags population out of the hot path private static InvocationFlags ComputeAndUpdateInvocationFlags(MethodInfo methodInfo, ref InvocationFlags flagsToUpdate) { InvocationFlags invocationFlags = InvocationFlags.Unknown; Type? declaringType = methodInfo.DeclaringType; if (methodInfo.ContainsGenericParameters // Method has unbound generics || IsDisallowedByRefType(methodInfo.ReturnType) // Return type is an invalid by-ref (i.e., by-ref-like or void*) || (methodInfo.CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs // Managed varargs ) { invocationFlags = InvocationFlags.NoInvoke; } else { if (declaringType != null) { if (declaringType.ContainsGenericParameters) // Enclosing type has unbound generics { invocationFlags = InvocationFlags.NoInvoke; } else if (declaringType.IsByRefLike) // Check for byref-like types { invocationFlags |= InvocationFlags.ContainsStackPointers; } } if (methodInfo.ReturnType.IsByRefLike) // Check for byref-like types for return { invocationFlags |= InvocationFlags.ContainsStackPointers; } } invocationFlags |= InvocationFlags.Initialized; flagsToUpdate = invocationFlags; // accesses are guaranteed atomic return invocationFlags; static bool IsDisallowedByRefType(Type type) { if (!type.IsByRef) return false; Type elementType = type.GetElementType()!; return elementType.IsByRefLike || elementType == typeof(void); } } [DoesNotReturn] private void ThrowNoInvokeException() { // method is on a class that contains stack pointers if ((InvocationFlags & InvocationFlags.ContainsStackPointers) != 0) { throw new NotSupportedException(); } // method is vararg else if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) { throw new NotSupportedException(); } // method is generic or on a generic class else if (DeclaringType!.ContainsGenericParameters || ContainsGenericParameters) { throw new InvalidOperationException(SR.Arg_UnboundGenParam); } // method is abstract class else if (IsAbstract) { throw new MemberAccessException(); } else if (ReturnType.IsByRef) { Type elementType = ReturnType.GetElementType()!; if (elementType.IsByRefLike) throw new NotSupportedException(SR.NotSupported_ByRefToByRefLikeReturn); if (elementType == typeof(void)) throw new NotSupportedException(SR.NotSupported_ByRefToVoidReturn); } throw new TargetException(); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override object? Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { // ContainsStackPointers means that the struct (either the declaring type or the return type) // contains pointers that point to the stack. This is either a ByRef or a TypedReference. These structs cannot // be boxed and thus cannot be invoked through reflection which only deals with boxed value type objects. if ((InvocationFlags & (InvocationFlags.NoInvoke | InvocationFlags.ContainsStackPointers)) != 0) { ThrowNoInvokeException(); } ValidateInvokeTarget(obj); // Correct number of arguments supplied int actualCount = (parameters is null) ? 0 : parameters.Length; if (ArgumentTypes.Length != actualCount) { throw new TargetParameterCountException(SR.Arg_ParmCnt); } StackAllocedArguments stackArgs = default; // try to avoid intermediate array allocation if possible Span<object?> arguments = default; if (actualCount != 0) { arguments = CheckArguments(ref stackArgs, parameters!, binder, invokeAttr, culture, ArgumentTypes); } object? retValue = InvokeWorker(obj, invokeAttr, arguments); // copy out. This should be made only if ByRef are present. // n.b. cannot use Span<T>.CopyTo, as parameters.GetType() might not actually be typeof(object[]) for (int index = 0; index < arguments.Length; index++) { parameters![index] = arguments[index]; } return retValue; } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Memory/tests/ReadOnlyMemory/Slice.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 System.Buffers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.MemoryTests { public static partial class ReadOnlyMemoryTests { [Fact] public static void SliceWithStart() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 }; ReadOnlyMemory<int> memory = new ReadOnlyMemory<int>(a).Slice(6); Assert.Equal(4, memory.Length); Assert.True(Unsafe.AreSame(ref a[6], ref Unsafe.AsRef(in MemoryMarshal.GetReference(memory.Span)))); MemoryManager<int> manager = new CustomMemoryForTest<int>(a); ReadOnlyMemory<int> memoryFromManager = ((ReadOnlyMemory<int>)manager.Memory).Slice(6); Assert.Equal(4, memoryFromManager.Length); Assert.True(Unsafe.AreSame(ref a[6], ref Unsafe.AsRef(in MemoryMarshal.GetReference(memoryFromManager.Span)))); } [Fact] public static void SliceWithStartPastEnd() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 }; ReadOnlyMemory<int> memory = new ReadOnlyMemory<int>(a).Slice(a.Length); Assert.Equal(0, memory.Length); Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract(ref Unsafe.AsRef(in MemoryMarshal.GetReference(memory.Span)), 1))); MemoryManager<int> manager = new CustomMemoryForTest<int>(a); ReadOnlyMemory<int> memoryFromManager = ((ReadOnlyMemory<int>)manager.Memory).Slice(a.Length); Assert.Equal(0, memoryFromManager.Length); Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract(ref Unsafe.AsRef(in MemoryMarshal.GetReference(memoryFromManager.Span)), 1))); } [Fact] public static void SliceWithStartAndLength() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 }; ReadOnlyMemory<int> memory = new ReadOnlyMemory<int>(a).Slice(3, 5); Assert.Equal(5, memory.Length); Assert.True(Unsafe.AreSame(ref a[3], ref Unsafe.AsRef(in MemoryMarshal.GetReference(memory.Span)))); MemoryManager<int> manager = new CustomMemoryForTest<int>(a); ReadOnlyMemory<int> memoryFromManager = ((ReadOnlyMemory<int>)manager.Memory).Slice(3, 5); Assert.Equal(5, memoryFromManager.Length); Assert.True(Unsafe.AreSame(ref a[3], ref Unsafe.AsRef(in MemoryMarshal.GetReference(memoryFromManager.Span)))); } [Fact] public static void SliceWithStartAndLengthUpToEnd() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 }; ReadOnlyMemory<int> memory = new ReadOnlyMemory<int>(a).Slice(4, 6); Assert.Equal(6, memory.Length); Assert.True(Unsafe.AreSame(ref a[4], ref Unsafe.AsRef(in MemoryMarshal.GetReference(memory.Span)))); MemoryManager<int> manager = new CustomMemoryForTest<int>(a); ReadOnlyMemory<int> memoryFromManager = ((ReadOnlyMemory<int>)manager.Memory).Slice(4, 6); Assert.Equal(6, memoryFromManager.Length); Assert.True(Unsafe.AreSame(ref a[4], ref Unsafe.AsRef(in MemoryMarshal.GetReference(memoryFromManager.Span)))); } [Fact] public static void SliceWithStartAndLengthPastEnd() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 }; ReadOnlyMemory<int> memory = new ReadOnlyMemory<int>(a).Slice(a.Length, 0); Assert.Equal(0, memory.Length); Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract(ref Unsafe.AsRef(in MemoryMarshal.GetReference(memory.Span)), 1))); MemoryManager<int> manager = new CustomMemoryForTest<int>(a); ReadOnlyMemory<int> memoryFromManager = ((ReadOnlyMemory<int>)manager.Memory).Slice(a.Length, 0); Assert.Equal(0, memoryFromManager.Length); Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract(ref Unsafe.AsRef(in MemoryMarshal.GetReference(memoryFromManager.Span)), 1))); } [Fact] public static void SliceRangeChecks() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 }; Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(a.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(-1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(0, a.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(2, a.Length + 1 - 2)); Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(a.Length + 1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(a.Length, 1)); MemoryManager<int> manager = new CustomMemoryForTest<int>(a); ReadOnlyMemory<int> memory = manager.Memory; Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(a.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(-1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(0, a.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(2, a.Length + 1 - 2)); Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(a.Length + 1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(a.Length, 1)); } [Fact] public static void SliceWithStartDefaultMemory() { ReadOnlyMemory<int> memory = default; memory = memory.Slice(0); Assert.True(memory.Equals(default)); } [Fact] public static void SliceWithStartAndLengthDefaultMemory() { ReadOnlyMemory<int> memory = default; memory = memory.Slice(0, 0); Assert.True(memory.Equals(default)); } } }
// 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 System.Buffers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.MemoryTests { public static partial class ReadOnlyMemoryTests { [Fact] public static void SliceWithStart() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 }; ReadOnlyMemory<int> memory = new ReadOnlyMemory<int>(a).Slice(6); Assert.Equal(4, memory.Length); Assert.True(Unsafe.AreSame(ref a[6], ref Unsafe.AsRef(in MemoryMarshal.GetReference(memory.Span)))); MemoryManager<int> manager = new CustomMemoryForTest<int>(a); ReadOnlyMemory<int> memoryFromManager = ((ReadOnlyMemory<int>)manager.Memory).Slice(6); Assert.Equal(4, memoryFromManager.Length); Assert.True(Unsafe.AreSame(ref a[6], ref Unsafe.AsRef(in MemoryMarshal.GetReference(memoryFromManager.Span)))); } [Fact] public static void SliceWithStartPastEnd() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 }; ReadOnlyMemory<int> memory = new ReadOnlyMemory<int>(a).Slice(a.Length); Assert.Equal(0, memory.Length); Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract(ref Unsafe.AsRef(in MemoryMarshal.GetReference(memory.Span)), 1))); MemoryManager<int> manager = new CustomMemoryForTest<int>(a); ReadOnlyMemory<int> memoryFromManager = ((ReadOnlyMemory<int>)manager.Memory).Slice(a.Length); Assert.Equal(0, memoryFromManager.Length); Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract(ref Unsafe.AsRef(in MemoryMarshal.GetReference(memoryFromManager.Span)), 1))); } [Fact] public static void SliceWithStartAndLength() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 }; ReadOnlyMemory<int> memory = new ReadOnlyMemory<int>(a).Slice(3, 5); Assert.Equal(5, memory.Length); Assert.True(Unsafe.AreSame(ref a[3], ref Unsafe.AsRef(in MemoryMarshal.GetReference(memory.Span)))); MemoryManager<int> manager = new CustomMemoryForTest<int>(a); ReadOnlyMemory<int> memoryFromManager = ((ReadOnlyMemory<int>)manager.Memory).Slice(3, 5); Assert.Equal(5, memoryFromManager.Length); Assert.True(Unsafe.AreSame(ref a[3], ref Unsafe.AsRef(in MemoryMarshal.GetReference(memoryFromManager.Span)))); } [Fact] public static void SliceWithStartAndLengthUpToEnd() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 }; ReadOnlyMemory<int> memory = new ReadOnlyMemory<int>(a).Slice(4, 6); Assert.Equal(6, memory.Length); Assert.True(Unsafe.AreSame(ref a[4], ref Unsafe.AsRef(in MemoryMarshal.GetReference(memory.Span)))); MemoryManager<int> manager = new CustomMemoryForTest<int>(a); ReadOnlyMemory<int> memoryFromManager = ((ReadOnlyMemory<int>)manager.Memory).Slice(4, 6); Assert.Equal(6, memoryFromManager.Length); Assert.True(Unsafe.AreSame(ref a[4], ref Unsafe.AsRef(in MemoryMarshal.GetReference(memoryFromManager.Span)))); } [Fact] public static void SliceWithStartAndLengthPastEnd() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 }; ReadOnlyMemory<int> memory = new ReadOnlyMemory<int>(a).Slice(a.Length, 0); Assert.Equal(0, memory.Length); Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract(ref Unsafe.AsRef(in MemoryMarshal.GetReference(memory.Span)), 1))); MemoryManager<int> manager = new CustomMemoryForTest<int>(a); ReadOnlyMemory<int> memoryFromManager = ((ReadOnlyMemory<int>)manager.Memory).Slice(a.Length, 0); Assert.Equal(0, memoryFromManager.Length); Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract(ref Unsafe.AsRef(in MemoryMarshal.GetReference(memoryFromManager.Span)), 1))); } [Fact] public static void SliceRangeChecks() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 }; Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(a.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(-1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(0, a.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(2, a.Length + 1 - 2)); Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(a.Length + 1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(a.Length, 1)); MemoryManager<int> manager = new CustomMemoryForTest<int>(a); ReadOnlyMemory<int> memory = manager.Memory; Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(a.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(-1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(0, a.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(2, a.Length + 1 - 2)); Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(a.Length + 1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(a.Length, 1)); } [Fact] public static void SliceWithStartDefaultMemory() { ReadOnlyMemory<int> memory = default; memory = memory.Slice(0); Assert.True(memory.Equals(default)); } [Fact] public static void SliceWithStartAndLengthDefaultMemory() { ReadOnlyMemory<int> memory = default; memory = memory.Slice(0, 0); Assert.True(memory.Equals(default)); } } }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltScenarios/EXslt/string-align.xsl
<?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:str="http://exslt.org/strings" exclude-result-prefixes="str"> <xsl:output indent="yes" omit-xml-declaration="yes"/> <xsl:template match="data"> <out> <test1> <xsl:value-of select="str:align(name, str:padding(20, '_'), 'left')"/> </test1> <test2> <xsl:value-of select="str:align(name, str:padding(20, '_'), 'center')"/> </test2> <test3> <xsl:value-of select="str:align(name, str:padding(20, '_'), 'right')"/> </test3> <test4> <xsl:value-of select="str:align(name, str:padding(20, '_'))"/> </test4> <test5> <xsl:value-of select="str:align(name, str:padding(20, '_'), 'none')"/> </test5> <test6> <xsl:value-of select="str:align(name, str:padding(2, '*'), 'center')"/> </test6> <test7> <xsl:value-of select="str:align('', '*******', 'center')"/> </test7> <test8> <xsl:value-of select="str:align('foo', '')"/> </test8> <test9> <xsl:value-of select="str:align('foo', '******', '')"/> </test9> </out> </xsl:template> </xsl:stylesheet>
<?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:str="http://exslt.org/strings" exclude-result-prefixes="str"> <xsl:output indent="yes" omit-xml-declaration="yes"/> <xsl:template match="data"> <out> <test1> <xsl:value-of select="str:align(name, str:padding(20, '_'), 'left')"/> </test1> <test2> <xsl:value-of select="str:align(name, str:padding(20, '_'), 'center')"/> </test2> <test3> <xsl:value-of select="str:align(name, str:padding(20, '_'), 'right')"/> </test3> <test4> <xsl:value-of select="str:align(name, str:padding(20, '_'))"/> </test4> <test5> <xsl:value-of select="str:align(name, str:padding(20, '_'), 'none')"/> </test5> <test6> <xsl:value-of select="str:align(name, str:padding(2, '*'), 'center')"/> </test6> <test7> <xsl:value-of select="str:align('', '*******', 'center')"/> </test7> <test8> <xsl:value-of select="str:align('foo', '')"/> </test8> <test9> <xsl:value-of select="str:align('foo', '******', '')"/> </test9> </out> </xsl:template> </xsl:stylesheet>
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Private.CoreLib/src/System/Function.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System { public delegate TResult Func<out TResult>(); public delegate TResult Func<in T, out TResult>(T arg); public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2); public delegate TResult Func<in T1, in T2, in T3, out TResult>(T1 arg1, T2 arg2, T3 arg3); public delegate TResult Func<in T1, in T2, in T3, in T4, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System { public delegate TResult Func<out TResult>(); public delegate TResult Func<in T, out TResult>(T arg); public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2); public delegate TResult Func<in T1, in T2, in T3, out TResult>(T1 arg1, T2 arg2, T3 arg3); public delegate TResult Func<in T1, in T2, in T3, in T4, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16); }
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/coreclr/debug/ee/funceval.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // **************************************************************************** // File: funceval.cpp // // // funceval.cpp - Debugger func-eval routines. // // **************************************************************************** // Putting code & #includes, #defines, etc, before the stdafx.h will // cause the code,etc, to be silently ignored #include "stdafx.h" #include "debugdebugger.h" #include "../inc/common.h" #include "eeconfig.h" // This is here even for retail & free builds... #include "../../dlls/mscorrc/resource.h" #include "vars.hpp" #include "threads.h" #include "appdomain.inl" #include <limits.h> #include "ilformatter.h" #ifndef DACCESS_COMPILE // // This is the main file for processing func-evals. Nestle in // with a cup o' tea and read on. // // The most common case is handled in GCProtectArgsAndDoNormalFuncEval(), which follows // all the comments below. The two other corner cases are handled in // FuncEvalHijackWorker(), and are extremely straight-forward. // // There are several steps to successfully processing a func-eval. At a // very high level, the first step is to gather all the information necessary // to make the call (specifically, gather arg info and method info); the second // step is to actually make the call to managed code; finally, the third step // is to take all results and unpackage them. // // The first step (gathering arg and method info) has several critical passes that // must be made. // a) Protect all passed in args from a GC. // b) Transition into the appropriate AppDomain if necessary // c) Pre-allocate object for 'new' calls and, if necessary, box the 'this' argument. (May cause a GC) // d) Gather method info (May cause GC) // e) Gather info from runtime about args. (May cause a GC) // f) Box args that need to be, GC-protecting the newly boxed items. (May cause a GC) // g) Pre-allocate object for return values. (May cause a GC) // h) Copy to pBufferForArgsArray all the args. This array is used to hold values that // may need writable memory for ByRef args. // i) Create and load pArgumentArray to be passed as the stack for the managed call. // NOTE: From the time we load the first argument into the stack we cannot cause a GC // as the argument array cannot be GC-protected. // // The second step (Making the managed call), is relatively easy, and is a single call. // // The third step (unpacking all results), has a couple of passes as well. // a) Copy back all resulting values. // b) Free all temporary work memory. // // // The most difficult part of doing a func-eval is the first step, since once you // have everything set up, unpacking and calling are reverse, gc-safe, operations. Thus, // elaboration is needed on the first step. // // a) Protect all passed in args from a GC. This must be done in a gc-forbid region, // and the code path to this function must not trigger a gc either. In this function five // parallel arrays are used: pObjectRefArray, pMaybeInteriorPtrArray, pByRefMaybeInteriorPtrArray, // pBufferForArgsArray, and pArguments. // pObjectRefArray is used to gc-protect all arguments and results that are objects. // pMaybeInteriorPtrArray is used to gc-protect all arguments that might be pointers // to an interior of a managed object. // pByRefMaybeInteriorPtrArray is similar to pMaybeInteriorPtrArray, except that it protects the // address of the arguments instead of the arguments themselves. This is needed because we may have // by ref arguments whose address is an interior pointer into the GC heap. // pBufferForArgsArray is used strictly as a buffer for copying primitives // that need to be passed as ByRef, or may be enregistered. This array also holds // handles. // These first two arrays are mutually exclusive, that is, if there is an entry // in one array at index i, there should be no entry in either of the other arrays at // the same index. // pArguments is used as the complete array of arguments to pass to the managed function. // // Unfortunately the necessary information to complete pass (a) perfectly may cause a gc, so // instead, pass (a) is over-aggressive and protects the following: All object refs into // pObjectRefArray, and puts all values that could be raw pointers into pMaybeInteriorPtrArray. // // b) Discovers the method to be called, and if it is a 'new' allocate an object for the result. // // c) Gather information about the method that will be called. // // d) Here we gather information from the method signature which tells which args are // ByRef and various other flags. We will use this information in later passes. // // e) Using the information in pass (c), for each argument: box arguments, placing newly // boxed items into pObjectRefArray immediately after creating them. // // f) Pre-allocate any object for a returned value. // // g) Using the information is pass (c), all arguments are copied into a scratch buffer before // invoking the managed function. // // h) pArguments is loaded from the pre-allocated return object, the individual elements // of the other 3 arrays, and from any non-ByRef literals. This is the complete stack // to be passed to the managed function. For performance increase, it can remove any // overly aggressive items that were placed in pMaybeInteriorPtrArray. // // // IsElementTypeSpecial() // // This is a simple function used to check if a CorElementType needs special handling for func eval. // // parameters: type - the CorElementType which we need to check // // return value: true if the specified type needs special handling // inline static bool IsElementTypeSpecial(CorElementType type) { LIMITED_METHOD_CONTRACT; return ((type == ELEMENT_TYPE_CLASS) || (type == ELEMENT_TYPE_OBJECT) || (type == ELEMENT_TYPE_ARRAY) || (type == ELEMENT_TYPE_SZARRAY) || (type == ELEMENT_TYPE_STRING)); } // // GetAndSetLiteralValue() // // This helper function extracts the value out of the source pointer while taking into account alignment and size. // Then it stores the value into the destination pointer, again taking into account alignment and size. // // parameters: pDst - destination pointer // dstType - the CorElementType of the destination value // pSrc - source pointer // srcType - the CorElementType of the source value // // return value: none // inline static void GetAndSetLiteralValue(LPVOID pDst, CorElementType dstType, LPVOID pSrc, CorElementType srcType) { LIMITED_METHOD_CONTRACT; UINT64 srcValue; // Retrieve the value using the source CorElementType. switch (g_pEEInterface->GetSizeForCorElementType(srcType)) { case 1: srcValue = (UINT64)*((BYTE*)pSrc); break; case 2: srcValue = (UINT64)*((USHORT*)pSrc); break; case 4: srcValue = (UINT64)*((UINT32*)pSrc); break; case 8: srcValue = (UINT64)*((UINT64*)pSrc); break; default: UNREACHABLE(); } // Cast to the appropriate type using the destination CorElementType. switch (dstType) { case ELEMENT_TYPE_BOOLEAN: *(BYTE*)pDst = (BYTE)!!srcValue; break; case ELEMENT_TYPE_I1: *(INT8*)pDst = (INT8)srcValue; break; case ELEMENT_TYPE_U1: *(UINT8*)pDst = (UINT8)srcValue; break; case ELEMENT_TYPE_I2: *(INT16*)pDst = (INT16)srcValue; break; case ELEMENT_TYPE_U2: case ELEMENT_TYPE_CHAR: *(UINT16*)pDst = (UINT16)srcValue; break; #if !defined(HOST_64BIT) case ELEMENT_TYPE_I: #endif case ELEMENT_TYPE_I4: *(int*)pDst = (int)srcValue; break; #if !defined(HOST_64BIT) case ELEMENT_TYPE_U: #endif case ELEMENT_TYPE_U4: case ELEMENT_TYPE_R4: *(unsigned*)pDst = (unsigned)srcValue; break; #if defined(HOST_64BIT) case ELEMENT_TYPE_I: #endif case ELEMENT_TYPE_I8: case ELEMENT_TYPE_R8: *(INT64*)pDst = (INT64)srcValue; break; #if defined(HOST_64BIT) case ELEMENT_TYPE_U: #endif case ELEMENT_TYPE_U8: *(UINT64*)pDst = (UINT64)srcValue; break; case ELEMENT_TYPE_FNPTR: case ELEMENT_TYPE_PTR: *(void **)pDst = (void *)(SIZE_T)srcValue; break; default: UNREACHABLE(); } } // // Throw on not supported func evals // static void ValidateFuncEvalReturnType(DebuggerIPCE_FuncEvalType evalType, MethodTable * pMT) { CONTRACTL { THROWS; GC_TRIGGERS; } CONTRACTL_END; if (pMT == g_pStringClass) { if (evalType == DB_IPCE_FET_NEW_OBJECT || evalType == DB_IPCE_FET_NEW_OBJECT_NC) { // Cannot call New object on String constructor. COMPlusThrow(kArgumentException,W("Argument_CannotCreateString")); } } else if (g_pEEInterface->IsTypedReference(pMT)) { // Cannot create typed references through funceval. if (evalType == DB_IPCE_FET_NEW_OBJECT || evalType == DB_IPCE_FET_NEW_OBJECT_NC || evalType == DB_IPCE_FET_NORMAL) { COMPlusThrow(kArgumentException, W("Argument_CannotCreateTypedReference")); } } } // // Given a register, return the value. // static SIZE_T GetRegisterValue(DebuggerEval *pDE, CorDebugRegister reg, void *regAddr, SIZE_T regValue) { LIMITED_METHOD_CONTRACT; SIZE_T ret = 0; // Check whether the register address is the marker value for a register in a non-leaf frame. // This is related to the funceval breaking change. // if (regAddr == CORDB_ADDRESS_TO_PTR(kNonLeafFrameRegAddr)) { ret = regValue; } else { switch (reg) { case REGISTER_STACK_POINTER: ret = (SIZE_T)GetSP(&pDE->m_context); break; case REGISTER_FRAME_POINTER: ret = (SIZE_T)GetFP(&pDE->m_context); break; #if defined(TARGET_X86) case REGISTER_X86_EAX: ret = pDE->m_context.Eax; break; case REGISTER_X86_ECX: ret = pDE->m_context.Ecx; break; case REGISTER_X86_EDX: ret = pDE->m_context.Edx; break; case REGISTER_X86_EBX: ret = pDE->m_context.Ebx; break; case REGISTER_X86_ESI: ret = pDE->m_context.Esi; break; case REGISTER_X86_EDI: ret = pDE->m_context.Edi; break; #elif defined(TARGET_AMD64) case REGISTER_AMD64_RAX: ret = pDE->m_context.Rax; break; case REGISTER_AMD64_RCX: ret = pDE->m_context.Rcx; break; case REGISTER_AMD64_RDX: ret = pDE->m_context.Rdx; break; case REGISTER_AMD64_RBX: ret = pDE->m_context.Rbx; break; case REGISTER_AMD64_RSI: ret = pDE->m_context.Rsi; break; case REGISTER_AMD64_RDI: ret = pDE->m_context.Rdi; break; case REGISTER_AMD64_R8: ret = pDE->m_context.R8; break; case REGISTER_AMD64_R9: ret = pDE->m_context.R9; break; case REGISTER_AMD64_R10: ret = pDE->m_context.R10; break; case REGISTER_AMD64_R11: ret = pDE->m_context.R11; break; case REGISTER_AMD64_R12: ret = pDE->m_context.R12; break; case REGISTER_AMD64_R13: ret = pDE->m_context.R13; break; case REGISTER_AMD64_R14: ret = pDE->m_context.R14; break; case REGISTER_AMD64_R15: ret = pDE->m_context.R15; break; // fall through case REGISTER_AMD64_XMM0: case REGISTER_AMD64_XMM1: case REGISTER_AMD64_XMM2: case REGISTER_AMD64_XMM3: case REGISTER_AMD64_XMM4: case REGISTER_AMD64_XMM5: case REGISTER_AMD64_XMM6: case REGISTER_AMD64_XMM7: case REGISTER_AMD64_XMM8: case REGISTER_AMD64_XMM9: case REGISTER_AMD64_XMM10: case REGISTER_AMD64_XMM11: case REGISTER_AMD64_XMM12: case REGISTER_AMD64_XMM13: case REGISTER_AMD64_XMM14: case REGISTER_AMD64_XMM15: ret = FPSpillToR8(&(pDE->m_context.Xmm0) + (reg - REGISTER_AMD64_XMM0)); break; #elif defined(TARGET_ARM64) // fall through case REGISTER_ARM64_X0: case REGISTER_ARM64_X1: case REGISTER_ARM64_X2: case REGISTER_ARM64_X3: case REGISTER_ARM64_X4: case REGISTER_ARM64_X5: case REGISTER_ARM64_X6: case REGISTER_ARM64_X7: case REGISTER_ARM64_X8: case REGISTER_ARM64_X9: case REGISTER_ARM64_X10: case REGISTER_ARM64_X11: case REGISTER_ARM64_X12: case REGISTER_ARM64_X13: case REGISTER_ARM64_X14: case REGISTER_ARM64_X15: case REGISTER_ARM64_X16: case REGISTER_ARM64_X17: case REGISTER_ARM64_X18: case REGISTER_ARM64_X19: case REGISTER_ARM64_X20: case REGISTER_ARM64_X21: case REGISTER_ARM64_X22: case REGISTER_ARM64_X23: case REGISTER_ARM64_X24: case REGISTER_ARM64_X25: case REGISTER_ARM64_X26: case REGISTER_ARM64_X27: case REGISTER_ARM64_X28: ret = pDE->m_context.X[reg - REGISTER_ARM64_X0]; break; case REGISTER_ARM64_LR: ret = pDE->m_context.Lr; break; case REGISTER_ARM64_V0: case REGISTER_ARM64_V1: case REGISTER_ARM64_V2: case REGISTER_ARM64_V3: case REGISTER_ARM64_V4: case REGISTER_ARM64_V5: case REGISTER_ARM64_V6: case REGISTER_ARM64_V7: case REGISTER_ARM64_V8: case REGISTER_ARM64_V9: case REGISTER_ARM64_V10: case REGISTER_ARM64_V11: case REGISTER_ARM64_V12: case REGISTER_ARM64_V13: case REGISTER_ARM64_V14: case REGISTER_ARM64_V15: case REGISTER_ARM64_V16: case REGISTER_ARM64_V17: case REGISTER_ARM64_V18: case REGISTER_ARM64_V19: case REGISTER_ARM64_V20: case REGISTER_ARM64_V21: case REGISTER_ARM64_V22: case REGISTER_ARM64_V23: case REGISTER_ARM64_V24: case REGISTER_ARM64_V25: case REGISTER_ARM64_V26: case REGISTER_ARM64_V27: case REGISTER_ARM64_V28: case REGISTER_ARM64_V29: case REGISTER_ARM64_V30: case REGISTER_ARM64_V31: ret = FPSpillToR8(&pDE->m_context.V[reg - REGISTER_ARM64_V0]); break; #endif // !TARGET_X86 && !TARGET_AMD64 && !TARGET_ARM64 default: _ASSERT(!"Invalid register number!"); } } return ret; } // // Given a register, set its value. // static void SetRegisterValue(DebuggerEval *pDE, CorDebugRegister reg, void *regAddr, SIZE_T newValue) { CONTRACTL { THROWS; } CONTRACTL_END; // Check whether the register address is the marker value for a register in a non-leaf frame. // If so, then we can't update the register. Throw an exception to communicate this error. if (regAddr == CORDB_ADDRESS_TO_PTR(kNonLeafFrameRegAddr)) { COMPlusThrowHR(CORDBG_E_FUNC_EVAL_CANNOT_UPDATE_REGISTER_IN_NONLEAF_FRAME); return; } else { switch (reg) { case REGISTER_STACK_POINTER: SetSP(&pDE->m_context, newValue); break; case REGISTER_FRAME_POINTER: SetFP(&pDE->m_context, newValue); break; #ifdef TARGET_X86 case REGISTER_X86_EAX: pDE->m_context.Eax = newValue; break; case REGISTER_X86_ECX: pDE->m_context.Ecx = newValue; break; case REGISTER_X86_EDX: pDE->m_context.Edx = newValue; break; case REGISTER_X86_EBX: pDE->m_context.Ebx = newValue; break; case REGISTER_X86_ESI: pDE->m_context.Esi = newValue; break; case REGISTER_X86_EDI: pDE->m_context.Edi = newValue; break; #elif defined(TARGET_AMD64) case REGISTER_AMD64_RAX: pDE->m_context.Rax = newValue; break; case REGISTER_AMD64_RCX: pDE->m_context.Rcx = newValue; break; case REGISTER_AMD64_RDX: pDE->m_context.Rdx = newValue; break; case REGISTER_AMD64_RBX: pDE->m_context.Rbx = newValue; break; case REGISTER_AMD64_RSI: pDE->m_context.Rsi = newValue; break; case REGISTER_AMD64_RDI: pDE->m_context.Rdi = newValue; break; case REGISTER_AMD64_R8: pDE->m_context.R8= newValue; break; case REGISTER_AMD64_R9: pDE->m_context.R9= newValue; break; case REGISTER_AMD64_R10: pDE->m_context.R10= newValue; break; case REGISTER_AMD64_R11: pDE->m_context.R11 = newValue; break; case REGISTER_AMD64_R12: pDE->m_context.R12 = newValue; break; case REGISTER_AMD64_R13: pDE->m_context.R13 = newValue; break; case REGISTER_AMD64_R14: pDE->m_context.R14 = newValue; break; case REGISTER_AMD64_R15: pDE->m_context.R15 = newValue; break; // fall through case REGISTER_AMD64_XMM0: case REGISTER_AMD64_XMM1: case REGISTER_AMD64_XMM2: case REGISTER_AMD64_XMM3: case REGISTER_AMD64_XMM4: case REGISTER_AMD64_XMM5: case REGISTER_AMD64_XMM6: case REGISTER_AMD64_XMM7: case REGISTER_AMD64_XMM8: case REGISTER_AMD64_XMM9: case REGISTER_AMD64_XMM10: case REGISTER_AMD64_XMM11: case REGISTER_AMD64_XMM12: case REGISTER_AMD64_XMM13: case REGISTER_AMD64_XMM14: case REGISTER_AMD64_XMM15: R8ToFPSpill(&(pDE->m_context.Xmm0) + (reg - REGISTER_AMD64_XMM0), newValue); break; #elif defined(TARGET_ARM64) // fall through case REGISTER_ARM64_X0: case REGISTER_ARM64_X1: case REGISTER_ARM64_X2: case REGISTER_ARM64_X3: case REGISTER_ARM64_X4: case REGISTER_ARM64_X5: case REGISTER_ARM64_X6: case REGISTER_ARM64_X7: case REGISTER_ARM64_X8: case REGISTER_ARM64_X9: case REGISTER_ARM64_X10: case REGISTER_ARM64_X11: case REGISTER_ARM64_X12: case REGISTER_ARM64_X13: case REGISTER_ARM64_X14: case REGISTER_ARM64_X15: case REGISTER_ARM64_X16: case REGISTER_ARM64_X17: case REGISTER_ARM64_X18: case REGISTER_ARM64_X19: case REGISTER_ARM64_X20: case REGISTER_ARM64_X21: case REGISTER_ARM64_X22: case REGISTER_ARM64_X23: case REGISTER_ARM64_X24: case REGISTER_ARM64_X25: case REGISTER_ARM64_X26: case REGISTER_ARM64_X27: case REGISTER_ARM64_X28: pDE->m_context.X[reg - REGISTER_ARM64_X0] = newValue; break; case REGISTER_ARM64_LR: pDE->m_context.Lr = newValue; break; case REGISTER_ARM64_V0: case REGISTER_ARM64_V1: case REGISTER_ARM64_V2: case REGISTER_ARM64_V3: case REGISTER_ARM64_V4: case REGISTER_ARM64_V5: case REGISTER_ARM64_V6: case REGISTER_ARM64_V7: case REGISTER_ARM64_V8: case REGISTER_ARM64_V9: case REGISTER_ARM64_V10: case REGISTER_ARM64_V11: case REGISTER_ARM64_V12: case REGISTER_ARM64_V13: case REGISTER_ARM64_V14: case REGISTER_ARM64_V15: case REGISTER_ARM64_V16: case REGISTER_ARM64_V17: case REGISTER_ARM64_V18: case REGISTER_ARM64_V19: case REGISTER_ARM64_V20: case REGISTER_ARM64_V21: case REGISTER_ARM64_V22: case REGISTER_ARM64_V23: case REGISTER_ARM64_V24: case REGISTER_ARM64_V25: case REGISTER_ARM64_V26: case REGISTER_ARM64_V27: case REGISTER_ARM64_V28: case REGISTER_ARM64_V29: case REGISTER_ARM64_V30: case REGISTER_ARM64_V31: R8ToFPSpill(&pDE->m_context.V[reg - REGISTER_ARM64_V0], newValue); break; #endif // !TARGET_X86 && !TARGET_AMD64 && !TARGET_ARM64 default: _ASSERT(!"Invalid register number!"); } } } /* * GetRegsiterValueAndReturnAddress * * This routine takes out a value from a register, or set of registers, into one of * the given buffers (depending on size), and returns a pointer to the filled in * buffer, or NULL on error. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * pFEAD - Information about this particular argument. * pInt64Buf - pointer to a buffer of type INT64 * pSizeTBuf - pointer to a buffer of native size type. * * Returns: * pointer to the filled in buffer, else NULL on error. * */ static PVOID GetRegisterValueAndReturnAddress(DebuggerEval *pDE, DebuggerIPCE_FuncEvalArgData *pFEAD, INT64 *pInt64Buf, SIZE_T *pSizeTBuf ) { LIMITED_METHOD_CONTRACT; PVOID pAddr; #if !defined(HOST_64BIT) pAddr = pInt64Buf; DWORD *pLow = (DWORD*)(pInt64Buf); DWORD *pHigh = pLow + 1; #endif // HOST_64BIT switch (pFEAD->argHome.kind) { #if !defined(HOST_64BIT) case RAK_REGREG: *pLow = GetRegisterValue(pDE, pFEAD->argHome.u.reg2, pFEAD->argHome.u.reg2Addr, pFEAD->argHome.u.reg2Value); *pHigh = GetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); break; case RAK_MEMREG: *pLow = GetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); *pHigh = *((DWORD*)CORDB_ADDRESS_TO_PTR(pFEAD->argHome.addr)); break; case RAK_REGMEM: *pLow = *((DWORD*)CORDB_ADDRESS_TO_PTR(pFEAD->argHome.addr)); *pHigh = GetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); break; #endif // HOST_64BIT case RAK_REG: // Simply grab the value out of the proper register. *pSizeTBuf = GetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); pAddr = pSizeTBuf; break; default: pAddr = NULL; break; } return pAddr; } //--------------------------------------------------------------------------------------- // // Clean up any temporary value class variables we have allocated for the funceval. // // Arguments: // pStackStructArray - array whose elements track the location and type of the temporary variables // void CleanUpTemporaryVariables(ValueClassInfo ** ppProtectedValueClasses) { while (*ppProtectedValueClasses != NULL) { ValueClassInfo * pValueClassInfo = *ppProtectedValueClasses; *ppProtectedValueClasses = pValueClassInfo->pNext; DeleteInteropSafe(reinterpret_cast<BYTE *>(pValueClassInfo)); } } #ifdef _DEBUG // // Create a parallel array that tracks that we have initialized information in // each array. // #define MAX_DATA_LOCATIONS_TRACKED 100 typedef DWORD DataLocation; #define DL_NonExistent 0x00 #define DL_ObjectRefArray 0x01 #define DL_MaybeInteriorPtrArray 0x02 #define DL_BufferForArgsArray 0x04 #define DL_All 0xFF #endif // _DEBUG /* * GetFuncEvalArgValue * * This routine is used to fill the pArgument array with the appropriate value. This function * uses the three parallel array entries given, and places the correct value, or reference to * the value in pArgument. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * pFEAD - Information about this particular argument. * isByRef - Is the argument being passed ByRef. * fNeedBoxOrUnbox - Did the argument need boxing or unboxing. * argTH - The type handle for the argument. * byrefArgSigType - The signature type of a parameter that isByRef == true. * pArgument - Location to place the reference or value. * pMaybeInteriorPtrArg - A pointer that contains a value that may be pointers to * the interior of a managed object. * pObjectRefArg - A pointer that contains an object ref. It was built previously. * pBufferArg - A pointer for holding stuff that did not need to be protected. * * Returns: * None. * */ static void GetFuncEvalArgValue(DebuggerEval *pDE, DebuggerIPCE_FuncEvalArgData *pFEAD, bool isByRef, bool fNeedBoxOrUnbox, TypeHandle argTH, CorElementType byrefArgSigType, TypeHandle byrefArgTH, ARG_SLOT *pArgument, void *pMaybeInteriorPtrArg, OBJECTREF *pObjectRefArg, INT64 *pBufferArg, ValueClassInfo ** ppProtectedValueClasses, CorElementType argSigType DEBUG_ARG(DataLocation dataLocation) ) { CONTRACTL { THROWS; GC_NOTRIGGER; } CONTRACTL_END; _ASSERTE((dataLocation != DL_NonExistent) || (pFEAD->argElementType == ELEMENT_TYPE_VALUETYPE)); switch (pFEAD->argElementType) { case ELEMENT_TYPE_I8: case ELEMENT_TYPE_U8: case ELEMENT_TYPE_R8: { INT64 *pSource; #if defined(HOST_64BIT) _ASSERTE(dataLocation & DL_MaybeInteriorPtrArray); pSource = (INT64 *)pMaybeInteriorPtrArg; #else // !HOST_64BIT _ASSERTE(dataLocation & DL_BufferForArgsArray); pSource = pBufferArg; #endif // !HOST_64BIT if (!isByRef) { *((INT64*)pArgument) = *pSource; } else { *pArgument = PtrToArgSlot(pSource); } } break; case ELEMENT_TYPE_VALUETYPE: { SIZE_T v = 0; LPVOID pAddr = NULL; INT64 bigVal = 0; if (pFEAD->argAddr != NULL) { pAddr = *((void **)pMaybeInteriorPtrArg); } else { pAddr = GetRegisterValueAndReturnAddress(pDE, pFEAD, &bigVal, &v); if (pAddr == NULL) { COMPlusThrow(kArgumentNullException); } } _ASSERTE(pAddr); if (!fNeedBoxOrUnbox && !isByRef) { _ASSERTE(argTH.GetMethodTable()); unsigned size = argTH.GetMethodTable()->GetNumInstanceFieldBytes(); if (size <= sizeof(ARG_SLOT) #if defined(TARGET_AMD64) // On AMD64 we pass value types of size which are not powers of 2 by ref. && ((size & (size-1)) == 0) #endif // TARGET_AMD64 ) { memcpyNoGCRefs(ArgSlotEndianessFixup(pArgument, sizeof(LPVOID)), pAddr, size); } else { _ASSERTE(pFEAD->argAddr != NULL); #if defined(ENREGISTERED_PARAMTYPE_MAXSIZE) if (ArgIterator::IsArgPassedByRef(argTH)) { // On X64, by-value value class arguments which are bigger than 8 bytes are passed by reference // according to the native calling convention. The same goes for value class arguments whose size // is smaller than 8 bytes but not a power of 2. To avoid side effets, we need to allocate a // temporary variable and pass that by reference instead. On ARM64, by-value value class // arguments which are bigger than 16 bytes are passed by reference. _ASSERTE(ppProtectedValueClasses != NULL); BYTE * pTemp = new (interopsafe) BYTE[ALIGN_UP(sizeof(ValueClassInfo), 8) + size]; ValueClassInfo * pValueClassInfo = (ValueClassInfo *)pTemp; LPVOID pData = pTemp + ALIGN_UP(sizeof(ValueClassInfo), 8); memcpyNoGCRefs(pData, pAddr, size); *pArgument = PtrToArgSlot(pData); pValueClassInfo->pData = pData; pValueClassInfo->pMT = argTH.GetMethodTable(); pValueClassInfo->pNext = *ppProtectedValueClasses; *ppProtectedValueClasses = pValueClassInfo; } else #endif // ENREGISTERED_PARAMTYPE_MAXSIZE *pArgument = PtrToArgSlot(pAddr); } } else { if (fNeedBoxOrUnbox) { *pArgument = ObjToArgSlot(*pObjectRefArg); } else { if (pFEAD->argAddr) { *pArgument = PtrToArgSlot(pAddr); } else { // The argument is the address of where we're holding the primitive in the PrimitiveArg array. We // stick the real value from the register into the PrimitiveArg array. It should be in a single // register since it is pointer-sized. _ASSERTE( pFEAD->argHome.kind == RAK_REG ); *pArgument = PtrToArgSlot(pBufferArg); *pBufferArg = (INT64)v; } } } } break; default: // literal values smaller than 8 bytes and "special types" (e.g. object, string, etc.) { INT64 *pSource; INDEBUG(DataLocation expectedLocation); #ifdef TARGET_X86 if ((pFEAD->argElementType == ELEMENT_TYPE_I4) || (pFEAD->argElementType == ELEMENT_TYPE_U4) || (pFEAD->argElementType == ELEMENT_TYPE_R4)) { INDEBUG(expectedLocation = DL_MaybeInteriorPtrArray); pSource = (INT64 *)pMaybeInteriorPtrArg; } else #endif if (IsElementTypeSpecial(pFEAD->argElementType)) { INDEBUG(expectedLocation = DL_ObjectRefArray); pSource = (INT64 *)pObjectRefArg; } else { INDEBUG(expectedLocation = DL_BufferForArgsArray); pSource = pBufferArg; } if (pFEAD->argAddr != NULL) { if (!isByRef) { if (pFEAD->argIsHandleValue) { _ASSERTE(dataLocation & DL_BufferForArgsArray); OBJECTHANDLE oh = *((OBJECTHANDLE*)(pBufferArg)); // Always comes from buffer *pArgument = PtrToArgSlot(g_pEEInterface->GetObjectFromHandle(oh)); } else { _ASSERTE(dataLocation & expectedLocation); if (pSource != NULL) { *pArgument = *pSource; // may come from either array. } else { *pArgument = NULL; } } } else { if (pFEAD->argIsHandleValue) { _ASSERTE(dataLocation & DL_BufferForArgsArray); *pArgument = *pBufferArg; // Buffer contains the object handle, in this case, so // just copy that across. } else { _ASSERTE(dataLocation & expectedLocation); *pArgument = PtrToArgSlot(pSource); // Load the argument with the address of our buffer. } } } else if (pFEAD->argIsLiteral) { _ASSERTE(dataLocation & expectedLocation); if (!isByRef) { if (pSource != NULL) { *pArgument = *pSource; // may come from either array. } else { *pArgument = NULL; } } else { *pArgument = PtrToArgSlot(pSource); // Load the argument with the address of our buffer. } } else { if (!isByRef) { if (pSource != NULL) { *pArgument = *pSource; // may come from either array. } else { *pArgument = NULL; } } else { *pArgument = PtrToArgSlot(pSource); // Load the argument with the address of our buffer. } } // If we need to unbox, then unbox the arg now. if (fNeedBoxOrUnbox) { if (!isByRef) { // function expects valuetype, argument received is class or object // Take the ObjectRef off the stack. ARG_SLOT oi1 = *pArgument; OBJECTREF o1 = ArgSlotToObj(oi1); // For Nullable types, we need a 'true' nullable to pass to the function, and we do this // by passing a boxed nullable that we unbox. We allocated this space earlier however we // did not know the data location until just now. Fill it in with the data and use that // to pass to the function. if (Nullable::IsNullableType(argTH)) { _ASSERTE(*pObjectRefArg != 0); _ASSERTE((*pObjectRefArg)->GetMethodTable() == argTH.GetMethodTable()); if (o1 != *pObjectRefArg) { Nullable::UnBoxNoCheck((*pObjectRefArg)->GetData(), o1, (*pObjectRefArg)->GetMethodTable()); o1 = *pObjectRefArg; } } if (o1 == NULL) { COMPlusThrow(kArgumentNullException); } if (!o1->GetMethodTable()->IsValueType()) { COMPlusThrow(kArgumentException, W("Argument_BadObjRef")); } // Unbox the little fella to get a pointer to the raw data. void *pData = o1->GetData(); // Get its size to make sure it fits in an ARG_SLOT unsigned size = o1->GetMethodTable()->GetNumInstanceFieldBytes(); if (size <= sizeof(ARG_SLOT)) { // Its not ByRef, so we need to copy the value class onto the ARG_SLOT. CopyValueClass(ArgSlotEndianessFixup(pArgument, sizeof(LPVOID)), pData, o1->GetMethodTable()); } else { // Store pointer to the space in the ARG_SLOT *pArgument = PtrToArgSlot(pData); } } else { // Function expects byref valuetype, argument received is byref class. // Grab the ObjectRef off the stack via the pointer on the stack. Note: the stack has a pointer to the // ObjectRef since the arg was specified as byref. OBJECTREF* op1 = (OBJECTREF*)ArgSlotToPtr(*pArgument); if (op1 == NULL) { COMPlusThrow(kArgumentNullException); } OBJECTREF o1 = *op1; // For Nullable types, we need a 'true' nullable to pass to the function, and we do this // by passing a boxed nullable that we unbox. We allocated this space earlier however we // did not know the data location until just now. Fill it in with the data and use that // to pass to the function. if (Nullable::IsNullableType(byrefArgTH)) { _ASSERTE(*pObjectRefArg != 0 && (*pObjectRefArg)->GetMethodTable() == byrefArgTH.GetMethodTable()); if (o1 != *pObjectRefArg) { Nullable::UnBoxNoCheck((*pObjectRefArg)->GetData(), o1, (*pObjectRefArg)->GetMethodTable()); o1 = *pObjectRefArg; } } if (o1 == NULL) { COMPlusThrow(kArgumentNullException); } _ASSERTE(o1->GetMethodTable()->IsValueType()); // Unbox the little fella to get a pointer to the raw data. void *pData = o1->GetData(); // If it is ByRef, then we just replace the ObjectRef with a pointer to the data. *pArgument = PtrToArgSlot(pData); } } // Validate any objectrefs that are supposed to be on the stack. // <TODO>@TODO: Move this to before the boxing/unboxing above</TODO> if (!fNeedBoxOrUnbox) { Object *objPtr; if (!isByRef) { if (IsElementTypeSpecial(argSigType)) { // validate the integrity of the object objPtr = (Object*)ArgSlotToPtr(*pArgument); if (FAILED(ValidateObject(objPtr))) { COMPlusThrow(kArgumentException, W("Argument_BadObjRef")); } } } else { _ASSERTE(argSigType == ELEMENT_TYPE_BYREF); if (IsElementTypeSpecial(byrefArgSigType)) { objPtr = *(Object**)(ArgSlotToPtr(*pArgument)); if (FAILED(ValidateObject(objPtr))) { COMPlusThrow(kArgumentException, W("Argument_BadObjRef")); } } } } } } } static CorDebugRegister GetArgAddrFromReg( DebuggerIPCE_FuncEvalArgData *pFEAD) { CorDebugRegister retval = REGISTER_INSTRUCTION_POINTER; // good as default as any #if defined(HOST_64BIT) retval = (pFEAD->argHome.kind == RAK_REG ? pFEAD->argHome.reg1 : (CorDebugRegister)((int)REGISTER_IA64_F0 + pFEAD->argHome.floatIndex)); #else // !HOST_64BIT retval = pFEAD->argHome.reg1; #endif // !HOST_64BIT return retval; } // // Given info about a byref argument, retrieve the current value from the pBufferForArgsArray, // the pMaybeInteriorPtrArray, the pByRefMaybeInteriorPtrArray, or the pObjectRefArray. Then // place it back into the proper register or address. // // Note that we should never use the argAddr of the DebuggerIPCE_FuncEvalArgData in this function // since the address may be an interior GC pointer and may have been moved by the GC. Instead, // use the pByRefMaybeInteriorPtrArray. // static void SetFuncEvalByRefArgValue(DebuggerEval *pDE, DebuggerIPCE_FuncEvalArgData *pFEAD, CorElementType byrefArgSigType, INT64 bufferByRefArg, void *maybeInteriorPtrArg, void *byRefMaybeInteriorPtrArg, OBJECTREF objectRefByRefArg) { WRAPPER_NO_CONTRACT; switch (pFEAD->argElementType) { case ELEMENT_TYPE_I8: case ELEMENT_TYPE_U8: case ELEMENT_TYPE_R8: // 64bit values { INT64 source; #if defined(HOST_64BIT) source = (INT64)maybeInteriorPtrArg; #else // !HOST_64BIT source = bufferByRefArg; #endif // !HOST_64BIT if (pFEAD->argIsLiteral) { // If this was a literal arg, then copy the updated primitive back into the literal. memcpy(pFEAD->argLiteralData, &source, sizeof(pFEAD->argLiteralData)); } else if (pFEAD->argAddr != NULL) { *((INT64 *)byRefMaybeInteriorPtrArg) = source; return; } else { #if !defined(HOST_64BIT) // RAK_REG is the only 4 byte type, all others are 8 byte types. _ASSERTE(pFEAD->argHome.kind != RAK_REG); SIZE_T *pLow = (SIZE_T*)(&source); SIZE_T *pHigh = pLow + 1; switch (pFEAD->argHome.kind) { case RAK_REGREG: SetRegisterValue(pDE, pFEAD->argHome.u.reg2, pFEAD->argHome.u.reg2Addr, *pLow); SetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, *pHigh); break; case RAK_MEMREG: SetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, *pLow); *((SIZE_T*)CORDB_ADDRESS_TO_PTR(pFEAD->argHome.addr)) = *pHigh; break; case RAK_REGMEM: *((SIZE_T*)CORDB_ADDRESS_TO_PTR(pFEAD->argHome.addr)) = *pLow; SetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, *pHigh); break; default: break; } #else // HOST_64BIT // The only types we use are RAK_REG and RAK_FLOAT, and both of them can be 4 or 8 bytes. _ASSERTE((pFEAD->argHome.kind == RAK_REG) || (pFEAD->argHome.kind == RAK_FLOAT)); SetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, source); #endif // HOST_64BIT } } break; default: // literal values smaller than 8 bytes and "special types" (e.g. object, array, string, etc.) { SIZE_T source; #ifdef TARGET_X86 if ((pFEAD->argElementType == ELEMENT_TYPE_I4) || (pFEAD->argElementType == ELEMENT_TYPE_U4) || (pFEAD->argElementType == ELEMENT_TYPE_R4)) { source = (SIZE_T)maybeInteriorPtrArg; } else { #endif source = (SIZE_T)bufferByRefArg; #ifdef TARGET_X86 } #endif if (pFEAD->argIsLiteral) { // If this was a literal arg, then copy the updated primitive back into the literal. // The literall buffer is a fixed size (8 bytes), but our source may be 4 or 8 bytes // depending on the platform. To prevent reading past the end of the source, we // zero the destination buffer and copy only as many bytes as available. memset( pFEAD->argLiteralData, 0, sizeof(pFEAD->argLiteralData) ); if (IsElementTypeSpecial(pFEAD->argElementType)) { _ASSERTE( sizeof(pFEAD->argLiteralData) >= sizeof(objectRefByRefArg) ); memcpy(pFEAD->argLiteralData, &objectRefByRefArg, sizeof(objectRefByRefArg)); } else { _ASSERTE( sizeof(pFEAD->argLiteralData) >= sizeof(source) ); memcpy(pFEAD->argLiteralData, &source, sizeof(source)); } } else if (pFEAD->argAddr == NULL) { // If the 32bit value is enregistered, copy it back to the proper regs. // RAK_REG is the only valid 4 byte type on WIN32. On WIN64, both RAK_REG and RAK_FLOAT can be // 4 bytes or 8 bytes. _ASSERTE((pFEAD->argHome.kind == RAK_REG) BIT64_ONLY(|| (pFEAD->argHome.kind == RAK_FLOAT))); CorDebugRegister regNum = GetArgAddrFromReg(pFEAD); // Shove the result back into the proper register. if (IsElementTypeSpecial(pFEAD->argElementType)) { SetRegisterValue(pDE, regNum, pFEAD->argHome.reg1Addr, (SIZE_T)ObjToArgSlot(objectRefByRefArg)); } else { SetRegisterValue(pDE, regNum, pFEAD->argHome.reg1Addr, (SIZE_T)source); } } else { // If the result was an object by ref, then copy back the new location of the object (in GC case). if (pFEAD->argIsHandleValue) { // do nothing. The Handle was passed in the pArgument array directly } else if (IsElementTypeSpecial(pFEAD->argElementType)) { *((SIZE_T*)byRefMaybeInteriorPtrArg) = (SIZE_T)ObjToArgSlot(objectRefByRefArg); } else if (pFEAD->argElementType == ELEMENT_TYPE_VALUETYPE) { // Do nothing, we passed in the pointer to the valuetype in the pArgument array directly. } else { GetAndSetLiteralValue(byRefMaybeInteriorPtrArg, pFEAD->argElementType, &source, ELEMENT_TYPE_PTR); } } } // end default } // end switch } /* * GCProtectAllPassedArgs * * This routine is the first step in doing a func-eval. For a complete overview, see * the comments at the top of this file. * * This routine over-aggressively protects all arguments that may be references to * managed objects. This function cannot crawl the function signature, since doing * so may trigger a GC, and thus, we must assume everything is ByRef. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * pObjectRefArray - An array that contains any object refs. It was built previously. * pMaybeInteriorPtrArray - An array that contains values that may be pointers to * the interior of a managed object. * pBufferForArgsArray - An array for holding stuff that does not need to be protected. * Any handle for the 'this' pointer is put in here for pulling it out later. * * Returns: * None. * */ static void GCProtectAllPassedArgs(DebuggerEval *pDE, OBJECTREF *pObjectRefArray, void **pMaybeInteriorPtrArray, void **pByRefMaybeInteriorPtrArray, INT64 *pBufferForArgsArray DEBUG_ARG(DataLocation pDataLocationArray[]) ) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; DebuggerIPCE_FuncEvalArgData *argData = pDE->GetArgData(); unsigned currArgIndex = 0; // // Gather all the information for the parameters. // for ( ; currArgIndex < pDE->m_argCount; currArgIndex++) { DebuggerIPCE_FuncEvalArgData *pFEAD = &argData[currArgIndex]; // In case any of the arguments is a by ref argument and points into the GC heap, // we need to GC protect their addresses as well. if (pFEAD->argAddr != NULL) { pByRefMaybeInteriorPtrArray[currArgIndex] = pFEAD->argAddr; } switch (pFEAD->argElementType) { case ELEMENT_TYPE_I8: case ELEMENT_TYPE_U8: case ELEMENT_TYPE_R8: // 64bit values #if defined(HOST_64BIT) // // Only need to worry about protecting if a pointer is a 64 bit quantity. // _ASSERTE(sizeof(void *) == sizeof(INT64)); if (pFEAD->argAddr != NULL) { pMaybeInteriorPtrArray[currArgIndex] = *((void **)(pFEAD->argAddr)); #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_MaybeInteriorPtrArray; } #endif } else if (pFEAD->argIsLiteral) { _ASSERTE(sizeof(pFEAD->argLiteralData) >= sizeof(void *)); // // If this is a byref literal arg, then it maybe an interior ptr. // void *v = NULL; memcpy(&v, pFEAD->argLiteralData, sizeof(v)); pMaybeInteriorPtrArray[currArgIndex] = v; #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_MaybeInteriorPtrArray; } #endif } else { _ASSERTE((pFEAD->argHome.kind == RAK_REG) || (pFEAD->argHome.kind == RAK_FLOAT)); CorDebugRegister regNum = GetArgAddrFromReg(pFEAD); SIZE_T v = GetRegisterValue(pDE, regNum, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); pMaybeInteriorPtrArray[currArgIndex] = (void *)(v); #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_MaybeInteriorPtrArray; } #endif } #endif // HOST_64BIT break; case ELEMENT_TYPE_VALUETYPE: // // If the value type address could be an interior pointer. // if (pFEAD->argAddr != NULL) { pMaybeInteriorPtrArray[currArgIndex] = ((void **)(pFEAD->argAddr)); } INDEBUG(pDataLocationArray[currArgIndex] |= DL_MaybeInteriorPtrArray); break; case ELEMENT_TYPE_CLASS: case ELEMENT_TYPE_OBJECT: case ELEMENT_TYPE_STRING: case ELEMENT_TYPE_ARRAY: case ELEMENT_TYPE_SZARRAY: if (pFEAD->argAddr != NULL) { if (pFEAD->argIsHandleValue) { OBJECTHANDLE oh = (OBJECTHANDLE)(pFEAD->argAddr); pBufferForArgsArray[currArgIndex] = (INT64)(size_t)oh; INDEBUG(pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray); } else { pObjectRefArray[currArgIndex] = *((OBJECTREF *)(pFEAD->argAddr)); INDEBUG(pDataLocationArray[currArgIndex] |= DL_ObjectRefArray); } } else if (pFEAD->argIsLiteral) { _ASSERTE(sizeof(pFEAD->argLiteralData) >= sizeof(OBJECTREF)); OBJECTREF v = NULL; memcpy(&v, pFEAD->argLiteralData, sizeof(v)); pObjectRefArray[currArgIndex] = v; #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_ObjectRefArray; } #endif } else { // RAK_REG is the only valid pointer-sized type. _ASSERTE(pFEAD->argHome.kind == RAK_REG); // Simply grab the value out of the proper register. SIZE_T v = GetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); // The argument is the address. pObjectRefArray[currArgIndex] = (OBJECTREF)v; #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_ObjectRefArray; } #endif } break; case ELEMENT_TYPE_I4: case ELEMENT_TYPE_U4: case ELEMENT_TYPE_R4: // 32bit values #ifdef TARGET_X86 _ASSERTE(sizeof(void *) == sizeof(INT32)); if (pFEAD->argAddr != NULL) { if (pFEAD->argIsHandleValue) { // // Ignorable - no need to protect // } else { pMaybeInteriorPtrArray[currArgIndex] = *((void **)(pFEAD->argAddr)); #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_MaybeInteriorPtrArray; } #endif } } else if (pFEAD->argIsLiteral) { _ASSERTE(sizeof(pFEAD->argLiteralData) >= sizeof(INT32)); // // If this is a byref literal arg, then it maybe an interior ptr. // void *v = NULL; memcpy(&v, pFEAD->argLiteralData, sizeof(v)); pMaybeInteriorPtrArray[currArgIndex] = v; #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_MaybeInteriorPtrArray; } #endif } else { // RAK_REG is the only valid 4 byte type on WIN32. _ASSERTE(pFEAD->argHome.kind == RAK_REG); // Simply grab the value out of the proper register. SIZE_T v = GetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); // The argument is the address. pMaybeInteriorPtrArray[currArgIndex] = (void *)v; #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_MaybeInteriorPtrArray; } #endif } #endif // TARGET_X86 FALLTHROUGH; default: // // Ignorable - no need to protect // break; } } } /* * ResolveFuncEvalGenericArgInfo * * This function pulls out any generic args and makes sure the method is loaded for it. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * * Returns: * None. * */ void ResolveFuncEvalGenericArgInfo(DebuggerEval *pDE) { CONTRACTL { THROWS; GC_TRIGGERS; } CONTRACTL_END; DebuggerIPCE_TypeArgData *firstdata = pDE->GetTypeArgData(); unsigned int nGenericArgs = pDE->m_genericArgsCount; SIZE_T cbAllocSize; if ((!ClrSafeInt<SIZE_T>::multiply(nGenericArgs, sizeof(TypeHandle *), cbAllocSize)) || (cbAllocSize != (size_t)(cbAllocSize))) { ThrowHR(COR_E_OVERFLOW); } TypeHandle * pGenericArgs = (nGenericArgs == 0) ? NULL : (TypeHandle *) _alloca(cbAllocSize); // // Snag the type arguments from the input and get the // method desc that corresponds to the instantiated desc. // Debugger::TypeDataWalk walk(firstdata, pDE->m_genericArgsNodeCount); walk.ReadTypeHandles(nGenericArgs, pGenericArgs); // <TODO>better error message</TODO> if (!walk.Finished()) { COMPlusThrow(kArgumentException, W("Argument_InvalidGenericArg")); } // Find the proper MethodDesc that we need to call. // Since we're already in the target domain, it can't be unloaded so it's safe to // use domain specific structures like the Module*. _ASSERTE( GetAppDomain() == pDE->m_debuggerModule->GetAppDomain() ); pDE->m_md = g_pEEInterface->LoadMethodDef(pDE->m_debuggerModule->GetRuntimeModule(), pDE->m_methodToken, nGenericArgs, pGenericArgs, &(pDE->m_ownerTypeHandle)); // We better have a MethodDesc at this point. _ASSERTE(pDE->m_md != NULL); ValidateFuncEvalReturnType(pDE->m_evalType , pDE->m_md->GetMethodTable()); // If this is a new object operation, then we should have a .ctor. if ((pDE->m_evalType == DB_IPCE_FET_NEW_OBJECT) && !pDE->m_md->IsCtor()) { COMPlusThrow(kArgumentException, W("Argument_MissingDefaultConstructor")); } pDE->m_md->EnsureActive(); // Run the Class Init for this class, if necessary. MethodTable * pOwningMT = pDE->m_ownerTypeHandle.GetMethodTable(); pOwningMT->EnsureInstanceActive(); pOwningMT->CheckRunClassInitThrowing(); if (pDE->m_evalType == DB_IPCE_FET_NEW_OBJECT) { // Work out the exact type of the allocated object pDE->m_resultType = (nGenericArgs == 0) ? TypeHandle(pDE->m_md->GetMethodTable()) : g_pEEInterface->LoadInstantiation(pDE->m_md->GetModule(), pDE->m_md->GetMethodTable()->GetCl(), nGenericArgs, pGenericArgs); } } /* * BoxFuncEvalThisParameter * * This function is a helper for DoNormalFuncEval. It boxes the 'this' parameter if necessary. * For example, when a method Object.ToString is called on a value class like System.DateTime * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * argData - Array of information about the arguments. * pMaybeInteriorPtrArray - An array that contains values that may be pointers to * the interior of a managed object. * pObjectRef - A GC protected place to put a boxed value, if necessary. * * Returns: * None * */ void BoxFuncEvalThisParameter(DebuggerEval *pDE, DebuggerIPCE_FuncEvalArgData *argData, void **pMaybeInteriorPtrArray, OBJECTREF *pObjectRefArg // out DEBUG_ARG(DataLocation pDataLocationArray[]) ) { WRAPPER_NO_CONTRACT; // // See if we have a value type that is going to be passed as a 'this' pointer. // if ((pDE->m_evalType != DB_IPCE_FET_NEW_OBJECT) && !pDE->m_md->IsStatic() && (pDE->m_argCount > 0)) { // Allocate the space for box nullables. Nullable parameters need a unboxed // nullable value to point at, where our current representation does not have // an unboxed value inside them. Thus we need another buffer to hold it (and // gcprotects it. We used boxed values for this by converting them to 'true' // nullable form, calling the function, and in the case of byrefs, converting // them back afterward. MethodTable* pMT = pDE->m_md->GetMethodTable(); if (Nullable::IsNullableType(pMT)) { OBJECTREF obj = AllocateObject(pMT); if (*pObjectRefArg != NULL) { BOOL typesMatch = Nullable::UnBox(obj->GetData(), *pObjectRefArg, pMT); (void)typesMatch; //prevent "unused variable" error from GCC _ASSERTE(typesMatch); } *pObjectRefArg = obj; } if (argData[0].argElementType == ELEMENT_TYPE_VALUETYPE) { // // See if we need to box up the 'this' parameter. // if (!pDE->m_md->GetMethodTable()->IsValueType()) { DebuggerIPCE_FuncEvalArgData *pFEAD = &argData[0]; SIZE_T v; LPVOID pAddr = NULL; INT64 bigVal; { GCX_FORBID(); //pAddr is unprotected from the time we initialize it if (pFEAD->argAddr != NULL) { _ASSERTE(pDataLocationArray[0] & DL_MaybeInteriorPtrArray); pAddr = pMaybeInteriorPtrArray[0]; INDEBUG(pDataLocationArray[0] &= ~DL_MaybeInteriorPtrArray); } else { pAddr = GetRegisterValueAndReturnAddress(pDE, pFEAD, &bigVal, &v); if (pAddr == NULL) { COMPlusThrow(kArgumentNullException); } } _ASSERTE(pAddr != NULL); } //GCX_FORBID GCPROTECT_BEGININTERIOR(pAddr); //ReadTypeHandle may trigger a GC and move the object that has the value type at pAddr as a field // // Grab the class of this value type. If the type is a parameterized // struct type then it may not have yet been loaded by the EE (generics // code sharing may have meant we have never bothered to create the exact // type yet). // // A buffer should have been allocated for the full struct type _ASSERTE(argData[0].fullArgType != NULL); Debugger::TypeDataWalk walk((DebuggerIPCE_TypeArgData *) argData[0].fullArgType, argData[0].fullArgTypeNodeCount); TypeHandle typeHandle = walk.ReadTypeHandle(); if (typeHandle.IsNull()) { COMPlusThrow(kArgumentException, W("Argument_BadObjRef")); } // // Box up this value type // *pObjectRefArg = typeHandle.GetMethodTable()->Box(pAddr); if (Nullable::IsNullableType(typeHandle.GetMethodTable()) && (*pObjectRefArg == NULL)) { COMPlusThrow(kArgumentNullException); } GCPROTECT_END(); INDEBUG(pDataLocationArray[0] |= DL_ObjectRefArray); } } } } // // This is used to store (temporarily) information about the arguments that func-eval // will pass. It is used only for the args of the function, not the return buffer nor // the 'this' pointer, if there is any of either. // struct FuncEvalArgInfo { CorElementType argSigType; CorElementType byrefArgSigType; TypeHandle byrefArgTypeHandle; bool fNeedBoxOrUnbox; TypeHandle sigTypeHandle; }; /* * GatherFuncEvalArgInfo * * This function is a helper for DoNormalFuncEval. It gathers together all the information * necessary to process the arguments. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * mSig - The metadata signature of the fuction to call. * argData - Array of information about the arguments. * pFEArgInfo - An array of structs to hold the argument information. * * Returns: * None. * */ void GatherFuncEvalArgInfo(DebuggerEval *pDE, MetaSig mSig, DebuggerIPCE_FuncEvalArgData *argData, FuncEvalArgInfo *pFEArgInfo // out ) { WRAPPER_NO_CONTRACT; unsigned currArgIndex = 0; if ((pDE->m_evalType == DB_IPCE_FET_NORMAL) && !pDE->m_md->IsStatic()) { // // Skip over the 'this' arg, since this function is not supposed to mess with it. // currArgIndex++; } // // Gather all the information for the parameters. // for ( ; currArgIndex < pDE->m_argCount; currArgIndex++) { DebuggerIPCE_FuncEvalArgData *pFEAD = &argData[currArgIndex]; // // Move to the next arg in the signature. // CorElementType argSigType = mSig.NextArgNormalized(); _ASSERTE(argSigType != ELEMENT_TYPE_END); // // If this arg is a byref arg, then we'll need to know what type we're referencing for later... // TypeHandle byrefTypeHandle = TypeHandle(); CorElementType byrefArgSigType = ELEMENT_TYPE_END; if (argSigType == ELEMENT_TYPE_BYREF) { byrefArgSigType = mSig.GetByRefType(&byrefTypeHandle); } // // If the sig says class but we've got a value class parameter, then remember that we need to box it. If // the sig says value class, but we've got a boxed value class, then remember that we need to unbox it. // bool fNeedBoxOrUnbox = ((argSigType == ELEMENT_TYPE_CLASS) && (pFEAD->argElementType == ELEMENT_TYPE_VALUETYPE)) || (((argSigType == ELEMENT_TYPE_VALUETYPE) && ((pFEAD->argElementType == ELEMENT_TYPE_CLASS) || (pFEAD->argElementType == ELEMENT_TYPE_OBJECT))) || // This is when method signature is expecting a BYREF ValueType, yet we receive the boxed valuetype's handle. (pFEAD->argElementType == ELEMENT_TYPE_CLASS && argSigType == ELEMENT_TYPE_BYREF && byrefArgSigType == ELEMENT_TYPE_VALUETYPE)); pFEArgInfo[currArgIndex].argSigType = argSigType; pFEArgInfo[currArgIndex].byrefArgSigType = byrefArgSigType; pFEArgInfo[currArgIndex].byrefArgTypeHandle = byrefTypeHandle; pFEArgInfo[currArgIndex].fNeedBoxOrUnbox = fNeedBoxOrUnbox; pFEArgInfo[currArgIndex].sigTypeHandle = mSig.GetLastTypeHandleThrowing(); } } /* * BoxFuncEvalArguments * * This function is a helper for DoNormalFuncEval. It boxes all the arguments that * need to be. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * argData - Array of information about the arguments. * pFEArgInfo - An array of structs to hold the argument information. * pMaybeInteriorPtrArray - An array that contains values that may be pointers to * the interior of a managed object. * pObjectRef - A GC protected place to put a boxed value, if necessary. * * Returns: * None * */ void BoxFuncEvalArguments(DebuggerEval *pDE, DebuggerIPCE_FuncEvalArgData *argData, FuncEvalArgInfo *pFEArgInfo, void **pMaybeInteriorPtrArray, OBJECTREF *pObjectRef // out DEBUG_ARG(DataLocation pDataLocationArray[]) ) { WRAPPER_NO_CONTRACT; unsigned currArgIndex = 0; if ((pDE->m_evalType == DB_IPCE_FET_NORMAL) && !pDE->m_md->IsStatic()) { // // Skip over the 'this' arg, since this function is not supposed to mess with it. // currArgIndex++; } // // Gather all the information for the parameters. // for ( ; currArgIndex < pDE->m_argCount; currArgIndex++) { DebuggerIPCE_FuncEvalArgData *pFEAD = &argData[currArgIndex]; // Allocate the space for box nullables. Nullable parameters need a unboxed // nullable value to point at, where our current representation does not have // an unboxed value inside them. Thus we need another buffer to hold it (and // gcprotects it. We used boxed values for this by converting them to 'true' // nullable form, calling the function, and in the case of byrefs, converting // them back afterward. TypeHandle th = pFEArgInfo[currArgIndex].sigTypeHandle; if (pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_BYREF) th = pFEArgInfo[currArgIndex].byrefArgTypeHandle; if (!th.IsNull() && Nullable::IsNullableType(th)) { OBJECTREF obj = AllocateObject(th.AsMethodTable()); if (pObjectRef[currArgIndex] != NULL) { BOOL typesMatch = Nullable::UnBox(obj->GetData(), pObjectRef[currArgIndex], th.AsMethodTable()); (void)typesMatch; //prevent "unused variable" error from GCC _ASSERTE(typesMatch); } pObjectRef[currArgIndex] = obj; } // // Check if we should box this value now // if ((pFEAD->argElementType == ELEMENT_TYPE_VALUETYPE) && (pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_BYREF) && pFEArgInfo[currArgIndex].fNeedBoxOrUnbox) { SIZE_T v; INT64 bigVal; LPVOID pAddr = NULL; if (pFEAD->argAddr != NULL) { _ASSERTE(pDataLocationArray[currArgIndex] & DL_MaybeInteriorPtrArray); pAddr = pMaybeInteriorPtrArray[currArgIndex]; INDEBUG(pDataLocationArray[currArgIndex] &= ~DL_MaybeInteriorPtrArray); } else { pAddr = GetRegisterValueAndReturnAddress(pDE, pFEAD, &bigVal, &v); if (pAddr == NULL) { COMPlusThrow(kArgumentNullException); } } _ASSERTE(pAddr != NULL); MethodTable * pMT = pFEArgInfo[currArgIndex].sigTypeHandle.GetMethodTable(); // // Stuff the newly boxed item into our GC-protected array. // pObjectRef[currArgIndex] = pMT->Box(pAddr); #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_ObjectRefArray; } #endif } } } /* * GatherFuncEvalMethodInfo * * This function is a helper for DoNormalFuncEval. It gathers together all the information * necessary to process the method * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * mSig - The metadata signature of the fuction to call. * argData - Array of information about the arguments. * ppUnboxedMD - Returns a resolve method desc if the original is an unboxing stub. * pObjectRefArray - GC protected array of objects passed to this func-eval call. * used to resolve down to the method target for generics. * pBufferForArgsArray - Array of values not needing gc-protection. May hold the * handle for the method targer for generics. * pfHasRetBuffArg - TRUE if the function has a return buffer. * pRetValueType - The TypeHandle of the return value. * * * Returns: * None. * */ void GatherFuncEvalMethodInfo(DebuggerEval *pDE, MetaSig mSig, DebuggerIPCE_FuncEvalArgData *argData, MethodDesc **ppUnboxedMD, OBJECTREF *pObjectRefArray, INT64 *pBufferForArgsArray, BOOL *pfHasRetBuffArg, // out BOOL *pfHasNonStdByValReturn, // out TypeHandle *pRetValueType // out, only if fHasRetBuffArg == true DEBUG_ARG(DataLocation pDataLocationArray[]) ) { WRAPPER_NO_CONTRACT; // // If 'this' is a non-static function that points to an unboxing stub, we need to return the // unboxed method desc to really call. // if ((pDE->m_evalType != DB_IPCE_FET_NEW_OBJECT) && !pDE->m_md->IsStatic() && pDE->m_md->IsUnboxingStub()) { *ppUnboxedMD = pDE->m_md->GetMethodTable()->GetUnboxedEntryPointMD(pDE->m_md); } // // Resolve down to the method on the class of the 'this' parameter. // if ((pDE->m_evalType != DB_IPCE_FET_NEW_OBJECT) && pDE->m_md->IsVtableMethod()) { // // Assuming that a constructor can't be an interface method... // _ASSERTE(pDE->m_evalType == DB_IPCE_FET_NORMAL); // // We need to go grab the 'this' argument to figure out what class we're headed for... // if (pDE->m_argCount == 0) { COMPlusThrow(kArgumentException, W("Argument_BadObjRef")); } // // We should have a valid this pointer. // <TODO>@todo: But the check should cover the register kind as well!</TODO> // if ((argData[0].argHome.kind == RAK_NONE) && (argData[0].argAddr == NULL)) { COMPlusThrow(kArgumentNullException); } // // Assume we can only have this for real objects or boxed value types, not value classes... // _ASSERTE((argData[0].argElementType == ELEMENT_TYPE_OBJECT) || (argData[0].argElementType == ELEMENT_TYPE_STRING) || (argData[0].argElementType == ELEMENT_TYPE_CLASS) || (argData[0].argElementType == ELEMENT_TYPE_ARRAY) || (argData[0].argElementType == ELEMENT_TYPE_SZARRAY) || ((argData[0].argElementType == ELEMENT_TYPE_VALUETYPE) && (pObjectRefArray[0] != NULL))); // // Now get the object pointer to our first arg. // OBJECTREF objRef = NULL; GCPROTECT_BEGIN(objRef); if (argData[0].argElementType == ELEMENT_TYPE_VALUETYPE) { // // In this case, we know where it is. // objRef = pObjectRefArray[0]; _ASSERTE(pDataLocationArray[0] & DL_ObjectRefArray); } else { TypeHandle dummyTH; ARG_SLOT objSlot; // // Take out the first arg. We're gonna trick GetFuncEvalArgValue by passing in just our // object ref as the stack. // // Note that we are passing ELEMENT_TYPE_END in the last parameter because we want to // supress the the valid object ref check. // GetFuncEvalArgValue(pDE, &(argData[0]), false, false, dummyTH, ELEMENT_TYPE_CLASS, dummyTH, &objSlot, NULL, pObjectRefArray, pBufferForArgsArray, NULL, ELEMENT_TYPE_END DEBUG_ARG(pDataLocationArray[0]) ); objRef = ArgSlotToObj(objSlot); } // // Validate the object // if (FAILED(ValidateObject(OBJECTREFToObject(objRef)))) { COMPlusThrow(kArgumentException, W("Argument_BadObjRef")); } // // Null isn't valid in this case! // if (objRef == NULL) { COMPlusThrow(kArgumentNullException); } // // Make sure that the object supplied is of a type that can call the method supplied. // if (!g_pEEInterface->ObjIsInstanceOf(OBJECTREFToObject(objRef), pDE->m_ownerTypeHandle)) { COMPlusThrow(kArgumentException, W("Argument_CORDBBadMethod")); } // // Now, find the proper MethodDesc for this interface method based on the object we're invoking the // method on. // pDE->m_targetCodeAddr = pDE->m_md->GetCallTarget(&objRef, pDE->m_ownerTypeHandle); GCPROTECT_END(); } else { pDE->m_targetCodeAddr = pDE->m_md->GetCallTarget(NULL, pDE->m_ownerTypeHandle); } // // Get the resulting type now. Doing this may trigger a GC or throw. // if (pDE->m_evalType != DB_IPCE_FET_NEW_OBJECT) { pDE->m_resultType = mSig.GetRetTypeHandleThrowing(); } // // Check if there is an explicit return argument, or if the return type is really a VALUETYPE but our // calling convention is passing it in registers. We just need to remember the pretValueClass so // that we will box it properly on our way out. // { ArgIterator argit(&mSig); *pfHasRetBuffArg = argit.HasRetBuffArg(); *pfHasNonStdByValReturn = argit.HasNonStandardByvalReturn(); } CorElementType retType = mSig.GetReturnType(); CorElementType retTypeNormalized = mSig.GetReturnTypeNormalized(); if (*pfHasRetBuffArg || *pfHasNonStdByValReturn || ((retType == ELEMENT_TYPE_VALUETYPE) && (retType != retTypeNormalized))) { *pRetValueType = mSig.GetRetTypeHandleThrowing(); } else { // // Make sure the caller initialized this value // _ASSERTE((*pRetValueType).IsNull()); } } /* * CopyArgsToBuffer * * This routine copies all the arguments to a local buffer, so that any one that needs to be * passed can be. Note that this local buffer is NOT GC-protected, and so all the values * in the buffer may not be relied on. You *must* use GetFuncEvalArgValue() to load up the * Arguments for the call, because it has the logic to decide which of the parallel arrays to pull * from. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * argData - Array of information about the arguments. * pFEArgInfo - An array of structs to hold the argument information. Must have be previously filled in. * pBufferArray - An array to store values. * * Returns: * None. * */ void CopyArgsToBuffer(DebuggerEval *pDE, DebuggerIPCE_FuncEvalArgData *argData, FuncEvalArgInfo *pFEArgInfo, INT64 *pBufferArray DEBUG_ARG(DataLocation pDataLocationArray[]) ) { CONTRACTL { THROWS; GC_NOTRIGGER; } CONTRACTL_END; unsigned currArgIndex = 0; if ((pDE->m_evalType == DB_IPCE_FET_NORMAL) && !pDE->m_md->IsStatic()) { // // Skip over the 'this' arg, since this function is not supposed to mess with it. // currArgIndex++; } // // Spin thru each argument now // for ( ; currArgIndex < pDE->m_argCount; currArgIndex++) { DebuggerIPCE_FuncEvalArgData *pFEAD = &argData[currArgIndex]; BOOL isByRef = (pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_BYREF); BOOL fNeedBoxOrUnbox; fNeedBoxOrUnbox = pFEArgInfo[currArgIndex].fNeedBoxOrUnbox; LOG((LF_CORDB, LL_EVERYTHING, "CATB: currArgIndex=%d\n", currArgIndex)); LOG((LF_CORDB, LL_EVERYTHING, "\t: argSigType=0x%x, byrefArgSigType=0x%0x, inType=0x%0x\n", pFEArgInfo[currArgIndex].argSigType, pFEArgInfo[currArgIndex].byrefArgSigType, pFEAD->argElementType)); INT64 *pDest = &(pBufferArray[currArgIndex]); switch (pFEAD->argElementType) { case ELEMENT_TYPE_I8: case ELEMENT_TYPE_U8: case ELEMENT_TYPE_R8: if (pFEAD->argAddr != NULL) { *pDest = *(INT64*)(pFEAD->argAddr); #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } else if (pFEAD->argIsLiteral) { _ASSERTE(sizeof(pFEAD->argLiteralData) >= sizeof(void *)); // If this is a literal arg, then we just copy the data. memcpy(pDest, pFEAD->argLiteralData, sizeof(INT64)); #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } else { #if !defined(HOST_64BIT) // RAK_REG is the only 4 byte type, all others are 8 byte types. _ASSERTE(pFEAD->argHome.kind != RAK_REG); INT64 bigVal = 0; SIZE_T v; INT64 *pAddr; pAddr = (INT64*)GetRegisterValueAndReturnAddress(pDE, pFEAD, &bigVal, &v); if (pAddr == NULL) { COMPlusThrow(kArgumentNullException); } *pDest = *pAddr; #else // HOST_64BIT // Both RAK_REG and RAK_FLOAT can be either 4 bytes or 8 bytes. _ASSERTE((pFEAD->argHome.kind == RAK_REG) || (pFEAD->argHome.kind == RAK_FLOAT)); CorDebugRegister regNum = GetArgAddrFromReg(pFEAD); *pDest = GetRegisterValue(pDE, regNum, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); #endif // HOST_64BIT #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } break; case ELEMENT_TYPE_VALUETYPE: // // For value types, we dont do anything here, instead delay until GetFuncEvalArgInfo // break; case ELEMENT_TYPE_CLASS: case ELEMENT_TYPE_OBJECT: case ELEMENT_TYPE_STRING: case ELEMENT_TYPE_ARRAY: case ELEMENT_TYPE_SZARRAY: if (pFEAD->argAddr != NULL) { if (!isByRef) { if (pFEAD->argIsHandleValue) { OBJECTHANDLE oh = (OBJECTHANDLE)(pFEAD->argAddr); *pDest = (INT64)(size_t)oh; } else { *pDest = *((SIZE_T*)(pFEAD->argAddr)); } #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } else { if (pFEAD->argIsHandleValue) { *pDest = (INT64)(size_t)(pFEAD->argAddr); } else { *pDest = *(SIZE_T*)(pFEAD->argAddr); } #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } } else if (pFEAD->argIsLiteral) { _ASSERTE(sizeof(pFEAD->argLiteralData) >= sizeof(INT64)); // The called function may expect a larger/smaller value than the literal value. // So we convert the value to the right type. CONSISTENCY_CHECK_MSGF(((pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_CLASS) || (pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_SZARRAY) || (pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_ARRAY)) || (isByRef && ((pFEArgInfo[currArgIndex].byrefArgSigType == ELEMENT_TYPE_CLASS) || (pFEArgInfo[currArgIndex].byrefArgSigType == ELEMENT_TYPE_SZARRAY) || (pFEArgInfo[currArgIndex].byrefArgSigType == ELEMENT_TYPE_ARRAY))), ("argSigType=0x%0x, byrefArgSigType=0x%0x, isByRef=%d", pFEArgInfo[currArgIndex].argSigType, pFEArgInfo[currArgIndex].byrefArgSigType, isByRef)); LOG((LF_CORDB, LL_EVERYTHING, "argSigType=0x%0x, byrefArgSigType=0x%0x, isByRef=%d\n", pFEArgInfo[currArgIndex].argSigType, pFEArgInfo[currArgIndex].byrefArgSigType, isByRef)); *(SIZE_T*)pDest = *(SIZE_T*)pFEAD->argLiteralData; #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } else { // RAK_REG is the only valid 4 byte type on WIN32. On WIN64, RAK_REG and RAK_FLOAT // can both be either 4 bytes or 8 bytes; _ASSERTE((pFEAD->argHome.kind == RAK_REG) BIT64_ONLY(|| (pFEAD->argHome.kind == RAK_FLOAT))); CorDebugRegister regNum = GetArgAddrFromReg(pFEAD); // Simply grab the value out of the proper register. SIZE_T v = GetRegisterValue(pDE, regNum, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); *pDest = v; #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } break; default: // 4-byte, 2-byte, or 1-byte values if (pFEAD->argAddr != NULL) { if (!isByRef) { if (pFEAD->argIsHandleValue) { OBJECTHANDLE oh = (OBJECTHANDLE)(pFEAD->argAddr); *pDest = (INT64)(size_t)oh; } else { GetAndSetLiteralValue(pDest, pFEArgInfo[currArgIndex].argSigType, pFEAD->argAddr, pFEAD->argElementType); } #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } else { if (pFEAD->argIsHandleValue) { *pDest = (INT64)(size_t)(pFEAD->argAddr); } else { // We have to make sure we only grab the correct size of memory from the source. On IA64, we // have to make sure we don't cause misaligned data exceptions as well. Then we put the value // into the pBufferArray. The reason is that we may be passing in some values by ref to a // function that's expecting something of a bigger size. Thus, if we don't do this, then we'll // be bashing memory right next to the source value as the function being called acts upon some // bigger value. GetAndSetLiteralValue(pDest, pFEArgInfo[currArgIndex].byrefArgSigType, pFEAD->argAddr, pFEAD->argElementType); } #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } } else if (pFEAD->argIsLiteral) { _ASSERTE(sizeof(pFEAD->argLiteralData) >= sizeof(INT32)); // The called function may expect a larger/smaller value than the literal value, // so we convert the value to the right type. CONSISTENCY_CHECK_MSGF( ((pFEArgInfo[currArgIndex].argSigType>=ELEMENT_TYPE_BOOLEAN) && (pFEArgInfo[currArgIndex].argSigType<=ELEMENT_TYPE_R8)) || (pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_PTR) || (pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_I) || (pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_U) || (isByRef && ((pFEArgInfo[currArgIndex].byrefArgSigType>=ELEMENT_TYPE_BOOLEAN) && (pFEArgInfo[currArgIndex].byrefArgSigType<=ELEMENT_TYPE_R8))), ("argSigType=0x%0x, byrefArgSigType=0x%0x, isByRef=%d", pFEArgInfo[currArgIndex].argSigType, pFEArgInfo[currArgIndex].byrefArgSigType, isByRef)); LOG((LF_CORDB, LL_EVERYTHING, "argSigType=0x%0x, byrefArgSigType=0x%0x, isByRef=%d\n", pFEArgInfo[currArgIndex].argSigType, pFEArgInfo[currArgIndex].byrefArgSigType, isByRef)); CorElementType relevantType = (isByRef ? pFEArgInfo[currArgIndex].byrefArgSigType : pFEArgInfo[currArgIndex].argSigType); GetAndSetLiteralValue(pDest, relevantType, pFEAD->argLiteralData, pFEAD->argElementType); #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } else { // RAK_REG is the only valid 4 byte type on WIN32. On WIN64, RAK_REG and RAK_FLOAT // can both be either 4 bytes or 8 bytes; _ASSERTE((pFEAD->argHome.kind == RAK_REG) BIT64_ONLY(|| (pFEAD->argHome.kind == RAK_FLOAT))); CorDebugRegister regNum = GetArgAddrFromReg(pFEAD); // Simply grab the value out of the proper register. SIZE_T v = GetRegisterValue(pDE, regNum, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); *pDest = v; #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } } } } /* * PackArgumentArray * * This routine fills a given array with the correct values for passing to a managed function. * It uses various component arrays that contain information to correctly create the argument array. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * argData - Array of information about the arguments. * pUnboxedMD - MethodDesc of the function to call, after unboxing. * RetValueType - Type Handle of the return value of the managed function we will call. * pFEArgInfo - An array of structs to hold the argument information. Must have be previously filled in. * pObjectRefArray - An array that contains any object refs. It was built previously. * pMaybeInteriorPtrArray - An array that contains values that may be pointers to * the interior of a managed object. * pBufferForArgsArray - An array that contains values that need writable memory space * for passing ByRef. * newObj - Pre-allocated object for a 'new' call. * pArguments - This array is packed from the above arrays. * ppRetValue - Return value buffer if fRetValueArg is TRUE * * Returns: * None. * */ void PackArgumentArray(DebuggerEval *pDE, DebuggerIPCE_FuncEvalArgData *argData, FuncEvalArgInfo *pFEArgInfo, MethodDesc *pUnboxedMD, TypeHandle RetValueType, OBJECTREF *pObjectRefArray, void **pMaybeInteriorPtrArray, INT64 *pBufferForArgsArray, ValueClassInfo ** ppProtectedValueClasses, OBJECTREF newObj, BOOL fRetValueArg, ARG_SLOT *pArguments, PVOID * ppRetValue DEBUG_ARG(DataLocation pDataLocationArray[]) ) { WRAPPER_NO_CONTRACT; GCX_FORBID(); unsigned currArgIndex = 0; unsigned currArgSlot = 0; // // THIS POINTER (if any) // For non-static methods, or when returning a new object, // the first arg in the array is 'this' or the new object. // if (pDE->m_evalType == DB_IPCE_FET_NEW_OBJECT) { // // If this is a new object op, then we need to fill in the 0'th // arg slot with the 'this' ptr. // pArguments[0] = ObjToArgSlot(newObj); // // If we are invoking a function on a value class, but we have a boxed value class for 'this', // then go ahead and unbox it and leave a ref to the value class on the stack as 'this'. // if (pDE->m_md->GetMethodTable()->IsValueType()) { _ASSERTE(newObj->GetMethodTable()->IsValueType()); // This is one of those places we use true boxed nullables _ASSERTE(!Nullable::IsNullableType(pDE->m_md->GetMethodTable()) || newObj->GetMethodTable() == pDE->m_md->GetMethodTable()); void *pData = newObj->GetData(); pArguments[0] = PtrToArgSlot(pData); } // // Bump up the arg slot // currArgSlot++; } else if (!pDE->m_md->IsStatic()) { // // Place 'this' first in the array for non-static methods. // TypeHandle dummyTH; bool isByRef = false; bool fNeedBoxOrUnbox = false; // We had better have an object for a 'this' argument! CorElementType et = argData[0].argElementType; if (!(IsElementTypeSpecial(et) || et == ELEMENT_TYPE_VALUETYPE)) { COMPlusThrow(kArgumentOutOfRangeException, W("ArgumentOutOfRange_Enum")); } LOG((LF_CORDB, LL_EVERYTHING, "this: currArgSlot=%d, currArgIndex=%d et=0x%x\n", currArgSlot, currArgIndex, et)); if (pDE->m_md->GetMethodTable()->IsValueType()) { // For value classes, the 'this' parameter is always passed by reference. // However do not unbox if we are calling an unboxing stub. if (pDE->m_md == pUnboxedMD) { // pDE->m_md is expecting an unboxed this pointer. Then we will unbox it. isByRef = true; // Remember if we need to unbox this parameter, though. if ((et == ELEMENT_TYPE_CLASS) || (et == ELEMENT_TYPE_OBJECT)) { fNeedBoxOrUnbox = true; } } } else if (et == ELEMENT_TYPE_VALUETYPE) { // When the method that we invoking is defined on non value type and we receive the ValueType as input, // we are calling methods on System.Object. In this case, we need to box the input ValueType. fNeedBoxOrUnbox = true; } GetFuncEvalArgValue(pDE, &argData[currArgIndex], isByRef, fNeedBoxOrUnbox, dummyTH, ELEMENT_TYPE_CLASS, pDE->m_md->GetMethodTable(), &(pArguments[currArgSlot]), &(pMaybeInteriorPtrArray[currArgIndex]), &(pObjectRefArray[currArgIndex]), &(pBufferForArgsArray[currArgIndex]), NULL, ELEMENT_TYPE_OBJECT DEBUG_ARG((currArgIndex < MAX_DATA_LOCATIONS_TRACKED) ? pDataLocationArray[currArgIndex] : DL_All) ); LOG((LF_CORDB, LL_EVERYTHING, "this = 0x%08x\n", ArgSlotToPtr(pArguments[currArgSlot]))); // We need to check 'this' for a null ref ourselves... NOTE: only do this if we put an object reference on // the stack. If we put a byref for a value type, then we don't need to do this! if (!isByRef) { // The this pointer is not a unboxed value type. ARG_SLOT oi1 = pArguments[currArgSlot]; OBJECTREF o1 = ArgSlotToObj(oi1); if (FAILED(ValidateObject(OBJECTREFToObject(o1)))) { COMPlusThrow(kArgumentException, W("Argument_BadObjRef")); } if (OBJECTREFToObject(o1) == NULL) { COMPlusThrow(kNullReferenceException, W("NullReference_This")); } // For interface method, we have already done the check early on. if (!pDE->m_md->IsInterface()) { // We also need to make sure that the method that we are invoking is either defined on this object or the direct/indirect // base objects. Object *objPtr = OBJECTREFToObject(o1); MethodTable *pMT = objPtr->GetMethodTable(); // <TODO> Do this check in the following cases as well... </TODO> if (!pMT->IsArray() && !pDE->m_md->IsSharedByGenericInstantiations()) { TypeHandle thFrom = TypeHandle(pMT); TypeHandle thTarget = TypeHandle(pDE->m_md->GetMethodTable()); //<TODO> What about MaybeCast?</TODO> if (thFrom.CanCastToCached(thTarget) == TypeHandle::CannotCast) { COMPlusThrow(kArgumentException, W("Argument_CORDBBadMethod")); } } } } // // Increment up both arrays. // currArgSlot++; currArgIndex++; } // Special handling for functions that return value classes. if (fRetValueArg) { LOG((LF_CORDB, LL_EVERYTHING, "retBuff: currArgSlot=%d, currArgIndex=%d\n", currArgSlot, currArgIndex)); // // Allocate buffer for return value and GC protect it in case it contains object references // unsigned size = RetValueType.GetMethodTable()->GetNumInstanceFieldBytes(); #ifdef FEATURE_HFA // The buffer for HFAs has to be always ENREGISTERED_RETURNTYPE_MAXSIZE size = max(size, ENREGISTERED_RETURNTYPE_MAXSIZE); #endif BYTE * pTemp = new (interopsafe) BYTE[ALIGN_UP(sizeof(ValueClassInfo), 8) + size]; ValueClassInfo * pValueClassInfo = (ValueClassInfo *)pTemp; LPVOID pData = pTemp + ALIGN_UP(sizeof(ValueClassInfo), 8); memset(pData, 0, size); pValueClassInfo->pData = pData; pValueClassInfo->pMT = RetValueType.GetMethodTable(); pValueClassInfo->pNext = *ppProtectedValueClasses; *ppProtectedValueClasses = pValueClassInfo; pArguments[currArgSlot++] = PtrToArgSlot(pData); *ppRetValue = pData; } // REAL ARGUMENTS (if any) // Now do the remaining args for ( ; currArgIndex < pDE->m_argCount; currArgSlot++, currArgIndex++) { DebuggerIPCE_FuncEvalArgData *pFEAD = &argData[currArgIndex]; LOG((LF_CORDB, LL_EVERYTHING, "currArgSlot=%d, currArgIndex=%d\n", currArgSlot, currArgIndex)); LOG((LF_CORDB, LL_EVERYTHING, "\t: argSigType=0x%x, byrefArgSigType=0x%0x, inType=0x%0x\n", pFEArgInfo[currArgIndex].argSigType, pFEArgInfo[currArgIndex].byrefArgSigType, pFEAD->argElementType)); GetFuncEvalArgValue(pDE, pFEAD, pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_BYREF, pFEArgInfo[currArgIndex].fNeedBoxOrUnbox, pFEArgInfo[currArgIndex].sigTypeHandle, pFEArgInfo[currArgIndex].byrefArgSigType, pFEArgInfo[currArgIndex].byrefArgTypeHandle, &(pArguments[currArgSlot]), &(pMaybeInteriorPtrArray[currArgIndex]), &(pObjectRefArray[currArgIndex]), &(pBufferForArgsArray[currArgIndex]), ppProtectedValueClasses, pFEArgInfo[currArgIndex].argSigType DEBUG_ARG((currArgIndex < MAX_DATA_LOCATIONS_TRACKED) ? pDataLocationArray[currArgIndex] : DL_All) ); } } /* * UnpackFuncEvalResult * * This routine takes the resulting object of a func-eval, and does any copying, boxing, unboxing, necessary. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * newObj - Pre-allocated object for NEW_OBJ func-evals. * retObject - Pre-allocated object to be filled in with the info in pRetBuff. * RetValueType - The return type of the function called. * pRetBuff - The raw bytes returned by the func-eval call when there is a return buffer parameter. * * * Returns: * None. * */ void UnpackFuncEvalResult(DebuggerEval *pDE, OBJECTREF newObj, OBJECTREF retObject, TypeHandle RetValueType, void *pRetBuff ) { CONTRACTL { WRAPPER(THROWS); GC_NOTRIGGER; } CONTRACTL_END; // Ah, but if this was a new object op, then the result is really // the object we allocated above... if (pDE->m_evalType == DB_IPCE_FET_NEW_OBJECT) { // We purposely do not morph nullables to be boxed Ts here because debugger EE's otherwise // have no way of creating true nullables that they need for their own purposes. pDE->m_result[0] = ObjToArgSlot(newObj); pDE->m_retValueBoxing = Debugger::AllBoxed; } else if (!RetValueType.IsNull()) { LOG((LF_CORDB, LL_EVERYTHING, "FuncEval call is saving a boxed VC return value.\n")); // // We pre-created it above // _ASSERTE(retObject != NULL); // This is one of those places we use true boxed nullables _ASSERTE(!Nullable::IsNullableType(RetValueType)|| retObject->GetMethodTable() == RetValueType.GetMethodTable()); if (pRetBuff != NULL) { // box the object CopyValueClass(retObject->GetData(), pRetBuff, RetValueType.GetMethodTable()); } else { // box the primitive returned, retObject is a true nullable for nullabes, It will be Normalized later CopyValueClass(retObject->GetData(), pDE->m_result, RetValueType.GetMethodTable()); } pDE->m_result[0] = ObjToArgSlot(retObject); pDE->m_retValueBoxing = Debugger::AllBoxed; } else { // // Other FuncEvals return primitives as unboxed. // pDE->m_retValueBoxing = Debugger::OnlyPrimitivesUnboxed; } LOG((LF_CORDB, LL_INFO10000, "FuncEval call has saved the return value.\n")); // No exception, so it worked as far as we're concerned. pDE->m_successful = true; // If the result is an object, then place the object // reference into a strong handle and place the handle into the // pDE to protect the result from a collection. CorElementType retClassET = pDE->m_resultType.GetSignatureCorElementType(); if ((pDE->m_retValueBoxing == Debugger::AllBoxed) || !RetValueType.IsNull() || IsElementTypeSpecial(retClassET)) { LOG((LF_CORDB, LL_EVERYTHING, "Creating strong handle for boxed DoNormalFuncEval result.\n")); OBJECTHANDLE oh = pDE->m_thread->GetDomain()->CreateStrongHandle(ArgSlotToObj(pDE->m_result[0])); pDE->m_result[0] = (INT64)(LONG_PTR)oh; pDE->m_vmObjectHandle = VMPTR_OBJECTHANDLE::MakePtr(oh); } } /* * UnpackFuncEvalArguments * * This routine takes the resulting object of a func-eval, and does any copying, boxing, unboxing, necessary. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * newObj - Pre-allocated object for NEW_OBJ func-evals. * retObject - Pre-allocated object to be filled in with the info in pSource. * RetValueType - The return type of the function called. * pSource - The raw bytes returned by the func-eval call when there is a hidden parameter. * * * Returns: * None. * */ void UnpackFuncEvalArguments(DebuggerEval *pDE, DebuggerIPCE_FuncEvalArgData *argData, MetaSig mSig, BOOL staticMethod, OBJECTREF *pObjectRefArray, void **pMaybeInteriorPtrArray, void **pByRefMaybeInteriorPtrArray, INT64 *pBufferForArgsArray ) { WRAPPER_NO_CONTRACT; // Update any enregistered byrefs with their new values from the // proper byref temporary array. if (pDE->m_argCount > 0) { mSig.Reset(); unsigned currArgIndex = 0; if ((pDE->m_evalType == DB_IPCE_FET_NORMAL) && !pDE->m_md->IsStatic()) { // // Skip over the 'this' arg, since this function is not supposed to mess with it. // currArgIndex++; } for (; currArgIndex < pDE->m_argCount; currArgIndex++) { CorElementType argSigType = mSig.NextArgNormalized(); LOG((LF_CORDB, LL_EVERYTHING, "currArgIndex=%d argSigType=0x%x\n", currArgIndex, argSigType)); _ASSERTE(argSigType != ELEMENT_TYPE_END); if (argSigType == ELEMENT_TYPE_BYREF) { TypeHandle byrefClass = TypeHandle(); CorElementType byrefArgSigType = mSig.GetByRefType(&byrefClass); // If these are the true boxed nullables we created in BoxFuncEvalArguments, convert them back pObjectRefArray[currArgIndex] = Nullable::NormalizeBox(pObjectRefArray[currArgIndex]); LOG((LF_CORDB, LL_EVERYTHING, "DoNormalFuncEval: Updating enregistered byref...\n")); SetFuncEvalByRefArgValue(pDE, &argData[currArgIndex], byrefArgSigType, pBufferForArgsArray[currArgIndex], pMaybeInteriorPtrArray[currArgIndex], pByRefMaybeInteriorPtrArray[currArgIndex], pObjectRefArray[currArgIndex] ); } } } } /* * FuncEvalWrapper * * Helper function for func-eval. We have to split it out so that we can put a __try / __finally in to * notify on a Catch-Handler found. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * pArguments - created stack to pass for the call. * pCatcherStackAddr - stack address to report as the Catch Handler Found location. * * Returns: * None. * */ void FuncEvalWrapper(MethodDescCallSite* pMDCS, DebuggerEval *pDE, const ARG_SLOT *pArguments, BYTE *pCatcherStackAddr) { struct Param : NotifyOfCHFFilterWrapperParam { MethodDescCallSite* pMDCS; DebuggerEval *pDE; const ARG_SLOT *pArguments; }; Param param; param.pFrame = pCatcherStackAddr; // Inherited from NotifyOfCHFFilterWrapperParam param.pMDCS = pMDCS; param.pDE = pDE; param.pArguments = pArguments; PAL_TRY(Param *, pParam, &param) { pParam->pMDCS->CallWithValueTypes_RetArgSlot(pParam->pArguments, pParam->pDE->m_result, sizeof(pParam->pDE->m_result)); } PAL_EXCEPT_FILTER(NotifyOfCHFFilterWrapper) { // Should never reach here b/c handler should always continue search. _ASSERTE(false); } PAL_ENDTRY } /* * RecordFuncEvalException * * Helper function records the details of an exception that occurred during a FuncEval * Note that this should be called from within the target domain of the FuncEval. * * Parameters: * pDE - pointer to the DebuggerEval object being processed * ppException - the Exception object that was thrown * * Returns: * None. */ static void RecordFuncEvalException(DebuggerEval *pDE, OBJECTREF ppException ) { CONTRACTL { THROWS; // CreateStrongHandle could throw OOM GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; // We got an exception. Make the exception into our result. pDE->m_successful = false; LOG((LF_CORDB, LL_EVERYTHING, "D::FEHW - Exception during funceval.\n")); // // Special handling for thread abort exceptions. We need to explicitly reset the // abort request on the EE thread, then make sure to place this thread on a thunk // that will re-raise the exception when we continue the process. Note: we still // pass this thread abort exception up as the result of the eval. // if (IsExceptionOfType(kThreadAbortException, &ppException)) { _ASSERTE(pDE->m_aborting != DebuggerEval::FE_ABORT_NONE); // // Reset the abort request. // pDE->m_thread->ResetAbort(); // // This is the abort we sent down. // memset(pDE->m_result, 0, sizeof(pDE->m_result)); pDE->m_resultType = TypeHandle(); pDE->m_aborted = true; pDE->m_retValueBoxing = Debugger::NoValueTypeBoxing; LOG((LF_CORDB, LL_EVERYTHING, "D::FEHW - funceval abort exception.\n")); } else { // // The result is the exception object. // pDE->m_result[0] = ObjToArgSlot(ppException); pDE->m_resultType = ppException->GetTypeHandle(); OBJECTHANDLE oh = pDE->m_thread->GetDomain()->CreateStrongHandle(ArgSlotToObj(pDE->m_result[0])); pDE->m_result[0] = (ARG_SLOT)(LONG_PTR)oh; pDE->m_vmObjectHandle = VMPTR_OBJECTHANDLE::MakePtr(oh); pDE->m_retValueBoxing = Debugger::NoValueTypeBoxing; LOG((LF_CORDB, LL_EVERYTHING, "D::FEHW - Exception for the user.\n")); } } /* * DoNormalFuncEval * * Does the main body of work (steps 1c onward) for the normal func-eval algorithm detailed at the * top of this file. The args have already been GC protected and we've transitioned into the appropriate * domain (steps 1a & 1b). This has to be a seperate function from GCProtectArgsAndDoNormalFuncEval * because otherwise we can't reliably find the right GCFrames to pop when unwinding the stack due to * an exception on 64-bit platforms (we have some GCFrames outside of the TRY, and some inside, * and they won't necesarily be layed out sequentially on the stack if they are all in the same function). * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * pCatcherStackAddr - stack address to report as the Catch Handler Found location. * pObjectRefArray - An array to hold object ref args. This array is protected from GC's. * pMaybeInteriorPtrArray - An array to hold values that may be pointers into a managed object. * This array is protected from GCs. * pByRefMaybeInteriorPtrArray - An array to hold values that may be pointers into a managed * object. This array is protected from GCs. This array protects the address of the arguments * while the pMaybeInteriorPtrArray protects the value of the arguments. We need to do this * because of by ref arguments. * pBufferForArgsArray - a buffer of temporary scratch space for things that do not need to be * protected, or are protected for free (e.g. Handles). * pDataLocationArray - an array of tracking data for debug sanity checks * * Returns: * None. */ static void DoNormalFuncEval( DebuggerEval *pDE, BYTE *pCatcherStackAddr, OBJECTREF *pObjectRefArray, void **pMaybeInteriorPtrArray, void **pByRefMaybeInteriorPtrArray, INT64 *pBufferForArgsArray, ValueClassInfo ** ppProtectedValueClasses DEBUG_ARG(DataLocation pDataLocationArray[]) ) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; // // Now that all the args are protected, we can go back and deal with generic args and resolving // all their information. // ResolveFuncEvalGenericArgInfo(pDE); // // Grab the signature of the method we're working on and do some error checking. // Note that if this instantiated generic code, then this will // correctly give as an instantiated view of the signature that we can iterate without // worrying about generic items in the signature. // MetaSig mSig(pDE->m_md); BYTE callingconvention = mSig.GetCallingConvention(); if (!isCallConv(callingconvention, IMAGE_CEE_CS_CALLCONV_DEFAULT)) { // We don't support calling vararg! COMPlusThrow(kArgumentException, W("Argument_CORDBBadVarArgCallConv")); } // // We'll need to know if this is a static method or not. // BOOL staticMethod = pDE->m_md->IsStatic(); _ASSERTE((pDE->m_evalType == DB_IPCE_FET_NORMAL) || !staticMethod); // // Do Step 1c - Pre-allocate space for new objects. // OBJECTREF newObj = NULL; GCPROTECT_BEGIN(newObj); SIZE_T allocArgCnt = 0; if (pDE->m_evalType == DB_IPCE_FET_NEW_OBJECT) { ValidateFuncEvalReturnType(DB_IPCE_FET_NEW_OBJECT, pDE->m_resultType.GetMethodTable()); pDE->m_resultType.GetMethodTable()->EnsureInstanceActive(); newObj = AllocateObject(pDE->m_resultType.GetMethodTable()); // // Note: we account for an extra argument in the count passed // in. We use this to increase the space allocated for args, // and we use it to control the number of args copied into // those arrays below. Note: m_argCount already includes space // for this. // allocArgCnt = pDE->m_argCount + 1; } else { allocArgCnt = pDE->m_argCount; } // // Validate the argument count with mSig. // if (allocArgCnt != (mSig.NumFixedArgs() + (staticMethod ? 0 : 1))) { COMPlusThrow(kTargetParameterCountException, W("Arg_ParmCnt")); } // // Do Step 1d - Gather information about the method that will be called. // // An array to hold information about the parameters to be passed. This is // all the information we need to gather before entering the GCX_FORBID area. // DebuggerIPCE_FuncEvalArgData *argData = pDE->GetArgData(); MethodDesc *pUnboxedMD = pDE->m_md; BOOL fHasRetBuffArg; BOOL fHasNonStdByValReturn; TypeHandle RetValueType; BoxFuncEvalThisParameter(pDE, argData, pMaybeInteriorPtrArray, pObjectRefArray DEBUG_ARG(pDataLocationArray) ); GatherFuncEvalMethodInfo(pDE, mSig, argData, &pUnboxedMD, pObjectRefArray, pBufferForArgsArray, &fHasRetBuffArg, &fHasNonStdByValReturn, &RetValueType DEBUG_ARG(pDataLocationArray) ); // // Do Step 1e - Gather info from runtime about args (may trigger a GC). // SIZE_T cbAllocSize; if (!(ClrSafeInt<SIZE_T>::multiply(pDE->m_argCount, sizeof(FuncEvalArgInfo), cbAllocSize)) || (cbAllocSize != (size_t)(cbAllocSize))) { ThrowHR(COR_E_OVERFLOW); } FuncEvalArgInfo * pFEArgInfo = (FuncEvalArgInfo *)_alloca(cbAllocSize); memset(pFEArgInfo, 0, cbAllocSize); GatherFuncEvalArgInfo(pDE, mSig, argData, pFEArgInfo); // // Do Step 1f - Box or unbox arguments one at a time, placing newly boxed items into // pObjectRefArray immediately after creating them. // BoxFuncEvalArguments(pDE, argData, pFEArgInfo, pMaybeInteriorPtrArray, pObjectRefArray DEBUG_ARG(pDataLocationArray) ); #ifdef _DEBUG if (!RetValueType.IsNull()) { _ASSERTE(RetValueType.IsValueType()); } #endif // // Do Step 1g - Pre-allocate any return value object. // OBJECTREF retObject = NULL; GCPROTECT_BEGIN(retObject); if ((pDE->m_evalType != DB_IPCE_FET_NEW_OBJECT) && !RetValueType.IsNull()) { ValidateFuncEvalReturnType(pDE->m_evalType, RetValueType.GetMethodTable()); RetValueType.GetMethodTable()->EnsureInstanceActive(); retObject = AllocateObject(RetValueType.GetMethodTable()); } // // Do Step 1h - Copy into scratch buffer all enregistered arguments, and // ByRef literals. // CopyArgsToBuffer(pDE, argData, pFEArgInfo, pBufferForArgsArray DEBUG_ARG(pDataLocationArray) ); // // We presume that the function has a return buffer. This assumption gets squeezed out // when we pack the argument array. // allocArgCnt++; LOG((LF_CORDB, LL_EVERYTHING, "Func eval for %s::%s: allocArgCnt=%d\n", pDE->m_md->m_pszDebugClassName, pDE->m_md->m_pszDebugMethodName, allocArgCnt)); MethodDescCallSite funcToEval(pDE->m_md, pDE->m_targetCodeAddr); // // Do Step 1i - Create and pack argument array for managed function call. // // Allocate space for argument stack // if ((!ClrSafeInt<SIZE_T>::multiply(allocArgCnt, sizeof(ARG_SLOT), cbAllocSize)) || (cbAllocSize != (size_t)(cbAllocSize))) { ThrowHR(COR_E_OVERFLOW); } ARG_SLOT * pArguments = (ARG_SLOT *)_alloca(cbAllocSize); memset(pArguments, 0, cbAllocSize); LPVOID pRetBuff = NULL; PackArgumentArray(pDE, argData, pFEArgInfo, pUnboxedMD, RetValueType, pObjectRefArray, pMaybeInteriorPtrArray, pBufferForArgsArray, ppProtectedValueClasses, newObj, #ifdef FEATURE_HFA fHasRetBuffArg || fHasNonStdByValReturn, #else fHasRetBuffArg, #endif pArguments, &pRetBuff DEBUG_ARG(pDataLocationArray) ); // // // Do Step 2 - Make the call! // // FuncEvalWrapper(&funcToEval, pDE, pArguments, pCatcherStackAddr); { // We have now entered the zone where taking a GC is fatal until we get the // return value all fixed up. // GCX_FORBID(); // // // Do Step 3 - Unpack results and update ByRef arguments. // // // LOG((LF_CORDB, LL_EVERYTHING, "FuncEval call has returned\n")); // GC still can't happen until we get our return value out half way through the unpack function UnpackFuncEvalResult(pDE, newObj, retObject, RetValueType, pRetBuff ); } UnpackFuncEvalArguments(pDE, argData, mSig, staticMethod, pObjectRefArray, pMaybeInteriorPtrArray, pByRefMaybeInteriorPtrArray, pBufferForArgsArray ); GCPROTECT_END(); // retObject GCPROTECT_END(); // newObj } /* * GCProtectArgsAndDoNormalFuncEval * * This routine is the primary entrypoint for normal func-evals. It implements the algorithm * described at the top of this file, doing steps 1a and 1b itself, then calling DoNormalFuncEval * to do the rest. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * pCatcherStackAddr - stack address to report as the Catch Handler Found location. * * Returns: * None. * */ static void GCProtectArgsAndDoNormalFuncEval(DebuggerEval *pDE, BYTE *pCatcherStackAddr ) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; INDEBUG(DataLocation pDataLocationArray[MAX_DATA_LOCATIONS_TRACKED]); // // An array to hold object ref args. This array is protected from GC's. // SIZE_T cbAllocSize; if ((!ClrSafeInt<SIZE_T>::multiply(pDE->m_argCount, sizeof(OBJECTREF), cbAllocSize)) || (cbAllocSize != (size_t)(cbAllocSize))) { ThrowHR(COR_E_OVERFLOW); } OBJECTREF * pObjectRefArray = (OBJECTREF*)_alloca(cbAllocSize); memset(pObjectRefArray, 0, cbAllocSize); GCPROTECT_ARRAY_BEGIN(*pObjectRefArray, pDE->m_argCount); // // An array to hold values that may be pointers into a managed object. This array // is protected from GCs. // if ((!ClrSafeInt<SIZE_T>::multiply(pDE->m_argCount, sizeof(void**), cbAllocSize)) || (cbAllocSize != (size_t)(cbAllocSize))) { ThrowHR(COR_E_OVERFLOW); } void ** pMaybeInteriorPtrArray = (void **)_alloca(cbAllocSize); memset(pMaybeInteriorPtrArray, 0, cbAllocSize); GCPROTECT_BEGININTERIOR_ARRAY(*pMaybeInteriorPtrArray, (UINT)(cbAllocSize/sizeof(OBJECTREF))); // // An array to hold values that may be pointers into a managed object. This array // is protected from GCs. This array protects the address of the arguments while the // pMaybeInteriorPtrArray protects the value of the arguments. We need to do this because // of by ref arguments. // if ((!ClrSafeInt<SIZE_T>::multiply(pDE->m_argCount, sizeof(void**), cbAllocSize)) || (cbAllocSize != (size_t)(cbAllocSize))) { ThrowHR(COR_E_OVERFLOW); } void ** pByRefMaybeInteriorPtrArray = (void **)_alloca(cbAllocSize); memset(pByRefMaybeInteriorPtrArray, 0, cbAllocSize); GCPROTECT_BEGININTERIOR_ARRAY(*pByRefMaybeInteriorPtrArray, (UINT)(cbAllocSize/sizeof(OBJECTREF))); // // A buffer of temporary scratch space for things that do not need to be protected, or // are protected for free (e.g. Handles). // if ((!ClrSafeInt<SIZE_T>::multiply(pDE->m_argCount, sizeof(INT64), cbAllocSize)) || (cbAllocSize != (size_t)(cbAllocSize))) { ThrowHR(COR_E_OVERFLOW); } INT64 *pBufferForArgsArray = (INT64*)_alloca(cbAllocSize); memset(pBufferForArgsArray, 0, cbAllocSize); FrameWithCookie<ProtectValueClassFrame> protectValueClassFrame; // // Initialize our tracking array // INDEBUG(memset(pDataLocationArray, 0, sizeof(DataLocation) * (MAX_DATA_LOCATIONS_TRACKED))); { GCX_FORBID(); // // Do step 1a // GCProtectAllPassedArgs(pDE, pObjectRefArray, pMaybeInteriorPtrArray, pByRefMaybeInteriorPtrArray, pBufferForArgsArray DEBUG_ARG(pDataLocationArray) ); } // // Do step 1b: we can switch domains since everything is now protected. // Note that before this point, it's unsafe to rely on pDE->m_module since it may be // invalid due to an AD unload. // All normal func evals should have an AppDomain specified. // // Wrap everything in a EX_TRY so we catch any exceptions that could be thrown. // Note that we don't let any thrown exceptions cross the AppDomain boundary because we don't // want them to get marshalled. EX_TRY { DoNormalFuncEval( pDE, pCatcherStackAddr, pObjectRefArray, pMaybeInteriorPtrArray, pByRefMaybeInteriorPtrArray, pBufferForArgsArray, protectValueClassFrame.GetValueClassInfoList() DEBUG_ARG(pDataLocationArray) ); } EX_CATCH { // We got an exception. Make the exception into our result. OBJECTREF ppException = GET_THROWABLE(); GCX_FORBID(); RecordFuncEvalException( pDE, ppException); } // Note: we need to catch all exceptioins here because they all get reported as the result of // the funceval. If a ThreadAbort occurred other than for a funcEval abort, we'll re-throw it manually. EX_END_CATCH(SwallowAllExceptions); protectValueClassFrame.Pop(); CleanUpTemporaryVariables(protectValueClassFrame.GetValueClassInfoList()); GCPROTECT_END(); // pByRefMaybeInteriorPtrArray GCPROTECT_END(); // pMaybeInteriorPtrArray GCPROTECT_END(); // pObjectRefArray LOG((LF_CORDB, LL_EVERYTHING, "DoNormalFuncEval: returning...\n")); } void FuncEvalHijackRealWorker(DebuggerEval *pDE, Thread* pThread, FuncEvalFrame* pFEFrame) { BYTE * pCatcherStackAddr = (BYTE*) pFEFrame; // Handle normal func evals in DoNormalFuncEval if ((pDE->m_evalType == DB_IPCE_FET_NEW_OBJECT) || (pDE->m_evalType == DB_IPCE_FET_NORMAL)) { GCProtectArgsAndDoNormalFuncEval(pDE, pCatcherStackAddr); LOG((LF_CORDB, LL_EVERYTHING, "DoNormalFuncEval has returned.\n")); return; } OBJECTREF newObj = NULL; GCPROTECT_BEGIN(newObj); // Wrap everything in a EX_TRY so we catch any exceptions that could be thrown. // Note that we don't let any thrown exceptions cross the AppDomain boundary because we don't // want them to get marshalled. EX_TRY { DebuggerIPCE_TypeArgData *firstdata = pDE->GetTypeArgData(); DWORD nGenericArgs = pDE->m_genericArgsCount; SIZE_T cbAllocSize; if ((!ClrSafeInt<SIZE_T>::multiply(nGenericArgs, sizeof(TypeHandle *), cbAllocSize)) || (cbAllocSize != (size_t)(cbAllocSize))) { ThrowHR(COR_E_OVERFLOW); } TypeHandle *pGenericArgs = (nGenericArgs == 0) ? NULL : (TypeHandle *) _alloca(cbAllocSize); // // Snag the type arguments from the input and get the // method desc that corresponds to the instantiated desc. // Debugger::TypeDataWalk walk(firstdata, pDE->m_genericArgsNodeCount); walk.ReadTypeHandles(nGenericArgs, pGenericArgs); // <TODO>better error message</TODO> if (!walk.Finished()) COMPlusThrow(kArgumentException, W("Argument_InvalidGenericArg")); switch (pDE->m_evalType) { case DB_IPCE_FET_NEW_OBJECT_NC: { // Find the class. TypeHandle thClass = g_pEEInterface->LoadClass(pDE->m_debuggerModule->GetRuntimeModule(), pDE->m_classToken); if (thClass.IsNull()) COMPlusThrow(kArgumentNullException, W("ArgumentNull_Type")); // Apply any type arguments TypeHandle th = (nGenericArgs == 0) ? thClass : g_pEEInterface->LoadInstantiation(pDE->m_debuggerModule->GetRuntimeModule(), pDE->m_classToken, nGenericArgs, pGenericArgs); if (th.IsNull() || th.ContainsGenericVariables()) COMPlusThrow(kArgumentException, W("Argument_InvalidGenericArg")); // Run the Class Init for this type, if necessary. MethodTable * pOwningMT = th.GetMethodTable(); pOwningMT->EnsureInstanceActive(); pOwningMT->CheckRunClassInitThrowing(); // Create a new instance of the class ValidateFuncEvalReturnType(DB_IPCE_FET_NEW_OBJECT_NC, th.GetMethodTable()); newObj = AllocateObject(th.GetMethodTable()); // No exception, so it worked. pDE->m_successful = true; // So is the result type. pDE->m_resultType = th; // // Box up all returned objects // pDE->m_retValueBoxing = Debugger::AllBoxed; // Make a strong handle for the result. OBJECTHANDLE oh = pDE->m_thread->GetDomain()->CreateStrongHandle(newObj); pDE->m_result[0] = (ARG_SLOT)(LONG_PTR)oh; pDE->m_vmObjectHandle = VMPTR_OBJECTHANDLE::MakePtr(oh); break; } case DB_IPCE_FET_NEW_STRING: { // Create the string. m_argData is not necessarily null terminated... // The numeration parameter represents the string length, not the buffer size, but // we have passed the buffer size across to copy our data properly, so must divide back out. // NewString will return NULL if pass null, but want an empty string in that case, so // just create an EmptyString explicitly. if ((pDE->m_argData == NULL) || (pDE->m_stringSize == 0)) { newObj = StringObject::GetEmptyString(); } else { newObj = StringObject::NewString(pDE->GetNewStringArgData(), (int)(pDE->m_stringSize/sizeof(WCHAR))); } // No exception, so it worked. pDE->m_successful = true; // Result type is, of course, a string. pDE->m_resultType = newObj->GetTypeHandle(); // Place the result in a strong handle to protect it from a collection. OBJECTHANDLE oh = pDE->m_thread->GetDomain()->CreateStrongHandle(newObj); pDE->m_result[0] = (ARG_SLOT)(LONG_PTR)oh; pDE->m_vmObjectHandle = VMPTR_OBJECTHANDLE::MakePtr(oh); break; } case DB_IPCE_FET_NEW_ARRAY: { // <TODO>@todo: We're only gonna handle SD arrays for right now.</TODO> if (pDE->m_arrayRank > 1) COMPlusThrow(kRankException, W("Rank_MultiDimNotSupported")); // Grab the elementType from the arg/data area. _ASSERTE(nGenericArgs == 1); TypeHandle th = pGenericArgs[0]; CorElementType et = th.GetSignatureCorElementType(); // Gotta be a primitive, class, or System.Object. if (((et < ELEMENT_TYPE_BOOLEAN) || (et > ELEMENT_TYPE_R8)) && !IsElementTypeSpecial(et)) { COMPlusThrow(kArgumentOutOfRangeException, W("ArgumentOutOfRange_Enum")); } // Grab the dims from the arg/data area. These come after the type arguments. SIZE_T *dims; dims = (SIZE_T*) (firstdata + pDE->m_genericArgsNodeCount); if (IsElementTypeSpecial(et)) { newObj = AllocateObjectArray((DWORD)dims[0], th); } else { // Create a simple array. Note: we can only do this type of create here due to the checks above. newObj = AllocatePrimitiveArray(et, (DWORD)dims[0]); } // No exception, so it worked. pDE->m_successful = true; // Result type is, of course, the type of the array. pDE->m_resultType = newObj->GetTypeHandle(); // Place the result in a strong handle to protect it from a collection. OBJECTHANDLE oh = pDE->m_thread->GetDomain()->CreateStrongHandle(newObj); pDE->m_result[0] = (ARG_SLOT)(LONG_PTR)oh; pDE->m_vmObjectHandle = VMPTR_OBJECTHANDLE::MakePtr(oh); break; } default: _ASSERTE(!"Invalid eval type!"); } } EX_CATCH { // We got an exception. Make the exception into our result. OBJECTREF ppException = GET_THROWABLE(); GCX_FORBID(); RecordFuncEvalException( pDE, ppException); } // Note: we need to catch all exceptioins here because they all get reported as the result of // the funceval. EX_END_CATCH(SwallowAllExceptions); GCPROTECT_END(); } // // FuncEvalHijackWorker is the function that managed threads start executing in order to perform a function // evaluation. Control is transfered here on the proper thread by hijacking that that's IP to this method in // Debugger::FuncEvalSetup. This function can also be called directly by a Runtime thread that is stopped sending a // first or second chance exception to the Right Side. // // The DebuggerEval object may get deleted by the helper thread doing a CleanupFuncEval while this thread is blocked // sending the eval complete. void * STDCALL FuncEvalHijackWorker(DebuggerEval *pDE) { CONTRACTL { MODE_COOPERATIVE; GC_TRIGGERS; THROWS; PRECONDITION(CheckPointer(pDE)); } CONTRACTL_END; Thread *pThread = NULL; CONTEXT *filterContext = NULL; { GCX_FORBID(); LOG((LF_CORDB, LL_INFO100000, "D:FEHW for pDE:%08x evalType:%d\n", pDE, pDE->m_evalType)); pThread = GetThread(); #ifndef DACCESS_COMPILE #ifdef _DEBUG // // Flush all debug tracking information for this thread on object refs as it // only approximates proper tracking and may have stale data, resulting in false // positives. We dont want that as func-eval runs a lot, so flush them now. // g_pEEInterface->ObjectRefFlush(pThread); #endif #endif if (!pDE->m_evalDuringException) { // // From this point forward we use FORBID regions to guard against GCs. // Refer to code:Debugger::FuncEvalSetup to see the increment was done. // g_pDebugger->DecThreadsAtUnsafePlaces(); } // Preemptive GC is disabled at the start of this method. _ASSERTE(g_pEEInterface->IsPreemptiveGCDisabled()); DebuggerController::DispatchFuncEvalEnter(pThread); // If we've got a filter context still installed, then remove it while we do the work... filterContext = g_pEEInterface->GetThreadFilterContext(pDE->m_thread); if (filterContext) { _ASSERTE(pDE->m_evalDuringException); g_pEEInterface->SetThreadFilterContext(pDE->m_thread, NULL); } } // // We cannot scope the following in a GCX_FORBID(), but we would like to. But we need the frames on the // stack here, so they must never go out of scope. // // // Push our FuncEvalFrame. The return address is equal to the IP in the saved context in the DebuggerEval. The // m_Datum becomes the ptr to the DebuggerEval. The frame address also serves as the address of the catch-handler-found. // FrameWithCookie<FuncEvalFrame> FEFrame(pDE, GetIP(&pDE->m_context), true); FEFrame.Push(); // On ARM/ARM64 the single step flag is per-thread and not per context. We need to make sure that the SS flag is cleared // for the funceval, and that the state is back to what it should be after the funceval completes. #ifdef FEATURE_EMULATE_SINGLESTEP bool ssEnabled = pDE->m_thread->IsSingleStepEnabled(); if (ssEnabled) pDE->m_thread->DisableSingleStep(); #endif FuncEvalHijackRealWorker(pDE, pThread, &FEFrame); #ifdef FEATURE_EMULATE_SINGLESTEP if (ssEnabled) pDE->m_thread->EnableSingleStep(); #endif LOG((LF_CORDB, LL_EVERYTHING, "FuncEval has finished its primary work.\n")); // // The func-eval is now completed, successfully or with failure, aborted or run-to-completion. // pDE->m_completed = true; if (pDE->m_thread->IsAbortRequested()) { // noone else shoud be requesting aborts, // so this must be our request that did not have a chance to run. _ASSERTE((pDE->m_aborting != DebuggerEval::FE_ABORT_NONE) && !pDE->m_aborted); // // Reset the abort request if a func-eval abort was submitted, but the func-eval completed // before the abort could take place, we want to make sure we do not throw an abort exception // in this case. // pDE->m_thread->ResetAbort(); } // Codepitching can hijack our frame's return address. That means that we'll need to update PC in our saved context // so that when its restored, its like we've returned to the codepitching hijack. At this point, the old value of // EIP is worthless anyway. if (!pDE->m_evalDuringException) { SetIP(&pDE->m_context, (SIZE_T)FEFrame.GetReturnAddress()); } // // Disable all steppers and breakpoints created during the func-eval // DebuggerController::DispatchFuncEvalExit(pThread); void *dest = NULL; if (!pDE->m_evalDuringException) { // Signal to the helper thread that we're done with our func eval. Start by creating a DebuggerFuncEvalComplete // object. Give it an address at which to create the patch, which is a chunk of memory specified by our // DebuggerEval big enough to hold a breakpoint instruction. #ifdef TARGET_ARM dest = (BYTE*)((DWORD)&(pDE->m_bpInfoSegment->m_breakpointInstruction) | THUMB_CODE); #else dest = &(pDE->m_bpInfoSegment->m_breakpointInstruction); #endif // // The created object below sets up itself as a hijack and will destroy itself when the hijack and work // is done. // DebuggerFuncEvalComplete *comp; comp = new (interopsafe) DebuggerFuncEvalComplete(pThread, dest); _ASSERTE(comp != NULL); // would have thrown // Pop the FuncEvalFrame now that we're pretty much done. Make sure we // don't pop the frame too early. Because GC can be triggered in our grabbing of // Debugger lock. If we pop the FE frame without setting back thread filter context, // the frames left uncrawlable. // FEFrame.Pop(); } else { // We don't have to setup any special hijacks to return from here when we've been processing during an // exception. We just go ahead and send the FuncEvalComplete event over now. Don't forget to enable/disable PGC // around the call... _ASSERTE(g_pEEInterface->IsPreemptiveGCDisabled()); if (filterContext != NULL) { g_pEEInterface->SetThreadFilterContext(pDE->m_thread, filterContext); } // Pop the FuncEvalFrame now that we're pretty much done. FEFrame.Pop(); { // // This also grabs the debugger lock, so we can atomically check if a detach has // happened. // SENDIPCEVENT_BEGIN(g_pDebugger, pDE->m_thread); if ((pDE->m_thread->GetDomain() != NULL) && pDE->m_thread->GetDomain()->IsDebuggerAttached()) { if (CORDebuggerAttached()) { g_pDebugger->FuncEvalComplete(pDE->m_thread, pDE); g_pDebugger->SyncAllThreads(SENDIPCEVENT_PtrDbgLockHolder); } } SENDIPCEVENT_END; } } // pDE may now point to deleted memory if the helper thread did a CleanupFuncEval while we // were blocked waiting for a continue after the func-eval complete. // We return the address that we want to resume executing at. return dest; } #if defined(FEATURE_EH_FUNCLETS) && !defined(TARGET_UNIX) EXTERN_C EXCEPTION_DISPOSITION FuncEvalHijackPersonalityRoutine(IN PEXCEPTION_RECORD pExceptionRecord BIT64_ARG(IN ULONG64 MemoryStackFp) NOT_BIT64_ARG(IN ULONG32 MemoryStackFp), IN OUT PCONTEXT pContextRecord, IN OUT PDISPATCHER_CONTEXT pDispatcherContext ) { DebuggerEval* pDE = NULL; #if defined(TARGET_AMD64) pDE = *(DebuggerEval**)(pDispatcherContext->EstablisherFrame); #elif defined(TARGET_ARM) // on ARM the establisher frame is the SP of the caller of FuncEvalHijack, on other platforms it's FuncEvalHijack's SP. // in FuncEvalHijack we allocate 8 bytes of stack space and then store R0 at the current SP, so if we subtract 8 from // the establisher frame we can get the stack location where R0 was stored. pDE = *(DebuggerEval**)(pDispatcherContext->EstablisherFrame - 8); #elif defined(TARGET_ARM64) // on ARM64 the establisher frame is the SP of the caller of FuncEvalHijack. // in FuncEvalHijack we allocate 32 bytes of stack space and then store R0 at the current SP + 16, so if we subtract 16 from // the establisher frame we can get the stack location where R0 was stored. pDE = *(DebuggerEval**)(pDispatcherContext->EstablisherFrame - 16); #else _ASSERTE(!"NYI - FuncEvalHijackPersonalityRoutine()"); #endif FixupDispatcherContext(pDispatcherContext, &(pDE->m_context), pContextRecord); // Returning ExceptionCollidedUnwind will cause the OS to take our new context record and // dispatcher context and restart the exception dispatching on this call frame, which is // exactly the behavior we want. return ExceptionCollidedUnwind; } #endif // FEATURE_EH_FUNCLETS && !TARGET_UNIX #endif // ifndef DACCESS_COMPILE
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // **************************************************************************** // File: funceval.cpp // // // funceval.cpp - Debugger func-eval routines. // // **************************************************************************** // Putting code & #includes, #defines, etc, before the stdafx.h will // cause the code,etc, to be silently ignored #include "stdafx.h" #include "debugdebugger.h" #include "../inc/common.h" #include "eeconfig.h" // This is here even for retail & free builds... #include "../../dlls/mscorrc/resource.h" #include "vars.hpp" #include "threads.h" #include "appdomain.inl" #include <limits.h> #include "ilformatter.h" #ifndef DACCESS_COMPILE // // This is the main file for processing func-evals. Nestle in // with a cup o' tea and read on. // // The most common case is handled in GCProtectArgsAndDoNormalFuncEval(), which follows // all the comments below. The two other corner cases are handled in // FuncEvalHijackWorker(), and are extremely straight-forward. // // There are several steps to successfully processing a func-eval. At a // very high level, the first step is to gather all the information necessary // to make the call (specifically, gather arg info and method info); the second // step is to actually make the call to managed code; finally, the third step // is to take all results and unpackage them. // // The first step (gathering arg and method info) has several critical passes that // must be made. // a) Protect all passed in args from a GC. // b) Transition into the appropriate AppDomain if necessary // c) Pre-allocate object for 'new' calls and, if necessary, box the 'this' argument. (May cause a GC) // d) Gather method info (May cause GC) // e) Gather info from runtime about args. (May cause a GC) // f) Box args that need to be, GC-protecting the newly boxed items. (May cause a GC) // g) Pre-allocate object for return values. (May cause a GC) // h) Copy to pBufferForArgsArray all the args. This array is used to hold values that // may need writable memory for ByRef args. // i) Create and load pArgumentArray to be passed as the stack for the managed call. // NOTE: From the time we load the first argument into the stack we cannot cause a GC // as the argument array cannot be GC-protected. // // The second step (Making the managed call), is relatively easy, and is a single call. // // The third step (unpacking all results), has a couple of passes as well. // a) Copy back all resulting values. // b) Free all temporary work memory. // // // The most difficult part of doing a func-eval is the first step, since once you // have everything set up, unpacking and calling are reverse, gc-safe, operations. Thus, // elaboration is needed on the first step. // // a) Protect all passed in args from a GC. This must be done in a gc-forbid region, // and the code path to this function must not trigger a gc either. In this function five // parallel arrays are used: pObjectRefArray, pMaybeInteriorPtrArray, pByRefMaybeInteriorPtrArray, // pBufferForArgsArray, and pArguments. // pObjectRefArray is used to gc-protect all arguments and results that are objects. // pMaybeInteriorPtrArray is used to gc-protect all arguments that might be pointers // to an interior of a managed object. // pByRefMaybeInteriorPtrArray is similar to pMaybeInteriorPtrArray, except that it protects the // address of the arguments instead of the arguments themselves. This is needed because we may have // by ref arguments whose address is an interior pointer into the GC heap. // pBufferForArgsArray is used strictly as a buffer for copying primitives // that need to be passed as ByRef, or may be enregistered. This array also holds // handles. // These first two arrays are mutually exclusive, that is, if there is an entry // in one array at index i, there should be no entry in either of the other arrays at // the same index. // pArguments is used as the complete array of arguments to pass to the managed function. // // Unfortunately the necessary information to complete pass (a) perfectly may cause a gc, so // instead, pass (a) is over-aggressive and protects the following: All object refs into // pObjectRefArray, and puts all values that could be raw pointers into pMaybeInteriorPtrArray. // // b) Discovers the method to be called, and if it is a 'new' allocate an object for the result. // // c) Gather information about the method that will be called. // // d) Here we gather information from the method signature which tells which args are // ByRef and various other flags. We will use this information in later passes. // // e) Using the information in pass (c), for each argument: box arguments, placing newly // boxed items into pObjectRefArray immediately after creating them. // // f) Pre-allocate any object for a returned value. // // g) Using the information is pass (c), all arguments are copied into a scratch buffer before // invoking the managed function. // // h) pArguments is loaded from the pre-allocated return object, the individual elements // of the other 3 arrays, and from any non-ByRef literals. This is the complete stack // to be passed to the managed function. For performance increase, it can remove any // overly aggressive items that were placed in pMaybeInteriorPtrArray. // // // IsElementTypeSpecial() // // This is a simple function used to check if a CorElementType needs special handling for func eval. // // parameters: type - the CorElementType which we need to check // // return value: true if the specified type needs special handling // inline static bool IsElementTypeSpecial(CorElementType type) { LIMITED_METHOD_CONTRACT; return ((type == ELEMENT_TYPE_CLASS) || (type == ELEMENT_TYPE_OBJECT) || (type == ELEMENT_TYPE_ARRAY) || (type == ELEMENT_TYPE_SZARRAY) || (type == ELEMENT_TYPE_STRING)); } // // GetAndSetLiteralValue() // // This helper function extracts the value out of the source pointer while taking into account alignment and size. // Then it stores the value into the destination pointer, again taking into account alignment and size. // // parameters: pDst - destination pointer // dstType - the CorElementType of the destination value // pSrc - source pointer // srcType - the CorElementType of the source value // // return value: none // inline static void GetAndSetLiteralValue(LPVOID pDst, CorElementType dstType, LPVOID pSrc, CorElementType srcType) { LIMITED_METHOD_CONTRACT; UINT64 srcValue; // Retrieve the value using the source CorElementType. switch (g_pEEInterface->GetSizeForCorElementType(srcType)) { case 1: srcValue = (UINT64)*((BYTE*)pSrc); break; case 2: srcValue = (UINT64)*((USHORT*)pSrc); break; case 4: srcValue = (UINT64)*((UINT32*)pSrc); break; case 8: srcValue = (UINT64)*((UINT64*)pSrc); break; default: UNREACHABLE(); } // Cast to the appropriate type using the destination CorElementType. switch (dstType) { case ELEMENT_TYPE_BOOLEAN: *(BYTE*)pDst = (BYTE)!!srcValue; break; case ELEMENT_TYPE_I1: *(INT8*)pDst = (INT8)srcValue; break; case ELEMENT_TYPE_U1: *(UINT8*)pDst = (UINT8)srcValue; break; case ELEMENT_TYPE_I2: *(INT16*)pDst = (INT16)srcValue; break; case ELEMENT_TYPE_U2: case ELEMENT_TYPE_CHAR: *(UINT16*)pDst = (UINT16)srcValue; break; #if !defined(HOST_64BIT) case ELEMENT_TYPE_I: #endif case ELEMENT_TYPE_I4: *(int*)pDst = (int)srcValue; break; #if !defined(HOST_64BIT) case ELEMENT_TYPE_U: #endif case ELEMENT_TYPE_U4: case ELEMENT_TYPE_R4: *(unsigned*)pDst = (unsigned)srcValue; break; #if defined(HOST_64BIT) case ELEMENT_TYPE_I: #endif case ELEMENT_TYPE_I8: case ELEMENT_TYPE_R8: *(INT64*)pDst = (INT64)srcValue; break; #if defined(HOST_64BIT) case ELEMENT_TYPE_U: #endif case ELEMENT_TYPE_U8: *(UINT64*)pDst = (UINT64)srcValue; break; case ELEMENT_TYPE_FNPTR: case ELEMENT_TYPE_PTR: *(void **)pDst = (void *)(SIZE_T)srcValue; break; default: UNREACHABLE(); } } // // Throw on not supported func evals // static void ValidateFuncEvalReturnType(DebuggerIPCE_FuncEvalType evalType, MethodTable * pMT) { CONTRACTL { THROWS; GC_TRIGGERS; } CONTRACTL_END; if (pMT == g_pStringClass) { if (evalType == DB_IPCE_FET_NEW_OBJECT || evalType == DB_IPCE_FET_NEW_OBJECT_NC) { // Cannot call New object on String constructor. COMPlusThrow(kArgumentException,W("Argument_CannotCreateString")); } } else if (g_pEEInterface->IsTypedReference(pMT)) { // Cannot create typed references through funceval. if (evalType == DB_IPCE_FET_NEW_OBJECT || evalType == DB_IPCE_FET_NEW_OBJECT_NC || evalType == DB_IPCE_FET_NORMAL) { COMPlusThrow(kArgumentException, W("Argument_CannotCreateTypedReference")); } } } // // Given a register, return the value. // static SIZE_T GetRegisterValue(DebuggerEval *pDE, CorDebugRegister reg, void *regAddr, SIZE_T regValue) { LIMITED_METHOD_CONTRACT; SIZE_T ret = 0; // Check whether the register address is the marker value for a register in a non-leaf frame. // This is related to the funceval breaking change. // if (regAddr == CORDB_ADDRESS_TO_PTR(kNonLeafFrameRegAddr)) { ret = regValue; } else { switch (reg) { case REGISTER_STACK_POINTER: ret = (SIZE_T)GetSP(&pDE->m_context); break; case REGISTER_FRAME_POINTER: ret = (SIZE_T)GetFP(&pDE->m_context); break; #if defined(TARGET_X86) case REGISTER_X86_EAX: ret = pDE->m_context.Eax; break; case REGISTER_X86_ECX: ret = pDE->m_context.Ecx; break; case REGISTER_X86_EDX: ret = pDE->m_context.Edx; break; case REGISTER_X86_EBX: ret = pDE->m_context.Ebx; break; case REGISTER_X86_ESI: ret = pDE->m_context.Esi; break; case REGISTER_X86_EDI: ret = pDE->m_context.Edi; break; #elif defined(TARGET_AMD64) case REGISTER_AMD64_RAX: ret = pDE->m_context.Rax; break; case REGISTER_AMD64_RCX: ret = pDE->m_context.Rcx; break; case REGISTER_AMD64_RDX: ret = pDE->m_context.Rdx; break; case REGISTER_AMD64_RBX: ret = pDE->m_context.Rbx; break; case REGISTER_AMD64_RSI: ret = pDE->m_context.Rsi; break; case REGISTER_AMD64_RDI: ret = pDE->m_context.Rdi; break; case REGISTER_AMD64_R8: ret = pDE->m_context.R8; break; case REGISTER_AMD64_R9: ret = pDE->m_context.R9; break; case REGISTER_AMD64_R10: ret = pDE->m_context.R10; break; case REGISTER_AMD64_R11: ret = pDE->m_context.R11; break; case REGISTER_AMD64_R12: ret = pDE->m_context.R12; break; case REGISTER_AMD64_R13: ret = pDE->m_context.R13; break; case REGISTER_AMD64_R14: ret = pDE->m_context.R14; break; case REGISTER_AMD64_R15: ret = pDE->m_context.R15; break; // fall through case REGISTER_AMD64_XMM0: case REGISTER_AMD64_XMM1: case REGISTER_AMD64_XMM2: case REGISTER_AMD64_XMM3: case REGISTER_AMD64_XMM4: case REGISTER_AMD64_XMM5: case REGISTER_AMD64_XMM6: case REGISTER_AMD64_XMM7: case REGISTER_AMD64_XMM8: case REGISTER_AMD64_XMM9: case REGISTER_AMD64_XMM10: case REGISTER_AMD64_XMM11: case REGISTER_AMD64_XMM12: case REGISTER_AMD64_XMM13: case REGISTER_AMD64_XMM14: case REGISTER_AMD64_XMM15: ret = FPSpillToR8(&(pDE->m_context.Xmm0) + (reg - REGISTER_AMD64_XMM0)); break; #elif defined(TARGET_ARM64) // fall through case REGISTER_ARM64_X0: case REGISTER_ARM64_X1: case REGISTER_ARM64_X2: case REGISTER_ARM64_X3: case REGISTER_ARM64_X4: case REGISTER_ARM64_X5: case REGISTER_ARM64_X6: case REGISTER_ARM64_X7: case REGISTER_ARM64_X8: case REGISTER_ARM64_X9: case REGISTER_ARM64_X10: case REGISTER_ARM64_X11: case REGISTER_ARM64_X12: case REGISTER_ARM64_X13: case REGISTER_ARM64_X14: case REGISTER_ARM64_X15: case REGISTER_ARM64_X16: case REGISTER_ARM64_X17: case REGISTER_ARM64_X18: case REGISTER_ARM64_X19: case REGISTER_ARM64_X20: case REGISTER_ARM64_X21: case REGISTER_ARM64_X22: case REGISTER_ARM64_X23: case REGISTER_ARM64_X24: case REGISTER_ARM64_X25: case REGISTER_ARM64_X26: case REGISTER_ARM64_X27: case REGISTER_ARM64_X28: ret = pDE->m_context.X[reg - REGISTER_ARM64_X0]; break; case REGISTER_ARM64_LR: ret = pDE->m_context.Lr; break; case REGISTER_ARM64_V0: case REGISTER_ARM64_V1: case REGISTER_ARM64_V2: case REGISTER_ARM64_V3: case REGISTER_ARM64_V4: case REGISTER_ARM64_V5: case REGISTER_ARM64_V6: case REGISTER_ARM64_V7: case REGISTER_ARM64_V8: case REGISTER_ARM64_V9: case REGISTER_ARM64_V10: case REGISTER_ARM64_V11: case REGISTER_ARM64_V12: case REGISTER_ARM64_V13: case REGISTER_ARM64_V14: case REGISTER_ARM64_V15: case REGISTER_ARM64_V16: case REGISTER_ARM64_V17: case REGISTER_ARM64_V18: case REGISTER_ARM64_V19: case REGISTER_ARM64_V20: case REGISTER_ARM64_V21: case REGISTER_ARM64_V22: case REGISTER_ARM64_V23: case REGISTER_ARM64_V24: case REGISTER_ARM64_V25: case REGISTER_ARM64_V26: case REGISTER_ARM64_V27: case REGISTER_ARM64_V28: case REGISTER_ARM64_V29: case REGISTER_ARM64_V30: case REGISTER_ARM64_V31: ret = FPSpillToR8(&pDE->m_context.V[reg - REGISTER_ARM64_V0]); break; #endif // !TARGET_X86 && !TARGET_AMD64 && !TARGET_ARM64 default: _ASSERT(!"Invalid register number!"); } } return ret; } // // Given a register, set its value. // static void SetRegisterValue(DebuggerEval *pDE, CorDebugRegister reg, void *regAddr, SIZE_T newValue) { CONTRACTL { THROWS; } CONTRACTL_END; // Check whether the register address is the marker value for a register in a non-leaf frame. // If so, then we can't update the register. Throw an exception to communicate this error. if (regAddr == CORDB_ADDRESS_TO_PTR(kNonLeafFrameRegAddr)) { COMPlusThrowHR(CORDBG_E_FUNC_EVAL_CANNOT_UPDATE_REGISTER_IN_NONLEAF_FRAME); return; } else { switch (reg) { case REGISTER_STACK_POINTER: SetSP(&pDE->m_context, newValue); break; case REGISTER_FRAME_POINTER: SetFP(&pDE->m_context, newValue); break; #ifdef TARGET_X86 case REGISTER_X86_EAX: pDE->m_context.Eax = newValue; break; case REGISTER_X86_ECX: pDE->m_context.Ecx = newValue; break; case REGISTER_X86_EDX: pDE->m_context.Edx = newValue; break; case REGISTER_X86_EBX: pDE->m_context.Ebx = newValue; break; case REGISTER_X86_ESI: pDE->m_context.Esi = newValue; break; case REGISTER_X86_EDI: pDE->m_context.Edi = newValue; break; #elif defined(TARGET_AMD64) case REGISTER_AMD64_RAX: pDE->m_context.Rax = newValue; break; case REGISTER_AMD64_RCX: pDE->m_context.Rcx = newValue; break; case REGISTER_AMD64_RDX: pDE->m_context.Rdx = newValue; break; case REGISTER_AMD64_RBX: pDE->m_context.Rbx = newValue; break; case REGISTER_AMD64_RSI: pDE->m_context.Rsi = newValue; break; case REGISTER_AMD64_RDI: pDE->m_context.Rdi = newValue; break; case REGISTER_AMD64_R8: pDE->m_context.R8= newValue; break; case REGISTER_AMD64_R9: pDE->m_context.R9= newValue; break; case REGISTER_AMD64_R10: pDE->m_context.R10= newValue; break; case REGISTER_AMD64_R11: pDE->m_context.R11 = newValue; break; case REGISTER_AMD64_R12: pDE->m_context.R12 = newValue; break; case REGISTER_AMD64_R13: pDE->m_context.R13 = newValue; break; case REGISTER_AMD64_R14: pDE->m_context.R14 = newValue; break; case REGISTER_AMD64_R15: pDE->m_context.R15 = newValue; break; // fall through case REGISTER_AMD64_XMM0: case REGISTER_AMD64_XMM1: case REGISTER_AMD64_XMM2: case REGISTER_AMD64_XMM3: case REGISTER_AMD64_XMM4: case REGISTER_AMD64_XMM5: case REGISTER_AMD64_XMM6: case REGISTER_AMD64_XMM7: case REGISTER_AMD64_XMM8: case REGISTER_AMD64_XMM9: case REGISTER_AMD64_XMM10: case REGISTER_AMD64_XMM11: case REGISTER_AMD64_XMM12: case REGISTER_AMD64_XMM13: case REGISTER_AMD64_XMM14: case REGISTER_AMD64_XMM15: R8ToFPSpill(&(pDE->m_context.Xmm0) + (reg - REGISTER_AMD64_XMM0), newValue); break; #elif defined(TARGET_ARM64) // fall through case REGISTER_ARM64_X0: case REGISTER_ARM64_X1: case REGISTER_ARM64_X2: case REGISTER_ARM64_X3: case REGISTER_ARM64_X4: case REGISTER_ARM64_X5: case REGISTER_ARM64_X6: case REGISTER_ARM64_X7: case REGISTER_ARM64_X8: case REGISTER_ARM64_X9: case REGISTER_ARM64_X10: case REGISTER_ARM64_X11: case REGISTER_ARM64_X12: case REGISTER_ARM64_X13: case REGISTER_ARM64_X14: case REGISTER_ARM64_X15: case REGISTER_ARM64_X16: case REGISTER_ARM64_X17: case REGISTER_ARM64_X18: case REGISTER_ARM64_X19: case REGISTER_ARM64_X20: case REGISTER_ARM64_X21: case REGISTER_ARM64_X22: case REGISTER_ARM64_X23: case REGISTER_ARM64_X24: case REGISTER_ARM64_X25: case REGISTER_ARM64_X26: case REGISTER_ARM64_X27: case REGISTER_ARM64_X28: pDE->m_context.X[reg - REGISTER_ARM64_X0] = newValue; break; case REGISTER_ARM64_LR: pDE->m_context.Lr = newValue; break; case REGISTER_ARM64_V0: case REGISTER_ARM64_V1: case REGISTER_ARM64_V2: case REGISTER_ARM64_V3: case REGISTER_ARM64_V4: case REGISTER_ARM64_V5: case REGISTER_ARM64_V6: case REGISTER_ARM64_V7: case REGISTER_ARM64_V8: case REGISTER_ARM64_V9: case REGISTER_ARM64_V10: case REGISTER_ARM64_V11: case REGISTER_ARM64_V12: case REGISTER_ARM64_V13: case REGISTER_ARM64_V14: case REGISTER_ARM64_V15: case REGISTER_ARM64_V16: case REGISTER_ARM64_V17: case REGISTER_ARM64_V18: case REGISTER_ARM64_V19: case REGISTER_ARM64_V20: case REGISTER_ARM64_V21: case REGISTER_ARM64_V22: case REGISTER_ARM64_V23: case REGISTER_ARM64_V24: case REGISTER_ARM64_V25: case REGISTER_ARM64_V26: case REGISTER_ARM64_V27: case REGISTER_ARM64_V28: case REGISTER_ARM64_V29: case REGISTER_ARM64_V30: case REGISTER_ARM64_V31: R8ToFPSpill(&pDE->m_context.V[reg - REGISTER_ARM64_V0], newValue); break; #endif // !TARGET_X86 && !TARGET_AMD64 && !TARGET_ARM64 default: _ASSERT(!"Invalid register number!"); } } } /* * GetRegsiterValueAndReturnAddress * * This routine takes out a value from a register, or set of registers, into one of * the given buffers (depending on size), and returns a pointer to the filled in * buffer, or NULL on error. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * pFEAD - Information about this particular argument. * pInt64Buf - pointer to a buffer of type INT64 * pSizeTBuf - pointer to a buffer of native size type. * * Returns: * pointer to the filled in buffer, else NULL on error. * */ static PVOID GetRegisterValueAndReturnAddress(DebuggerEval *pDE, DebuggerIPCE_FuncEvalArgData *pFEAD, INT64 *pInt64Buf, SIZE_T *pSizeTBuf ) { LIMITED_METHOD_CONTRACT; PVOID pAddr; #if !defined(HOST_64BIT) pAddr = pInt64Buf; DWORD *pLow = (DWORD*)(pInt64Buf); DWORD *pHigh = pLow + 1; #endif // HOST_64BIT switch (pFEAD->argHome.kind) { #if !defined(HOST_64BIT) case RAK_REGREG: *pLow = GetRegisterValue(pDE, pFEAD->argHome.u.reg2, pFEAD->argHome.u.reg2Addr, pFEAD->argHome.u.reg2Value); *pHigh = GetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); break; case RAK_MEMREG: *pLow = GetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); *pHigh = *((DWORD*)CORDB_ADDRESS_TO_PTR(pFEAD->argHome.addr)); break; case RAK_REGMEM: *pLow = *((DWORD*)CORDB_ADDRESS_TO_PTR(pFEAD->argHome.addr)); *pHigh = GetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); break; #endif // HOST_64BIT case RAK_REG: // Simply grab the value out of the proper register. *pSizeTBuf = GetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); pAddr = pSizeTBuf; break; default: pAddr = NULL; break; } return pAddr; } //--------------------------------------------------------------------------------------- // // Clean up any temporary value class variables we have allocated for the funceval. // // Arguments: // pStackStructArray - array whose elements track the location and type of the temporary variables // void CleanUpTemporaryVariables(ValueClassInfo ** ppProtectedValueClasses) { while (*ppProtectedValueClasses != NULL) { ValueClassInfo * pValueClassInfo = *ppProtectedValueClasses; *ppProtectedValueClasses = pValueClassInfo->pNext; DeleteInteropSafe(reinterpret_cast<BYTE *>(pValueClassInfo)); } } #ifdef _DEBUG // // Create a parallel array that tracks that we have initialized information in // each array. // #define MAX_DATA_LOCATIONS_TRACKED 100 typedef DWORD DataLocation; #define DL_NonExistent 0x00 #define DL_ObjectRefArray 0x01 #define DL_MaybeInteriorPtrArray 0x02 #define DL_BufferForArgsArray 0x04 #define DL_All 0xFF #endif // _DEBUG /* * GetFuncEvalArgValue * * This routine is used to fill the pArgument array with the appropriate value. This function * uses the three parallel array entries given, and places the correct value, or reference to * the value in pArgument. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * pFEAD - Information about this particular argument. * isByRef - Is the argument being passed ByRef. * fNeedBoxOrUnbox - Did the argument need boxing or unboxing. * argTH - The type handle for the argument. * byrefArgSigType - The signature type of a parameter that isByRef == true. * pArgument - Location to place the reference or value. * pMaybeInteriorPtrArg - A pointer that contains a value that may be pointers to * the interior of a managed object. * pObjectRefArg - A pointer that contains an object ref. It was built previously. * pBufferArg - A pointer for holding stuff that did not need to be protected. * * Returns: * None. * */ static void GetFuncEvalArgValue(DebuggerEval *pDE, DebuggerIPCE_FuncEvalArgData *pFEAD, bool isByRef, bool fNeedBoxOrUnbox, TypeHandle argTH, CorElementType byrefArgSigType, TypeHandle byrefArgTH, ARG_SLOT *pArgument, void *pMaybeInteriorPtrArg, OBJECTREF *pObjectRefArg, INT64 *pBufferArg, ValueClassInfo ** ppProtectedValueClasses, CorElementType argSigType DEBUG_ARG(DataLocation dataLocation) ) { CONTRACTL { THROWS; GC_NOTRIGGER; } CONTRACTL_END; _ASSERTE((dataLocation != DL_NonExistent) || (pFEAD->argElementType == ELEMENT_TYPE_VALUETYPE)); switch (pFEAD->argElementType) { case ELEMENT_TYPE_I8: case ELEMENT_TYPE_U8: case ELEMENT_TYPE_R8: { INT64 *pSource; #if defined(HOST_64BIT) _ASSERTE(dataLocation & DL_MaybeInteriorPtrArray); pSource = (INT64 *)pMaybeInteriorPtrArg; #else // !HOST_64BIT _ASSERTE(dataLocation & DL_BufferForArgsArray); pSource = pBufferArg; #endif // !HOST_64BIT if (!isByRef) { *((INT64*)pArgument) = *pSource; } else { *pArgument = PtrToArgSlot(pSource); } } break; case ELEMENT_TYPE_VALUETYPE: { SIZE_T v = 0; LPVOID pAddr = NULL; INT64 bigVal = 0; if (pFEAD->argAddr != NULL) { pAddr = *((void **)pMaybeInteriorPtrArg); } else { pAddr = GetRegisterValueAndReturnAddress(pDE, pFEAD, &bigVal, &v); if (pAddr == NULL) { COMPlusThrow(kArgumentNullException); } } _ASSERTE(pAddr); if (!fNeedBoxOrUnbox && !isByRef) { _ASSERTE(argTH.GetMethodTable()); unsigned size = argTH.GetMethodTable()->GetNumInstanceFieldBytes(); if (size <= sizeof(ARG_SLOT) #if defined(TARGET_AMD64) // On AMD64 we pass value types of size which are not powers of 2 by ref. && ((size & (size-1)) == 0) #endif // TARGET_AMD64 ) { memcpyNoGCRefs(ArgSlotEndianessFixup(pArgument, sizeof(LPVOID)), pAddr, size); } else { _ASSERTE(pFEAD->argAddr != NULL); #if defined(ENREGISTERED_PARAMTYPE_MAXSIZE) if (ArgIterator::IsArgPassedByRef(argTH)) { // On X64, by-value value class arguments which are bigger than 8 bytes are passed by reference // according to the native calling convention. The same goes for value class arguments whose size // is smaller than 8 bytes but not a power of 2. To avoid side effets, we need to allocate a // temporary variable and pass that by reference instead. On ARM64, by-value value class // arguments which are bigger than 16 bytes are passed by reference. _ASSERTE(ppProtectedValueClasses != NULL); BYTE * pTemp = new (interopsafe) BYTE[ALIGN_UP(sizeof(ValueClassInfo), 8) + size]; ValueClassInfo * pValueClassInfo = (ValueClassInfo *)pTemp; LPVOID pData = pTemp + ALIGN_UP(sizeof(ValueClassInfo), 8); memcpyNoGCRefs(pData, pAddr, size); *pArgument = PtrToArgSlot(pData); pValueClassInfo->pData = pData; pValueClassInfo->pMT = argTH.GetMethodTable(); pValueClassInfo->pNext = *ppProtectedValueClasses; *ppProtectedValueClasses = pValueClassInfo; } else #endif // ENREGISTERED_PARAMTYPE_MAXSIZE *pArgument = PtrToArgSlot(pAddr); } } else { if (fNeedBoxOrUnbox) { *pArgument = ObjToArgSlot(*pObjectRefArg); } else { if (pFEAD->argAddr) { *pArgument = PtrToArgSlot(pAddr); } else { // The argument is the address of where we're holding the primitive in the PrimitiveArg array. We // stick the real value from the register into the PrimitiveArg array. It should be in a single // register since it is pointer-sized. _ASSERTE( pFEAD->argHome.kind == RAK_REG ); *pArgument = PtrToArgSlot(pBufferArg); *pBufferArg = (INT64)v; } } } } break; default: // literal values smaller than 8 bytes and "special types" (e.g. object, string, etc.) { INT64 *pSource; INDEBUG(DataLocation expectedLocation); #ifdef TARGET_X86 if ((pFEAD->argElementType == ELEMENT_TYPE_I4) || (pFEAD->argElementType == ELEMENT_TYPE_U4) || (pFEAD->argElementType == ELEMENT_TYPE_R4)) { INDEBUG(expectedLocation = DL_MaybeInteriorPtrArray); pSource = (INT64 *)pMaybeInteriorPtrArg; } else #endif if (IsElementTypeSpecial(pFEAD->argElementType)) { INDEBUG(expectedLocation = DL_ObjectRefArray); pSource = (INT64 *)pObjectRefArg; } else { INDEBUG(expectedLocation = DL_BufferForArgsArray); pSource = pBufferArg; } if (pFEAD->argAddr != NULL) { if (!isByRef) { if (pFEAD->argIsHandleValue) { _ASSERTE(dataLocation & DL_BufferForArgsArray); OBJECTHANDLE oh = *((OBJECTHANDLE*)(pBufferArg)); // Always comes from buffer *pArgument = PtrToArgSlot(g_pEEInterface->GetObjectFromHandle(oh)); } else { _ASSERTE(dataLocation & expectedLocation); if (pSource != NULL) { *pArgument = *pSource; // may come from either array. } else { *pArgument = NULL; } } } else { if (pFEAD->argIsHandleValue) { _ASSERTE(dataLocation & DL_BufferForArgsArray); *pArgument = *pBufferArg; // Buffer contains the object handle, in this case, so // just copy that across. } else { _ASSERTE(dataLocation & expectedLocation); *pArgument = PtrToArgSlot(pSource); // Load the argument with the address of our buffer. } } } else if (pFEAD->argIsLiteral) { _ASSERTE(dataLocation & expectedLocation); if (!isByRef) { if (pSource != NULL) { *pArgument = *pSource; // may come from either array. } else { *pArgument = NULL; } } else { *pArgument = PtrToArgSlot(pSource); // Load the argument with the address of our buffer. } } else { if (!isByRef) { if (pSource != NULL) { *pArgument = *pSource; // may come from either array. } else { *pArgument = NULL; } } else { *pArgument = PtrToArgSlot(pSource); // Load the argument with the address of our buffer. } } // If we need to unbox, then unbox the arg now. if (fNeedBoxOrUnbox) { if (!isByRef) { // function expects valuetype, argument received is class or object // Take the ObjectRef off the stack. ARG_SLOT oi1 = *pArgument; OBJECTREF o1 = ArgSlotToObj(oi1); // For Nullable types, we need a 'true' nullable to pass to the function, and we do this // by passing a boxed nullable that we unbox. We allocated this space earlier however we // did not know the data location until just now. Fill it in with the data and use that // to pass to the function. if (Nullable::IsNullableType(argTH)) { _ASSERTE(*pObjectRefArg != 0); _ASSERTE((*pObjectRefArg)->GetMethodTable() == argTH.GetMethodTable()); if (o1 != *pObjectRefArg) { Nullable::UnBoxNoCheck((*pObjectRefArg)->GetData(), o1, (*pObjectRefArg)->GetMethodTable()); o1 = *pObjectRefArg; } } if (o1 == NULL) { COMPlusThrow(kArgumentNullException); } if (!o1->GetMethodTable()->IsValueType()) { COMPlusThrow(kArgumentException, W("Argument_BadObjRef")); } // Unbox the little fella to get a pointer to the raw data. void *pData = o1->GetData(); // Get its size to make sure it fits in an ARG_SLOT unsigned size = o1->GetMethodTable()->GetNumInstanceFieldBytes(); if (size <= sizeof(ARG_SLOT)) { // Its not ByRef, so we need to copy the value class onto the ARG_SLOT. CopyValueClass(ArgSlotEndianessFixup(pArgument, sizeof(LPVOID)), pData, o1->GetMethodTable()); } else { // Store pointer to the space in the ARG_SLOT *pArgument = PtrToArgSlot(pData); } } else { // Function expects byref valuetype, argument received is byref class. // Grab the ObjectRef off the stack via the pointer on the stack. Note: the stack has a pointer to the // ObjectRef since the arg was specified as byref. OBJECTREF* op1 = (OBJECTREF*)ArgSlotToPtr(*pArgument); if (op1 == NULL) { COMPlusThrow(kArgumentNullException); } OBJECTREF o1 = *op1; // For Nullable types, we need a 'true' nullable to pass to the function, and we do this // by passing a boxed nullable that we unbox. We allocated this space earlier however we // did not know the data location until just now. Fill it in with the data and use that // to pass to the function. if (Nullable::IsNullableType(byrefArgTH)) { _ASSERTE(*pObjectRefArg != 0 && (*pObjectRefArg)->GetMethodTable() == byrefArgTH.GetMethodTable()); if (o1 != *pObjectRefArg) { Nullable::UnBoxNoCheck((*pObjectRefArg)->GetData(), o1, (*pObjectRefArg)->GetMethodTable()); o1 = *pObjectRefArg; } } if (o1 == NULL) { COMPlusThrow(kArgumentNullException); } _ASSERTE(o1->GetMethodTable()->IsValueType()); // Unbox the little fella to get a pointer to the raw data. void *pData = o1->GetData(); // If it is ByRef, then we just replace the ObjectRef with a pointer to the data. *pArgument = PtrToArgSlot(pData); } } // Validate any objectrefs that are supposed to be on the stack. // <TODO>@TODO: Move this to before the boxing/unboxing above</TODO> if (!fNeedBoxOrUnbox) { Object *objPtr; if (!isByRef) { if (IsElementTypeSpecial(argSigType)) { // validate the integrity of the object objPtr = (Object*)ArgSlotToPtr(*pArgument); if (FAILED(ValidateObject(objPtr))) { COMPlusThrow(kArgumentException, W("Argument_BadObjRef")); } } } else { _ASSERTE(argSigType == ELEMENT_TYPE_BYREF); if (IsElementTypeSpecial(byrefArgSigType)) { objPtr = *(Object**)(ArgSlotToPtr(*pArgument)); if (FAILED(ValidateObject(objPtr))) { COMPlusThrow(kArgumentException, W("Argument_BadObjRef")); } } } } } } } static CorDebugRegister GetArgAddrFromReg( DebuggerIPCE_FuncEvalArgData *pFEAD) { CorDebugRegister retval = REGISTER_INSTRUCTION_POINTER; // good as default as any #if defined(HOST_64BIT) retval = (pFEAD->argHome.kind == RAK_REG ? pFEAD->argHome.reg1 : (CorDebugRegister)((int)REGISTER_IA64_F0 + pFEAD->argHome.floatIndex)); #else // !HOST_64BIT retval = pFEAD->argHome.reg1; #endif // !HOST_64BIT return retval; } // // Given info about a byref argument, retrieve the current value from the pBufferForArgsArray, // the pMaybeInteriorPtrArray, the pByRefMaybeInteriorPtrArray, or the pObjectRefArray. Then // place it back into the proper register or address. // // Note that we should never use the argAddr of the DebuggerIPCE_FuncEvalArgData in this function // since the address may be an interior GC pointer and may have been moved by the GC. Instead, // use the pByRefMaybeInteriorPtrArray. // static void SetFuncEvalByRefArgValue(DebuggerEval *pDE, DebuggerIPCE_FuncEvalArgData *pFEAD, CorElementType byrefArgSigType, INT64 bufferByRefArg, void *maybeInteriorPtrArg, void *byRefMaybeInteriorPtrArg, OBJECTREF objectRefByRefArg) { WRAPPER_NO_CONTRACT; switch (pFEAD->argElementType) { case ELEMENT_TYPE_I8: case ELEMENT_TYPE_U8: case ELEMENT_TYPE_R8: // 64bit values { INT64 source; #if defined(HOST_64BIT) source = (INT64)maybeInteriorPtrArg; #else // !HOST_64BIT source = bufferByRefArg; #endif // !HOST_64BIT if (pFEAD->argIsLiteral) { // If this was a literal arg, then copy the updated primitive back into the literal. memcpy(pFEAD->argLiteralData, &source, sizeof(pFEAD->argLiteralData)); } else if (pFEAD->argAddr != NULL) { *((INT64 *)byRefMaybeInteriorPtrArg) = source; return; } else { #if !defined(HOST_64BIT) // RAK_REG is the only 4 byte type, all others are 8 byte types. _ASSERTE(pFEAD->argHome.kind != RAK_REG); SIZE_T *pLow = (SIZE_T*)(&source); SIZE_T *pHigh = pLow + 1; switch (pFEAD->argHome.kind) { case RAK_REGREG: SetRegisterValue(pDE, pFEAD->argHome.u.reg2, pFEAD->argHome.u.reg2Addr, *pLow); SetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, *pHigh); break; case RAK_MEMREG: SetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, *pLow); *((SIZE_T*)CORDB_ADDRESS_TO_PTR(pFEAD->argHome.addr)) = *pHigh; break; case RAK_REGMEM: *((SIZE_T*)CORDB_ADDRESS_TO_PTR(pFEAD->argHome.addr)) = *pLow; SetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, *pHigh); break; default: break; } #else // HOST_64BIT // The only types we use are RAK_REG and RAK_FLOAT, and both of them can be 4 or 8 bytes. _ASSERTE((pFEAD->argHome.kind == RAK_REG) || (pFEAD->argHome.kind == RAK_FLOAT)); SetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, source); #endif // HOST_64BIT } } break; default: // literal values smaller than 8 bytes and "special types" (e.g. object, array, string, etc.) { SIZE_T source; #ifdef TARGET_X86 if ((pFEAD->argElementType == ELEMENT_TYPE_I4) || (pFEAD->argElementType == ELEMENT_TYPE_U4) || (pFEAD->argElementType == ELEMENT_TYPE_R4)) { source = (SIZE_T)maybeInteriorPtrArg; } else { #endif source = (SIZE_T)bufferByRefArg; #ifdef TARGET_X86 } #endif if (pFEAD->argIsLiteral) { // If this was a literal arg, then copy the updated primitive back into the literal. // The literall buffer is a fixed size (8 bytes), but our source may be 4 or 8 bytes // depending on the platform. To prevent reading past the end of the source, we // zero the destination buffer and copy only as many bytes as available. memset( pFEAD->argLiteralData, 0, sizeof(pFEAD->argLiteralData) ); if (IsElementTypeSpecial(pFEAD->argElementType)) { _ASSERTE( sizeof(pFEAD->argLiteralData) >= sizeof(objectRefByRefArg) ); memcpy(pFEAD->argLiteralData, &objectRefByRefArg, sizeof(objectRefByRefArg)); } else { _ASSERTE( sizeof(pFEAD->argLiteralData) >= sizeof(source) ); memcpy(pFEAD->argLiteralData, &source, sizeof(source)); } } else if (pFEAD->argAddr == NULL) { // If the 32bit value is enregistered, copy it back to the proper regs. // RAK_REG is the only valid 4 byte type on WIN32. On WIN64, both RAK_REG and RAK_FLOAT can be // 4 bytes or 8 bytes. _ASSERTE((pFEAD->argHome.kind == RAK_REG) BIT64_ONLY(|| (pFEAD->argHome.kind == RAK_FLOAT))); CorDebugRegister regNum = GetArgAddrFromReg(pFEAD); // Shove the result back into the proper register. if (IsElementTypeSpecial(pFEAD->argElementType)) { SetRegisterValue(pDE, regNum, pFEAD->argHome.reg1Addr, (SIZE_T)ObjToArgSlot(objectRefByRefArg)); } else { SetRegisterValue(pDE, regNum, pFEAD->argHome.reg1Addr, (SIZE_T)source); } } else { // If the result was an object by ref, then copy back the new location of the object (in GC case). if (pFEAD->argIsHandleValue) { // do nothing. The Handle was passed in the pArgument array directly } else if (IsElementTypeSpecial(pFEAD->argElementType)) { *((SIZE_T*)byRefMaybeInteriorPtrArg) = (SIZE_T)ObjToArgSlot(objectRefByRefArg); } else if (pFEAD->argElementType == ELEMENT_TYPE_VALUETYPE) { // Do nothing, we passed in the pointer to the valuetype in the pArgument array directly. } else { GetAndSetLiteralValue(byRefMaybeInteriorPtrArg, pFEAD->argElementType, &source, ELEMENT_TYPE_PTR); } } } // end default } // end switch } /* * GCProtectAllPassedArgs * * This routine is the first step in doing a func-eval. For a complete overview, see * the comments at the top of this file. * * This routine over-aggressively protects all arguments that may be references to * managed objects. This function cannot crawl the function signature, since doing * so may trigger a GC, and thus, we must assume everything is ByRef. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * pObjectRefArray - An array that contains any object refs. It was built previously. * pMaybeInteriorPtrArray - An array that contains values that may be pointers to * the interior of a managed object. * pBufferForArgsArray - An array for holding stuff that does not need to be protected. * Any handle for the 'this' pointer is put in here for pulling it out later. * * Returns: * None. * */ static void GCProtectAllPassedArgs(DebuggerEval *pDE, OBJECTREF *pObjectRefArray, void **pMaybeInteriorPtrArray, void **pByRefMaybeInteriorPtrArray, INT64 *pBufferForArgsArray DEBUG_ARG(DataLocation pDataLocationArray[]) ) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; DebuggerIPCE_FuncEvalArgData *argData = pDE->GetArgData(); unsigned currArgIndex = 0; // // Gather all the information for the parameters. // for ( ; currArgIndex < pDE->m_argCount; currArgIndex++) { DebuggerIPCE_FuncEvalArgData *pFEAD = &argData[currArgIndex]; // In case any of the arguments is a by ref argument and points into the GC heap, // we need to GC protect their addresses as well. if (pFEAD->argAddr != NULL) { pByRefMaybeInteriorPtrArray[currArgIndex] = pFEAD->argAddr; } switch (pFEAD->argElementType) { case ELEMENT_TYPE_I8: case ELEMENT_TYPE_U8: case ELEMENT_TYPE_R8: // 64bit values #if defined(HOST_64BIT) // // Only need to worry about protecting if a pointer is a 64 bit quantity. // _ASSERTE(sizeof(void *) == sizeof(INT64)); if (pFEAD->argAddr != NULL) { pMaybeInteriorPtrArray[currArgIndex] = *((void **)(pFEAD->argAddr)); #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_MaybeInteriorPtrArray; } #endif } else if (pFEAD->argIsLiteral) { _ASSERTE(sizeof(pFEAD->argLiteralData) >= sizeof(void *)); // // If this is a byref literal arg, then it maybe an interior ptr. // void *v = NULL; memcpy(&v, pFEAD->argLiteralData, sizeof(v)); pMaybeInteriorPtrArray[currArgIndex] = v; #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_MaybeInteriorPtrArray; } #endif } else { _ASSERTE((pFEAD->argHome.kind == RAK_REG) || (pFEAD->argHome.kind == RAK_FLOAT)); CorDebugRegister regNum = GetArgAddrFromReg(pFEAD); SIZE_T v = GetRegisterValue(pDE, regNum, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); pMaybeInteriorPtrArray[currArgIndex] = (void *)(v); #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_MaybeInteriorPtrArray; } #endif } #endif // HOST_64BIT break; case ELEMENT_TYPE_VALUETYPE: // // If the value type address could be an interior pointer. // if (pFEAD->argAddr != NULL) { pMaybeInteriorPtrArray[currArgIndex] = ((void **)(pFEAD->argAddr)); } INDEBUG(pDataLocationArray[currArgIndex] |= DL_MaybeInteriorPtrArray); break; case ELEMENT_TYPE_CLASS: case ELEMENT_TYPE_OBJECT: case ELEMENT_TYPE_STRING: case ELEMENT_TYPE_ARRAY: case ELEMENT_TYPE_SZARRAY: if (pFEAD->argAddr != NULL) { if (pFEAD->argIsHandleValue) { OBJECTHANDLE oh = (OBJECTHANDLE)(pFEAD->argAddr); pBufferForArgsArray[currArgIndex] = (INT64)(size_t)oh; INDEBUG(pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray); } else { pObjectRefArray[currArgIndex] = *((OBJECTREF *)(pFEAD->argAddr)); INDEBUG(pDataLocationArray[currArgIndex] |= DL_ObjectRefArray); } } else if (pFEAD->argIsLiteral) { _ASSERTE(sizeof(pFEAD->argLiteralData) >= sizeof(OBJECTREF)); OBJECTREF v = NULL; memcpy(&v, pFEAD->argLiteralData, sizeof(v)); pObjectRefArray[currArgIndex] = v; #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_ObjectRefArray; } #endif } else { // RAK_REG is the only valid pointer-sized type. _ASSERTE(pFEAD->argHome.kind == RAK_REG); // Simply grab the value out of the proper register. SIZE_T v = GetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); // The argument is the address. pObjectRefArray[currArgIndex] = (OBJECTREF)v; #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_ObjectRefArray; } #endif } break; case ELEMENT_TYPE_I4: case ELEMENT_TYPE_U4: case ELEMENT_TYPE_R4: // 32bit values #ifdef TARGET_X86 _ASSERTE(sizeof(void *) == sizeof(INT32)); if (pFEAD->argAddr != NULL) { if (pFEAD->argIsHandleValue) { // // Ignorable - no need to protect // } else { pMaybeInteriorPtrArray[currArgIndex] = *((void **)(pFEAD->argAddr)); #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_MaybeInteriorPtrArray; } #endif } } else if (pFEAD->argIsLiteral) { _ASSERTE(sizeof(pFEAD->argLiteralData) >= sizeof(INT32)); // // If this is a byref literal arg, then it maybe an interior ptr. // void *v = NULL; memcpy(&v, pFEAD->argLiteralData, sizeof(v)); pMaybeInteriorPtrArray[currArgIndex] = v; #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_MaybeInteriorPtrArray; } #endif } else { // RAK_REG is the only valid 4 byte type on WIN32. _ASSERTE(pFEAD->argHome.kind == RAK_REG); // Simply grab the value out of the proper register. SIZE_T v = GetRegisterValue(pDE, pFEAD->argHome.reg1, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); // The argument is the address. pMaybeInteriorPtrArray[currArgIndex] = (void *)v; #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_MaybeInteriorPtrArray; } #endif } #endif // TARGET_X86 FALLTHROUGH; default: // // Ignorable - no need to protect // break; } } } /* * ResolveFuncEvalGenericArgInfo * * This function pulls out any generic args and makes sure the method is loaded for it. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * * Returns: * None. * */ void ResolveFuncEvalGenericArgInfo(DebuggerEval *pDE) { CONTRACTL { THROWS; GC_TRIGGERS; } CONTRACTL_END; DebuggerIPCE_TypeArgData *firstdata = pDE->GetTypeArgData(); unsigned int nGenericArgs = pDE->m_genericArgsCount; SIZE_T cbAllocSize; if ((!ClrSafeInt<SIZE_T>::multiply(nGenericArgs, sizeof(TypeHandle *), cbAllocSize)) || (cbAllocSize != (size_t)(cbAllocSize))) { ThrowHR(COR_E_OVERFLOW); } TypeHandle * pGenericArgs = (nGenericArgs == 0) ? NULL : (TypeHandle *) _alloca(cbAllocSize); // // Snag the type arguments from the input and get the // method desc that corresponds to the instantiated desc. // Debugger::TypeDataWalk walk(firstdata, pDE->m_genericArgsNodeCount); walk.ReadTypeHandles(nGenericArgs, pGenericArgs); // <TODO>better error message</TODO> if (!walk.Finished()) { COMPlusThrow(kArgumentException, W("Argument_InvalidGenericArg")); } // Find the proper MethodDesc that we need to call. // Since we're already in the target domain, it can't be unloaded so it's safe to // use domain specific structures like the Module*. _ASSERTE( GetAppDomain() == pDE->m_debuggerModule->GetAppDomain() ); pDE->m_md = g_pEEInterface->LoadMethodDef(pDE->m_debuggerModule->GetRuntimeModule(), pDE->m_methodToken, nGenericArgs, pGenericArgs, &(pDE->m_ownerTypeHandle)); // We better have a MethodDesc at this point. _ASSERTE(pDE->m_md != NULL); ValidateFuncEvalReturnType(pDE->m_evalType , pDE->m_md->GetMethodTable()); // If this is a new object operation, then we should have a .ctor. if ((pDE->m_evalType == DB_IPCE_FET_NEW_OBJECT) && !pDE->m_md->IsCtor()) { COMPlusThrow(kArgumentException, W("Argument_MissingDefaultConstructor")); } pDE->m_md->EnsureActive(); // Run the Class Init for this class, if necessary. MethodTable * pOwningMT = pDE->m_ownerTypeHandle.GetMethodTable(); pOwningMT->EnsureInstanceActive(); pOwningMT->CheckRunClassInitThrowing(); if (pDE->m_evalType == DB_IPCE_FET_NEW_OBJECT) { // Work out the exact type of the allocated object pDE->m_resultType = (nGenericArgs == 0) ? TypeHandle(pDE->m_md->GetMethodTable()) : g_pEEInterface->LoadInstantiation(pDE->m_md->GetModule(), pDE->m_md->GetMethodTable()->GetCl(), nGenericArgs, pGenericArgs); } } /* * BoxFuncEvalThisParameter * * This function is a helper for DoNormalFuncEval. It boxes the 'this' parameter if necessary. * For example, when a method Object.ToString is called on a value class like System.DateTime * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * argData - Array of information about the arguments. * pMaybeInteriorPtrArray - An array that contains values that may be pointers to * the interior of a managed object. * pObjectRef - A GC protected place to put a boxed value, if necessary. * * Returns: * None * */ void BoxFuncEvalThisParameter(DebuggerEval *pDE, DebuggerIPCE_FuncEvalArgData *argData, void **pMaybeInteriorPtrArray, OBJECTREF *pObjectRefArg // out DEBUG_ARG(DataLocation pDataLocationArray[]) ) { WRAPPER_NO_CONTRACT; // // See if we have a value type that is going to be passed as a 'this' pointer. // if ((pDE->m_evalType != DB_IPCE_FET_NEW_OBJECT) && !pDE->m_md->IsStatic() && (pDE->m_argCount > 0)) { // Allocate the space for box nullables. Nullable parameters need a unboxed // nullable value to point at, where our current representation does not have // an unboxed value inside them. Thus we need another buffer to hold it (and // gcprotects it. We used boxed values for this by converting them to 'true' // nullable form, calling the function, and in the case of byrefs, converting // them back afterward. MethodTable* pMT = pDE->m_md->GetMethodTable(); if (Nullable::IsNullableType(pMT)) { OBJECTREF obj = AllocateObject(pMT); if (*pObjectRefArg != NULL) { BOOL typesMatch = Nullable::UnBox(obj->GetData(), *pObjectRefArg, pMT); (void)typesMatch; //prevent "unused variable" error from GCC _ASSERTE(typesMatch); } *pObjectRefArg = obj; } if (argData[0].argElementType == ELEMENT_TYPE_VALUETYPE) { // // See if we need to box up the 'this' parameter. // if (!pDE->m_md->GetMethodTable()->IsValueType()) { DebuggerIPCE_FuncEvalArgData *pFEAD = &argData[0]; SIZE_T v; LPVOID pAddr = NULL; INT64 bigVal; { GCX_FORBID(); //pAddr is unprotected from the time we initialize it if (pFEAD->argAddr != NULL) { _ASSERTE(pDataLocationArray[0] & DL_MaybeInteriorPtrArray); pAddr = pMaybeInteriorPtrArray[0]; INDEBUG(pDataLocationArray[0] &= ~DL_MaybeInteriorPtrArray); } else { pAddr = GetRegisterValueAndReturnAddress(pDE, pFEAD, &bigVal, &v); if (pAddr == NULL) { COMPlusThrow(kArgumentNullException); } } _ASSERTE(pAddr != NULL); } //GCX_FORBID GCPROTECT_BEGININTERIOR(pAddr); //ReadTypeHandle may trigger a GC and move the object that has the value type at pAddr as a field // // Grab the class of this value type. If the type is a parameterized // struct type then it may not have yet been loaded by the EE (generics // code sharing may have meant we have never bothered to create the exact // type yet). // // A buffer should have been allocated for the full struct type _ASSERTE(argData[0].fullArgType != NULL); Debugger::TypeDataWalk walk((DebuggerIPCE_TypeArgData *) argData[0].fullArgType, argData[0].fullArgTypeNodeCount); TypeHandle typeHandle = walk.ReadTypeHandle(); if (typeHandle.IsNull()) { COMPlusThrow(kArgumentException, W("Argument_BadObjRef")); } // // Box up this value type // *pObjectRefArg = typeHandle.GetMethodTable()->Box(pAddr); if (Nullable::IsNullableType(typeHandle.GetMethodTable()) && (*pObjectRefArg == NULL)) { COMPlusThrow(kArgumentNullException); } GCPROTECT_END(); INDEBUG(pDataLocationArray[0] |= DL_ObjectRefArray); } } } } // // This is used to store (temporarily) information about the arguments that func-eval // will pass. It is used only for the args of the function, not the return buffer nor // the 'this' pointer, if there is any of either. // struct FuncEvalArgInfo { CorElementType argSigType; CorElementType byrefArgSigType; TypeHandle byrefArgTypeHandle; bool fNeedBoxOrUnbox; TypeHandle sigTypeHandle; }; /* * GatherFuncEvalArgInfo * * This function is a helper for DoNormalFuncEval. It gathers together all the information * necessary to process the arguments. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * mSig - The metadata signature of the fuction to call. * argData - Array of information about the arguments. * pFEArgInfo - An array of structs to hold the argument information. * * Returns: * None. * */ void GatherFuncEvalArgInfo(DebuggerEval *pDE, MetaSig mSig, DebuggerIPCE_FuncEvalArgData *argData, FuncEvalArgInfo *pFEArgInfo // out ) { WRAPPER_NO_CONTRACT; unsigned currArgIndex = 0; if ((pDE->m_evalType == DB_IPCE_FET_NORMAL) && !pDE->m_md->IsStatic()) { // // Skip over the 'this' arg, since this function is not supposed to mess with it. // currArgIndex++; } // // Gather all the information for the parameters. // for ( ; currArgIndex < pDE->m_argCount; currArgIndex++) { DebuggerIPCE_FuncEvalArgData *pFEAD = &argData[currArgIndex]; // // Move to the next arg in the signature. // CorElementType argSigType = mSig.NextArgNormalized(); _ASSERTE(argSigType != ELEMENT_TYPE_END); // // If this arg is a byref arg, then we'll need to know what type we're referencing for later... // TypeHandle byrefTypeHandle = TypeHandle(); CorElementType byrefArgSigType = ELEMENT_TYPE_END; if (argSigType == ELEMENT_TYPE_BYREF) { byrefArgSigType = mSig.GetByRefType(&byrefTypeHandle); } // // If the sig says class but we've got a value class parameter, then remember that we need to box it. If // the sig says value class, but we've got a boxed value class, then remember that we need to unbox it. // bool fNeedBoxOrUnbox = ((argSigType == ELEMENT_TYPE_CLASS) && (pFEAD->argElementType == ELEMENT_TYPE_VALUETYPE)) || (((argSigType == ELEMENT_TYPE_VALUETYPE) && ((pFEAD->argElementType == ELEMENT_TYPE_CLASS) || (pFEAD->argElementType == ELEMENT_TYPE_OBJECT))) || // This is when method signature is expecting a BYREF ValueType, yet we receive the boxed valuetype's handle. (pFEAD->argElementType == ELEMENT_TYPE_CLASS && argSigType == ELEMENT_TYPE_BYREF && byrefArgSigType == ELEMENT_TYPE_VALUETYPE)); pFEArgInfo[currArgIndex].argSigType = argSigType; pFEArgInfo[currArgIndex].byrefArgSigType = byrefArgSigType; pFEArgInfo[currArgIndex].byrefArgTypeHandle = byrefTypeHandle; pFEArgInfo[currArgIndex].fNeedBoxOrUnbox = fNeedBoxOrUnbox; pFEArgInfo[currArgIndex].sigTypeHandle = mSig.GetLastTypeHandleThrowing(); } } /* * BoxFuncEvalArguments * * This function is a helper for DoNormalFuncEval. It boxes all the arguments that * need to be. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * argData - Array of information about the arguments. * pFEArgInfo - An array of structs to hold the argument information. * pMaybeInteriorPtrArray - An array that contains values that may be pointers to * the interior of a managed object. * pObjectRef - A GC protected place to put a boxed value, if necessary. * * Returns: * None * */ void BoxFuncEvalArguments(DebuggerEval *pDE, DebuggerIPCE_FuncEvalArgData *argData, FuncEvalArgInfo *pFEArgInfo, void **pMaybeInteriorPtrArray, OBJECTREF *pObjectRef // out DEBUG_ARG(DataLocation pDataLocationArray[]) ) { WRAPPER_NO_CONTRACT; unsigned currArgIndex = 0; if ((pDE->m_evalType == DB_IPCE_FET_NORMAL) && !pDE->m_md->IsStatic()) { // // Skip over the 'this' arg, since this function is not supposed to mess with it. // currArgIndex++; } // // Gather all the information for the parameters. // for ( ; currArgIndex < pDE->m_argCount; currArgIndex++) { DebuggerIPCE_FuncEvalArgData *pFEAD = &argData[currArgIndex]; // Allocate the space for box nullables. Nullable parameters need a unboxed // nullable value to point at, where our current representation does not have // an unboxed value inside them. Thus we need another buffer to hold it (and // gcprotects it. We used boxed values for this by converting them to 'true' // nullable form, calling the function, and in the case of byrefs, converting // them back afterward. TypeHandle th = pFEArgInfo[currArgIndex].sigTypeHandle; if (pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_BYREF) th = pFEArgInfo[currArgIndex].byrefArgTypeHandle; if (!th.IsNull() && Nullable::IsNullableType(th)) { OBJECTREF obj = AllocateObject(th.AsMethodTable()); if (pObjectRef[currArgIndex] != NULL) { BOOL typesMatch = Nullable::UnBox(obj->GetData(), pObjectRef[currArgIndex], th.AsMethodTable()); (void)typesMatch; //prevent "unused variable" error from GCC _ASSERTE(typesMatch); } pObjectRef[currArgIndex] = obj; } // // Check if we should box this value now // if ((pFEAD->argElementType == ELEMENT_TYPE_VALUETYPE) && (pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_BYREF) && pFEArgInfo[currArgIndex].fNeedBoxOrUnbox) { SIZE_T v; INT64 bigVal; LPVOID pAddr = NULL; if (pFEAD->argAddr != NULL) { _ASSERTE(pDataLocationArray[currArgIndex] & DL_MaybeInteriorPtrArray); pAddr = pMaybeInteriorPtrArray[currArgIndex]; INDEBUG(pDataLocationArray[currArgIndex] &= ~DL_MaybeInteriorPtrArray); } else { pAddr = GetRegisterValueAndReturnAddress(pDE, pFEAD, &bigVal, &v); if (pAddr == NULL) { COMPlusThrow(kArgumentNullException); } } _ASSERTE(pAddr != NULL); MethodTable * pMT = pFEArgInfo[currArgIndex].sigTypeHandle.GetMethodTable(); // // Stuff the newly boxed item into our GC-protected array. // pObjectRef[currArgIndex] = pMT->Box(pAddr); #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_ObjectRefArray; } #endif } } } /* * GatherFuncEvalMethodInfo * * This function is a helper for DoNormalFuncEval. It gathers together all the information * necessary to process the method * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * mSig - The metadata signature of the fuction to call. * argData - Array of information about the arguments. * ppUnboxedMD - Returns a resolve method desc if the original is an unboxing stub. * pObjectRefArray - GC protected array of objects passed to this func-eval call. * used to resolve down to the method target for generics. * pBufferForArgsArray - Array of values not needing gc-protection. May hold the * handle for the method targer for generics. * pfHasRetBuffArg - TRUE if the function has a return buffer. * pRetValueType - The TypeHandle of the return value. * * * Returns: * None. * */ void GatherFuncEvalMethodInfo(DebuggerEval *pDE, MetaSig mSig, DebuggerIPCE_FuncEvalArgData *argData, MethodDesc **ppUnboxedMD, OBJECTREF *pObjectRefArray, INT64 *pBufferForArgsArray, BOOL *pfHasRetBuffArg, // out BOOL *pfHasNonStdByValReturn, // out TypeHandle *pRetValueType // out, only if fHasRetBuffArg == true DEBUG_ARG(DataLocation pDataLocationArray[]) ) { WRAPPER_NO_CONTRACT; // // If 'this' is a non-static function that points to an unboxing stub, we need to return the // unboxed method desc to really call. // if ((pDE->m_evalType != DB_IPCE_FET_NEW_OBJECT) && !pDE->m_md->IsStatic() && pDE->m_md->IsUnboxingStub()) { *ppUnboxedMD = pDE->m_md->GetMethodTable()->GetUnboxedEntryPointMD(pDE->m_md); } // // Resolve down to the method on the class of the 'this' parameter. // if ((pDE->m_evalType != DB_IPCE_FET_NEW_OBJECT) && pDE->m_md->IsVtableMethod()) { // // Assuming that a constructor can't be an interface method... // _ASSERTE(pDE->m_evalType == DB_IPCE_FET_NORMAL); // // We need to go grab the 'this' argument to figure out what class we're headed for... // if (pDE->m_argCount == 0) { COMPlusThrow(kArgumentException, W("Argument_BadObjRef")); } // // We should have a valid this pointer. // <TODO>@todo: But the check should cover the register kind as well!</TODO> // if ((argData[0].argHome.kind == RAK_NONE) && (argData[0].argAddr == NULL)) { COMPlusThrow(kArgumentNullException); } // // Assume we can only have this for real objects or boxed value types, not value classes... // _ASSERTE((argData[0].argElementType == ELEMENT_TYPE_OBJECT) || (argData[0].argElementType == ELEMENT_TYPE_STRING) || (argData[0].argElementType == ELEMENT_TYPE_CLASS) || (argData[0].argElementType == ELEMENT_TYPE_ARRAY) || (argData[0].argElementType == ELEMENT_TYPE_SZARRAY) || ((argData[0].argElementType == ELEMENT_TYPE_VALUETYPE) && (pObjectRefArray[0] != NULL))); // // Now get the object pointer to our first arg. // OBJECTREF objRef = NULL; GCPROTECT_BEGIN(objRef); if (argData[0].argElementType == ELEMENT_TYPE_VALUETYPE) { // // In this case, we know where it is. // objRef = pObjectRefArray[0]; _ASSERTE(pDataLocationArray[0] & DL_ObjectRefArray); } else { TypeHandle dummyTH; ARG_SLOT objSlot; // // Take out the first arg. We're gonna trick GetFuncEvalArgValue by passing in just our // object ref as the stack. // // Note that we are passing ELEMENT_TYPE_END in the last parameter because we want to // supress the the valid object ref check. // GetFuncEvalArgValue(pDE, &(argData[0]), false, false, dummyTH, ELEMENT_TYPE_CLASS, dummyTH, &objSlot, NULL, pObjectRefArray, pBufferForArgsArray, NULL, ELEMENT_TYPE_END DEBUG_ARG(pDataLocationArray[0]) ); objRef = ArgSlotToObj(objSlot); } // // Validate the object // if (FAILED(ValidateObject(OBJECTREFToObject(objRef)))) { COMPlusThrow(kArgumentException, W("Argument_BadObjRef")); } // // Null isn't valid in this case! // if (objRef == NULL) { COMPlusThrow(kArgumentNullException); } // // Make sure that the object supplied is of a type that can call the method supplied. // if (!g_pEEInterface->ObjIsInstanceOf(OBJECTREFToObject(objRef), pDE->m_ownerTypeHandle)) { COMPlusThrow(kArgumentException, W("Argument_CORDBBadMethod")); } // // Now, find the proper MethodDesc for this interface method based on the object we're invoking the // method on. // pDE->m_targetCodeAddr = pDE->m_md->GetCallTarget(&objRef, pDE->m_ownerTypeHandle); GCPROTECT_END(); } else { pDE->m_targetCodeAddr = pDE->m_md->GetCallTarget(NULL, pDE->m_ownerTypeHandle); } // // Get the resulting type now. Doing this may trigger a GC or throw. // if (pDE->m_evalType != DB_IPCE_FET_NEW_OBJECT) { pDE->m_resultType = mSig.GetRetTypeHandleThrowing(); } // // Check if there is an explicit return argument, or if the return type is really a VALUETYPE but our // calling convention is passing it in registers. We just need to remember the pretValueClass so // that we will box it properly on our way out. // { ArgIterator argit(&mSig); *pfHasRetBuffArg = argit.HasRetBuffArg(); *pfHasNonStdByValReturn = argit.HasNonStandardByvalReturn(); } CorElementType retType = mSig.GetReturnType(); CorElementType retTypeNormalized = mSig.GetReturnTypeNormalized(); if (*pfHasRetBuffArg || *pfHasNonStdByValReturn || ((retType == ELEMENT_TYPE_VALUETYPE) && (retType != retTypeNormalized))) { *pRetValueType = mSig.GetRetTypeHandleThrowing(); } else { // // Make sure the caller initialized this value // _ASSERTE((*pRetValueType).IsNull()); } } /* * CopyArgsToBuffer * * This routine copies all the arguments to a local buffer, so that any one that needs to be * passed can be. Note that this local buffer is NOT GC-protected, and so all the values * in the buffer may not be relied on. You *must* use GetFuncEvalArgValue() to load up the * Arguments for the call, because it has the logic to decide which of the parallel arrays to pull * from. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * argData - Array of information about the arguments. * pFEArgInfo - An array of structs to hold the argument information. Must have be previously filled in. * pBufferArray - An array to store values. * * Returns: * None. * */ void CopyArgsToBuffer(DebuggerEval *pDE, DebuggerIPCE_FuncEvalArgData *argData, FuncEvalArgInfo *pFEArgInfo, INT64 *pBufferArray DEBUG_ARG(DataLocation pDataLocationArray[]) ) { CONTRACTL { THROWS; GC_NOTRIGGER; } CONTRACTL_END; unsigned currArgIndex = 0; if ((pDE->m_evalType == DB_IPCE_FET_NORMAL) && !pDE->m_md->IsStatic()) { // // Skip over the 'this' arg, since this function is not supposed to mess with it. // currArgIndex++; } // // Spin thru each argument now // for ( ; currArgIndex < pDE->m_argCount; currArgIndex++) { DebuggerIPCE_FuncEvalArgData *pFEAD = &argData[currArgIndex]; BOOL isByRef = (pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_BYREF); BOOL fNeedBoxOrUnbox; fNeedBoxOrUnbox = pFEArgInfo[currArgIndex].fNeedBoxOrUnbox; LOG((LF_CORDB, LL_EVERYTHING, "CATB: currArgIndex=%d\n", currArgIndex)); LOG((LF_CORDB, LL_EVERYTHING, "\t: argSigType=0x%x, byrefArgSigType=0x%0x, inType=0x%0x\n", pFEArgInfo[currArgIndex].argSigType, pFEArgInfo[currArgIndex].byrefArgSigType, pFEAD->argElementType)); INT64 *pDest = &(pBufferArray[currArgIndex]); switch (pFEAD->argElementType) { case ELEMENT_TYPE_I8: case ELEMENT_TYPE_U8: case ELEMENT_TYPE_R8: if (pFEAD->argAddr != NULL) { *pDest = *(INT64*)(pFEAD->argAddr); #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } else if (pFEAD->argIsLiteral) { _ASSERTE(sizeof(pFEAD->argLiteralData) >= sizeof(void *)); // If this is a literal arg, then we just copy the data. memcpy(pDest, pFEAD->argLiteralData, sizeof(INT64)); #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } else { #if !defined(HOST_64BIT) // RAK_REG is the only 4 byte type, all others are 8 byte types. _ASSERTE(pFEAD->argHome.kind != RAK_REG); INT64 bigVal = 0; SIZE_T v; INT64 *pAddr; pAddr = (INT64*)GetRegisterValueAndReturnAddress(pDE, pFEAD, &bigVal, &v); if (pAddr == NULL) { COMPlusThrow(kArgumentNullException); } *pDest = *pAddr; #else // HOST_64BIT // Both RAK_REG and RAK_FLOAT can be either 4 bytes or 8 bytes. _ASSERTE((pFEAD->argHome.kind == RAK_REG) || (pFEAD->argHome.kind == RAK_FLOAT)); CorDebugRegister regNum = GetArgAddrFromReg(pFEAD); *pDest = GetRegisterValue(pDE, regNum, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); #endif // HOST_64BIT #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } break; case ELEMENT_TYPE_VALUETYPE: // // For value types, we dont do anything here, instead delay until GetFuncEvalArgInfo // break; case ELEMENT_TYPE_CLASS: case ELEMENT_TYPE_OBJECT: case ELEMENT_TYPE_STRING: case ELEMENT_TYPE_ARRAY: case ELEMENT_TYPE_SZARRAY: if (pFEAD->argAddr != NULL) { if (!isByRef) { if (pFEAD->argIsHandleValue) { OBJECTHANDLE oh = (OBJECTHANDLE)(pFEAD->argAddr); *pDest = (INT64)(size_t)oh; } else { *pDest = *((SIZE_T*)(pFEAD->argAddr)); } #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } else { if (pFEAD->argIsHandleValue) { *pDest = (INT64)(size_t)(pFEAD->argAddr); } else { *pDest = *(SIZE_T*)(pFEAD->argAddr); } #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } } else if (pFEAD->argIsLiteral) { _ASSERTE(sizeof(pFEAD->argLiteralData) >= sizeof(INT64)); // The called function may expect a larger/smaller value than the literal value. // So we convert the value to the right type. CONSISTENCY_CHECK_MSGF(((pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_CLASS) || (pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_SZARRAY) || (pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_ARRAY)) || (isByRef && ((pFEArgInfo[currArgIndex].byrefArgSigType == ELEMENT_TYPE_CLASS) || (pFEArgInfo[currArgIndex].byrefArgSigType == ELEMENT_TYPE_SZARRAY) || (pFEArgInfo[currArgIndex].byrefArgSigType == ELEMENT_TYPE_ARRAY))), ("argSigType=0x%0x, byrefArgSigType=0x%0x, isByRef=%d", pFEArgInfo[currArgIndex].argSigType, pFEArgInfo[currArgIndex].byrefArgSigType, isByRef)); LOG((LF_CORDB, LL_EVERYTHING, "argSigType=0x%0x, byrefArgSigType=0x%0x, isByRef=%d\n", pFEArgInfo[currArgIndex].argSigType, pFEArgInfo[currArgIndex].byrefArgSigType, isByRef)); *(SIZE_T*)pDest = *(SIZE_T*)pFEAD->argLiteralData; #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } else { // RAK_REG is the only valid 4 byte type on WIN32. On WIN64, RAK_REG and RAK_FLOAT // can both be either 4 bytes or 8 bytes; _ASSERTE((pFEAD->argHome.kind == RAK_REG) BIT64_ONLY(|| (pFEAD->argHome.kind == RAK_FLOAT))); CorDebugRegister regNum = GetArgAddrFromReg(pFEAD); // Simply grab the value out of the proper register. SIZE_T v = GetRegisterValue(pDE, regNum, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); *pDest = v; #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } break; default: // 4-byte, 2-byte, or 1-byte values if (pFEAD->argAddr != NULL) { if (!isByRef) { if (pFEAD->argIsHandleValue) { OBJECTHANDLE oh = (OBJECTHANDLE)(pFEAD->argAddr); *pDest = (INT64)(size_t)oh; } else { GetAndSetLiteralValue(pDest, pFEArgInfo[currArgIndex].argSigType, pFEAD->argAddr, pFEAD->argElementType); } #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } else { if (pFEAD->argIsHandleValue) { *pDest = (INT64)(size_t)(pFEAD->argAddr); } else { // We have to make sure we only grab the correct size of memory from the source. On IA64, we // have to make sure we don't cause misaligned data exceptions as well. Then we put the value // into the pBufferArray. The reason is that we may be passing in some values by ref to a // function that's expecting something of a bigger size. Thus, if we don't do this, then we'll // be bashing memory right next to the source value as the function being called acts upon some // bigger value. GetAndSetLiteralValue(pDest, pFEArgInfo[currArgIndex].byrefArgSigType, pFEAD->argAddr, pFEAD->argElementType); } #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } } else if (pFEAD->argIsLiteral) { _ASSERTE(sizeof(pFEAD->argLiteralData) >= sizeof(INT32)); // The called function may expect a larger/smaller value than the literal value, // so we convert the value to the right type. CONSISTENCY_CHECK_MSGF( ((pFEArgInfo[currArgIndex].argSigType>=ELEMENT_TYPE_BOOLEAN) && (pFEArgInfo[currArgIndex].argSigType<=ELEMENT_TYPE_R8)) || (pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_PTR) || (pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_I) || (pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_U) || (isByRef && ((pFEArgInfo[currArgIndex].byrefArgSigType>=ELEMENT_TYPE_BOOLEAN) && (pFEArgInfo[currArgIndex].byrefArgSigType<=ELEMENT_TYPE_R8))), ("argSigType=0x%0x, byrefArgSigType=0x%0x, isByRef=%d", pFEArgInfo[currArgIndex].argSigType, pFEArgInfo[currArgIndex].byrefArgSigType, isByRef)); LOG((LF_CORDB, LL_EVERYTHING, "argSigType=0x%0x, byrefArgSigType=0x%0x, isByRef=%d\n", pFEArgInfo[currArgIndex].argSigType, pFEArgInfo[currArgIndex].byrefArgSigType, isByRef)); CorElementType relevantType = (isByRef ? pFEArgInfo[currArgIndex].byrefArgSigType : pFEArgInfo[currArgIndex].argSigType); GetAndSetLiteralValue(pDest, relevantType, pFEAD->argLiteralData, pFEAD->argElementType); #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } else { // RAK_REG is the only valid 4 byte type on WIN32. On WIN64, RAK_REG and RAK_FLOAT // can both be either 4 bytes or 8 bytes; _ASSERTE((pFEAD->argHome.kind == RAK_REG) BIT64_ONLY(|| (pFEAD->argHome.kind == RAK_FLOAT))); CorDebugRegister regNum = GetArgAddrFromReg(pFEAD); // Simply grab the value out of the proper register. SIZE_T v = GetRegisterValue(pDE, regNum, pFEAD->argHome.reg1Addr, pFEAD->argHome.reg1Value); *pDest = v; #ifdef _DEBUG if (currArgIndex < MAX_DATA_LOCATIONS_TRACKED) { pDataLocationArray[currArgIndex] |= DL_BufferForArgsArray; } #endif } } } } /* * PackArgumentArray * * This routine fills a given array with the correct values for passing to a managed function. * It uses various component arrays that contain information to correctly create the argument array. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * argData - Array of information about the arguments. * pUnboxedMD - MethodDesc of the function to call, after unboxing. * RetValueType - Type Handle of the return value of the managed function we will call. * pFEArgInfo - An array of structs to hold the argument information. Must have be previously filled in. * pObjectRefArray - An array that contains any object refs. It was built previously. * pMaybeInteriorPtrArray - An array that contains values that may be pointers to * the interior of a managed object. * pBufferForArgsArray - An array that contains values that need writable memory space * for passing ByRef. * newObj - Pre-allocated object for a 'new' call. * pArguments - This array is packed from the above arrays. * ppRetValue - Return value buffer if fRetValueArg is TRUE * * Returns: * None. * */ void PackArgumentArray(DebuggerEval *pDE, DebuggerIPCE_FuncEvalArgData *argData, FuncEvalArgInfo *pFEArgInfo, MethodDesc *pUnboxedMD, TypeHandle RetValueType, OBJECTREF *pObjectRefArray, void **pMaybeInteriorPtrArray, INT64 *pBufferForArgsArray, ValueClassInfo ** ppProtectedValueClasses, OBJECTREF newObj, BOOL fRetValueArg, ARG_SLOT *pArguments, PVOID * ppRetValue DEBUG_ARG(DataLocation pDataLocationArray[]) ) { WRAPPER_NO_CONTRACT; GCX_FORBID(); unsigned currArgIndex = 0; unsigned currArgSlot = 0; // // THIS POINTER (if any) // For non-static methods, or when returning a new object, // the first arg in the array is 'this' or the new object. // if (pDE->m_evalType == DB_IPCE_FET_NEW_OBJECT) { // // If this is a new object op, then we need to fill in the 0'th // arg slot with the 'this' ptr. // pArguments[0] = ObjToArgSlot(newObj); // // If we are invoking a function on a value class, but we have a boxed value class for 'this', // then go ahead and unbox it and leave a ref to the value class on the stack as 'this'. // if (pDE->m_md->GetMethodTable()->IsValueType()) { _ASSERTE(newObj->GetMethodTable()->IsValueType()); // This is one of those places we use true boxed nullables _ASSERTE(!Nullable::IsNullableType(pDE->m_md->GetMethodTable()) || newObj->GetMethodTable() == pDE->m_md->GetMethodTable()); void *pData = newObj->GetData(); pArguments[0] = PtrToArgSlot(pData); } // // Bump up the arg slot // currArgSlot++; } else if (!pDE->m_md->IsStatic()) { // // Place 'this' first in the array for non-static methods. // TypeHandle dummyTH; bool isByRef = false; bool fNeedBoxOrUnbox = false; // We had better have an object for a 'this' argument! CorElementType et = argData[0].argElementType; if (!(IsElementTypeSpecial(et) || et == ELEMENT_TYPE_VALUETYPE)) { COMPlusThrow(kArgumentOutOfRangeException, W("ArgumentOutOfRange_Enum")); } LOG((LF_CORDB, LL_EVERYTHING, "this: currArgSlot=%d, currArgIndex=%d et=0x%x\n", currArgSlot, currArgIndex, et)); if (pDE->m_md->GetMethodTable()->IsValueType()) { // For value classes, the 'this' parameter is always passed by reference. // However do not unbox if we are calling an unboxing stub. if (pDE->m_md == pUnboxedMD) { // pDE->m_md is expecting an unboxed this pointer. Then we will unbox it. isByRef = true; // Remember if we need to unbox this parameter, though. if ((et == ELEMENT_TYPE_CLASS) || (et == ELEMENT_TYPE_OBJECT)) { fNeedBoxOrUnbox = true; } } } else if (et == ELEMENT_TYPE_VALUETYPE) { // When the method that we invoking is defined on non value type and we receive the ValueType as input, // we are calling methods on System.Object. In this case, we need to box the input ValueType. fNeedBoxOrUnbox = true; } GetFuncEvalArgValue(pDE, &argData[currArgIndex], isByRef, fNeedBoxOrUnbox, dummyTH, ELEMENT_TYPE_CLASS, pDE->m_md->GetMethodTable(), &(pArguments[currArgSlot]), &(pMaybeInteriorPtrArray[currArgIndex]), &(pObjectRefArray[currArgIndex]), &(pBufferForArgsArray[currArgIndex]), NULL, ELEMENT_TYPE_OBJECT DEBUG_ARG((currArgIndex < MAX_DATA_LOCATIONS_TRACKED) ? pDataLocationArray[currArgIndex] : DL_All) ); LOG((LF_CORDB, LL_EVERYTHING, "this = 0x%08x\n", ArgSlotToPtr(pArguments[currArgSlot]))); // We need to check 'this' for a null ref ourselves... NOTE: only do this if we put an object reference on // the stack. If we put a byref for a value type, then we don't need to do this! if (!isByRef) { // The this pointer is not a unboxed value type. ARG_SLOT oi1 = pArguments[currArgSlot]; OBJECTREF o1 = ArgSlotToObj(oi1); if (FAILED(ValidateObject(OBJECTREFToObject(o1)))) { COMPlusThrow(kArgumentException, W("Argument_BadObjRef")); } if (OBJECTREFToObject(o1) == NULL) { COMPlusThrow(kNullReferenceException, W("NullReference_This")); } // For interface method, we have already done the check early on. if (!pDE->m_md->IsInterface()) { // We also need to make sure that the method that we are invoking is either defined on this object or the direct/indirect // base objects. Object *objPtr = OBJECTREFToObject(o1); MethodTable *pMT = objPtr->GetMethodTable(); // <TODO> Do this check in the following cases as well... </TODO> if (!pMT->IsArray() && !pDE->m_md->IsSharedByGenericInstantiations()) { TypeHandle thFrom = TypeHandle(pMT); TypeHandle thTarget = TypeHandle(pDE->m_md->GetMethodTable()); //<TODO> What about MaybeCast?</TODO> if (thFrom.CanCastToCached(thTarget) == TypeHandle::CannotCast) { COMPlusThrow(kArgumentException, W("Argument_CORDBBadMethod")); } } } } // // Increment up both arrays. // currArgSlot++; currArgIndex++; } // Special handling for functions that return value classes. if (fRetValueArg) { LOG((LF_CORDB, LL_EVERYTHING, "retBuff: currArgSlot=%d, currArgIndex=%d\n", currArgSlot, currArgIndex)); // // Allocate buffer for return value and GC protect it in case it contains object references // unsigned size = RetValueType.GetMethodTable()->GetNumInstanceFieldBytes(); #ifdef FEATURE_HFA // The buffer for HFAs has to be always ENREGISTERED_RETURNTYPE_MAXSIZE size = max(size, ENREGISTERED_RETURNTYPE_MAXSIZE); #endif BYTE * pTemp = new (interopsafe) BYTE[ALIGN_UP(sizeof(ValueClassInfo), 8) + size]; ValueClassInfo * pValueClassInfo = (ValueClassInfo *)pTemp; LPVOID pData = pTemp + ALIGN_UP(sizeof(ValueClassInfo), 8); memset(pData, 0, size); pValueClassInfo->pData = pData; pValueClassInfo->pMT = RetValueType.GetMethodTable(); pValueClassInfo->pNext = *ppProtectedValueClasses; *ppProtectedValueClasses = pValueClassInfo; pArguments[currArgSlot++] = PtrToArgSlot(pData); *ppRetValue = pData; } // REAL ARGUMENTS (if any) // Now do the remaining args for ( ; currArgIndex < pDE->m_argCount; currArgSlot++, currArgIndex++) { DebuggerIPCE_FuncEvalArgData *pFEAD = &argData[currArgIndex]; LOG((LF_CORDB, LL_EVERYTHING, "currArgSlot=%d, currArgIndex=%d\n", currArgSlot, currArgIndex)); LOG((LF_CORDB, LL_EVERYTHING, "\t: argSigType=0x%x, byrefArgSigType=0x%0x, inType=0x%0x\n", pFEArgInfo[currArgIndex].argSigType, pFEArgInfo[currArgIndex].byrefArgSigType, pFEAD->argElementType)); GetFuncEvalArgValue(pDE, pFEAD, pFEArgInfo[currArgIndex].argSigType == ELEMENT_TYPE_BYREF, pFEArgInfo[currArgIndex].fNeedBoxOrUnbox, pFEArgInfo[currArgIndex].sigTypeHandle, pFEArgInfo[currArgIndex].byrefArgSigType, pFEArgInfo[currArgIndex].byrefArgTypeHandle, &(pArguments[currArgSlot]), &(pMaybeInteriorPtrArray[currArgIndex]), &(pObjectRefArray[currArgIndex]), &(pBufferForArgsArray[currArgIndex]), ppProtectedValueClasses, pFEArgInfo[currArgIndex].argSigType DEBUG_ARG((currArgIndex < MAX_DATA_LOCATIONS_TRACKED) ? pDataLocationArray[currArgIndex] : DL_All) ); } } /* * UnpackFuncEvalResult * * This routine takes the resulting object of a func-eval, and does any copying, boxing, unboxing, necessary. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * newObj - Pre-allocated object for NEW_OBJ func-evals. * retObject - Pre-allocated object to be filled in with the info in pRetBuff. * RetValueType - The return type of the function called. * pRetBuff - The raw bytes returned by the func-eval call when there is a return buffer parameter. * * * Returns: * None. * */ void UnpackFuncEvalResult(DebuggerEval *pDE, OBJECTREF newObj, OBJECTREF retObject, TypeHandle RetValueType, void *pRetBuff ) { CONTRACTL { WRAPPER(THROWS); GC_NOTRIGGER; } CONTRACTL_END; // Ah, but if this was a new object op, then the result is really // the object we allocated above... if (pDE->m_evalType == DB_IPCE_FET_NEW_OBJECT) { // We purposely do not morph nullables to be boxed Ts here because debugger EE's otherwise // have no way of creating true nullables that they need for their own purposes. pDE->m_result[0] = ObjToArgSlot(newObj); pDE->m_retValueBoxing = Debugger::AllBoxed; } else if (!RetValueType.IsNull()) { LOG((LF_CORDB, LL_EVERYTHING, "FuncEval call is saving a boxed VC return value.\n")); // // We pre-created it above // _ASSERTE(retObject != NULL); // This is one of those places we use true boxed nullables _ASSERTE(!Nullable::IsNullableType(RetValueType)|| retObject->GetMethodTable() == RetValueType.GetMethodTable()); if (pRetBuff != NULL) { // box the object CopyValueClass(retObject->GetData(), pRetBuff, RetValueType.GetMethodTable()); } else { // box the primitive returned, retObject is a true nullable for nullabes, It will be Normalized later CopyValueClass(retObject->GetData(), pDE->m_result, RetValueType.GetMethodTable()); } pDE->m_result[0] = ObjToArgSlot(retObject); pDE->m_retValueBoxing = Debugger::AllBoxed; } else { // // Other FuncEvals return primitives as unboxed. // pDE->m_retValueBoxing = Debugger::OnlyPrimitivesUnboxed; } LOG((LF_CORDB, LL_INFO10000, "FuncEval call has saved the return value.\n")); // No exception, so it worked as far as we're concerned. pDE->m_successful = true; // If the result is an object, then place the object // reference into a strong handle and place the handle into the // pDE to protect the result from a collection. CorElementType retClassET = pDE->m_resultType.GetSignatureCorElementType(); if ((pDE->m_retValueBoxing == Debugger::AllBoxed) || !RetValueType.IsNull() || IsElementTypeSpecial(retClassET)) { LOG((LF_CORDB, LL_EVERYTHING, "Creating strong handle for boxed DoNormalFuncEval result.\n")); OBJECTHANDLE oh = pDE->m_thread->GetDomain()->CreateStrongHandle(ArgSlotToObj(pDE->m_result[0])); pDE->m_result[0] = (INT64)(LONG_PTR)oh; pDE->m_vmObjectHandle = VMPTR_OBJECTHANDLE::MakePtr(oh); } } /* * UnpackFuncEvalArguments * * This routine takes the resulting object of a func-eval, and does any copying, boxing, unboxing, necessary. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * newObj - Pre-allocated object for NEW_OBJ func-evals. * retObject - Pre-allocated object to be filled in with the info in pSource. * RetValueType - The return type of the function called. * pSource - The raw bytes returned by the func-eval call when there is a hidden parameter. * * * Returns: * None. * */ void UnpackFuncEvalArguments(DebuggerEval *pDE, DebuggerIPCE_FuncEvalArgData *argData, MetaSig mSig, BOOL staticMethod, OBJECTREF *pObjectRefArray, void **pMaybeInteriorPtrArray, void **pByRefMaybeInteriorPtrArray, INT64 *pBufferForArgsArray ) { WRAPPER_NO_CONTRACT; // Update any enregistered byrefs with their new values from the // proper byref temporary array. if (pDE->m_argCount > 0) { mSig.Reset(); unsigned currArgIndex = 0; if ((pDE->m_evalType == DB_IPCE_FET_NORMAL) && !pDE->m_md->IsStatic()) { // // Skip over the 'this' arg, since this function is not supposed to mess with it. // currArgIndex++; } for (; currArgIndex < pDE->m_argCount; currArgIndex++) { CorElementType argSigType = mSig.NextArgNormalized(); LOG((LF_CORDB, LL_EVERYTHING, "currArgIndex=%d argSigType=0x%x\n", currArgIndex, argSigType)); _ASSERTE(argSigType != ELEMENT_TYPE_END); if (argSigType == ELEMENT_TYPE_BYREF) { TypeHandle byrefClass = TypeHandle(); CorElementType byrefArgSigType = mSig.GetByRefType(&byrefClass); // If these are the true boxed nullables we created in BoxFuncEvalArguments, convert them back pObjectRefArray[currArgIndex] = Nullable::NormalizeBox(pObjectRefArray[currArgIndex]); LOG((LF_CORDB, LL_EVERYTHING, "DoNormalFuncEval: Updating enregistered byref...\n")); SetFuncEvalByRefArgValue(pDE, &argData[currArgIndex], byrefArgSigType, pBufferForArgsArray[currArgIndex], pMaybeInteriorPtrArray[currArgIndex], pByRefMaybeInteriorPtrArray[currArgIndex], pObjectRefArray[currArgIndex] ); } } } } /* * FuncEvalWrapper * * Helper function for func-eval. We have to split it out so that we can put a __try / __finally in to * notify on a Catch-Handler found. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * pArguments - created stack to pass for the call. * pCatcherStackAddr - stack address to report as the Catch Handler Found location. * * Returns: * None. * */ void FuncEvalWrapper(MethodDescCallSite* pMDCS, DebuggerEval *pDE, const ARG_SLOT *pArguments, BYTE *pCatcherStackAddr) { struct Param : NotifyOfCHFFilterWrapperParam { MethodDescCallSite* pMDCS; DebuggerEval *pDE; const ARG_SLOT *pArguments; }; Param param; param.pFrame = pCatcherStackAddr; // Inherited from NotifyOfCHFFilterWrapperParam param.pMDCS = pMDCS; param.pDE = pDE; param.pArguments = pArguments; PAL_TRY(Param *, pParam, &param) { pParam->pMDCS->CallWithValueTypes_RetArgSlot(pParam->pArguments, pParam->pDE->m_result, sizeof(pParam->pDE->m_result)); } PAL_EXCEPT_FILTER(NotifyOfCHFFilterWrapper) { // Should never reach here b/c handler should always continue search. _ASSERTE(false); } PAL_ENDTRY } /* * RecordFuncEvalException * * Helper function records the details of an exception that occurred during a FuncEval * Note that this should be called from within the target domain of the FuncEval. * * Parameters: * pDE - pointer to the DebuggerEval object being processed * ppException - the Exception object that was thrown * * Returns: * None. */ static void RecordFuncEvalException(DebuggerEval *pDE, OBJECTREF ppException ) { CONTRACTL { THROWS; // CreateStrongHandle could throw OOM GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; // We got an exception. Make the exception into our result. pDE->m_successful = false; LOG((LF_CORDB, LL_EVERYTHING, "D::FEHW - Exception during funceval.\n")); // // Special handling for thread abort exceptions. We need to explicitly reset the // abort request on the EE thread, then make sure to place this thread on a thunk // that will re-raise the exception when we continue the process. Note: we still // pass this thread abort exception up as the result of the eval. // if (IsExceptionOfType(kThreadAbortException, &ppException)) { _ASSERTE(pDE->m_aborting != DebuggerEval::FE_ABORT_NONE); // // Reset the abort request. // pDE->m_thread->ResetAbort(); // // This is the abort we sent down. // memset(pDE->m_result, 0, sizeof(pDE->m_result)); pDE->m_resultType = TypeHandle(); pDE->m_aborted = true; pDE->m_retValueBoxing = Debugger::NoValueTypeBoxing; LOG((LF_CORDB, LL_EVERYTHING, "D::FEHW - funceval abort exception.\n")); } else { // // The result is the exception object. // pDE->m_result[0] = ObjToArgSlot(ppException); pDE->m_resultType = ppException->GetTypeHandle(); OBJECTHANDLE oh = pDE->m_thread->GetDomain()->CreateStrongHandle(ArgSlotToObj(pDE->m_result[0])); pDE->m_result[0] = (ARG_SLOT)(LONG_PTR)oh; pDE->m_vmObjectHandle = VMPTR_OBJECTHANDLE::MakePtr(oh); pDE->m_retValueBoxing = Debugger::NoValueTypeBoxing; LOG((LF_CORDB, LL_EVERYTHING, "D::FEHW - Exception for the user.\n")); } } /* * DoNormalFuncEval * * Does the main body of work (steps 1c onward) for the normal func-eval algorithm detailed at the * top of this file. The args have already been GC protected and we've transitioned into the appropriate * domain (steps 1a & 1b). This has to be a seperate function from GCProtectArgsAndDoNormalFuncEval * because otherwise we can't reliably find the right GCFrames to pop when unwinding the stack due to * an exception on 64-bit platforms (we have some GCFrames outside of the TRY, and some inside, * and they won't necesarily be layed out sequentially on the stack if they are all in the same function). * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * pCatcherStackAddr - stack address to report as the Catch Handler Found location. * pObjectRefArray - An array to hold object ref args. This array is protected from GC's. * pMaybeInteriorPtrArray - An array to hold values that may be pointers into a managed object. * This array is protected from GCs. * pByRefMaybeInteriorPtrArray - An array to hold values that may be pointers into a managed * object. This array is protected from GCs. This array protects the address of the arguments * while the pMaybeInteriorPtrArray protects the value of the arguments. We need to do this * because of by ref arguments. * pBufferForArgsArray - a buffer of temporary scratch space for things that do not need to be * protected, or are protected for free (e.g. Handles). * pDataLocationArray - an array of tracking data for debug sanity checks * * Returns: * None. */ static void DoNormalFuncEval( DebuggerEval *pDE, BYTE *pCatcherStackAddr, OBJECTREF *pObjectRefArray, void **pMaybeInteriorPtrArray, void **pByRefMaybeInteriorPtrArray, INT64 *pBufferForArgsArray, ValueClassInfo ** ppProtectedValueClasses DEBUG_ARG(DataLocation pDataLocationArray[]) ) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; // // Now that all the args are protected, we can go back and deal with generic args and resolving // all their information. // ResolveFuncEvalGenericArgInfo(pDE); // // Grab the signature of the method we're working on and do some error checking. // Note that if this instantiated generic code, then this will // correctly give as an instantiated view of the signature that we can iterate without // worrying about generic items in the signature. // MetaSig mSig(pDE->m_md); BYTE callingconvention = mSig.GetCallingConvention(); if (!isCallConv(callingconvention, IMAGE_CEE_CS_CALLCONV_DEFAULT)) { // We don't support calling vararg! COMPlusThrow(kArgumentException, W("Argument_CORDBBadVarArgCallConv")); } // // We'll need to know if this is a static method or not. // BOOL staticMethod = pDE->m_md->IsStatic(); _ASSERTE((pDE->m_evalType == DB_IPCE_FET_NORMAL) || !staticMethod); // // Do Step 1c - Pre-allocate space for new objects. // OBJECTREF newObj = NULL; GCPROTECT_BEGIN(newObj); SIZE_T allocArgCnt = 0; if (pDE->m_evalType == DB_IPCE_FET_NEW_OBJECT) { ValidateFuncEvalReturnType(DB_IPCE_FET_NEW_OBJECT, pDE->m_resultType.GetMethodTable()); pDE->m_resultType.GetMethodTable()->EnsureInstanceActive(); newObj = AllocateObject(pDE->m_resultType.GetMethodTable()); // // Note: we account for an extra argument in the count passed // in. We use this to increase the space allocated for args, // and we use it to control the number of args copied into // those arrays below. Note: m_argCount already includes space // for this. // allocArgCnt = pDE->m_argCount + 1; } else { allocArgCnt = pDE->m_argCount; } // // Validate the argument count with mSig. // if (allocArgCnt != (mSig.NumFixedArgs() + (staticMethod ? 0 : 1))) { COMPlusThrow(kTargetParameterCountException, W("Arg_ParmCnt")); } // // Do Step 1d - Gather information about the method that will be called. // // An array to hold information about the parameters to be passed. This is // all the information we need to gather before entering the GCX_FORBID area. // DebuggerIPCE_FuncEvalArgData *argData = pDE->GetArgData(); MethodDesc *pUnboxedMD = pDE->m_md; BOOL fHasRetBuffArg; BOOL fHasNonStdByValReturn; TypeHandle RetValueType; BoxFuncEvalThisParameter(pDE, argData, pMaybeInteriorPtrArray, pObjectRefArray DEBUG_ARG(pDataLocationArray) ); GatherFuncEvalMethodInfo(pDE, mSig, argData, &pUnboxedMD, pObjectRefArray, pBufferForArgsArray, &fHasRetBuffArg, &fHasNonStdByValReturn, &RetValueType DEBUG_ARG(pDataLocationArray) ); // // Do Step 1e - Gather info from runtime about args (may trigger a GC). // SIZE_T cbAllocSize; if (!(ClrSafeInt<SIZE_T>::multiply(pDE->m_argCount, sizeof(FuncEvalArgInfo), cbAllocSize)) || (cbAllocSize != (size_t)(cbAllocSize))) { ThrowHR(COR_E_OVERFLOW); } FuncEvalArgInfo * pFEArgInfo = (FuncEvalArgInfo *)_alloca(cbAllocSize); memset(pFEArgInfo, 0, cbAllocSize); GatherFuncEvalArgInfo(pDE, mSig, argData, pFEArgInfo); // // Do Step 1f - Box or unbox arguments one at a time, placing newly boxed items into // pObjectRefArray immediately after creating them. // BoxFuncEvalArguments(pDE, argData, pFEArgInfo, pMaybeInteriorPtrArray, pObjectRefArray DEBUG_ARG(pDataLocationArray) ); #ifdef _DEBUG if (!RetValueType.IsNull()) { _ASSERTE(RetValueType.IsValueType()); } #endif // // Do Step 1g - Pre-allocate any return value object. // OBJECTREF retObject = NULL; GCPROTECT_BEGIN(retObject); if ((pDE->m_evalType != DB_IPCE_FET_NEW_OBJECT) && !RetValueType.IsNull()) { ValidateFuncEvalReturnType(pDE->m_evalType, RetValueType.GetMethodTable()); RetValueType.GetMethodTable()->EnsureInstanceActive(); retObject = AllocateObject(RetValueType.GetMethodTable()); } // // Do Step 1h - Copy into scratch buffer all enregistered arguments, and // ByRef literals. // CopyArgsToBuffer(pDE, argData, pFEArgInfo, pBufferForArgsArray DEBUG_ARG(pDataLocationArray) ); // // We presume that the function has a return buffer. This assumption gets squeezed out // when we pack the argument array. // allocArgCnt++; LOG((LF_CORDB, LL_EVERYTHING, "Func eval for %s::%s: allocArgCnt=%d\n", pDE->m_md->m_pszDebugClassName, pDE->m_md->m_pszDebugMethodName, allocArgCnt)); MethodDescCallSite funcToEval(pDE->m_md, pDE->m_targetCodeAddr); // // Do Step 1i - Create and pack argument array for managed function call. // // Allocate space for argument stack // if ((!ClrSafeInt<SIZE_T>::multiply(allocArgCnt, sizeof(ARG_SLOT), cbAllocSize)) || (cbAllocSize != (size_t)(cbAllocSize))) { ThrowHR(COR_E_OVERFLOW); } ARG_SLOT * pArguments = (ARG_SLOT *)_alloca(cbAllocSize); memset(pArguments, 0, cbAllocSize); LPVOID pRetBuff = NULL; PackArgumentArray(pDE, argData, pFEArgInfo, pUnboxedMD, RetValueType, pObjectRefArray, pMaybeInteriorPtrArray, pBufferForArgsArray, ppProtectedValueClasses, newObj, #ifdef FEATURE_HFA fHasRetBuffArg || fHasNonStdByValReturn, #else fHasRetBuffArg, #endif pArguments, &pRetBuff DEBUG_ARG(pDataLocationArray) ); // // // Do Step 2 - Make the call! // // FuncEvalWrapper(&funcToEval, pDE, pArguments, pCatcherStackAddr); { // We have now entered the zone where taking a GC is fatal until we get the // return value all fixed up. // GCX_FORBID(); // // // Do Step 3 - Unpack results and update ByRef arguments. // // // LOG((LF_CORDB, LL_EVERYTHING, "FuncEval call has returned\n")); // GC still can't happen until we get our return value out half way through the unpack function UnpackFuncEvalResult(pDE, newObj, retObject, RetValueType, pRetBuff ); } UnpackFuncEvalArguments(pDE, argData, mSig, staticMethod, pObjectRefArray, pMaybeInteriorPtrArray, pByRefMaybeInteriorPtrArray, pBufferForArgsArray ); GCPROTECT_END(); // retObject GCPROTECT_END(); // newObj } /* * GCProtectArgsAndDoNormalFuncEval * * This routine is the primary entrypoint for normal func-evals. It implements the algorithm * described at the top of this file, doing steps 1a and 1b itself, then calling DoNormalFuncEval * to do the rest. * * Parameters: * pDE - pointer to the DebuggerEval object being processed. * pCatcherStackAddr - stack address to report as the Catch Handler Found location. * * Returns: * None. * */ static void GCProtectArgsAndDoNormalFuncEval(DebuggerEval *pDE, BYTE *pCatcherStackAddr ) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; INDEBUG(DataLocation pDataLocationArray[MAX_DATA_LOCATIONS_TRACKED]); // // An array to hold object ref args. This array is protected from GC's. // SIZE_T cbAllocSize; if ((!ClrSafeInt<SIZE_T>::multiply(pDE->m_argCount, sizeof(OBJECTREF), cbAllocSize)) || (cbAllocSize != (size_t)(cbAllocSize))) { ThrowHR(COR_E_OVERFLOW); } OBJECTREF * pObjectRefArray = (OBJECTREF*)_alloca(cbAllocSize); memset(pObjectRefArray, 0, cbAllocSize); GCPROTECT_ARRAY_BEGIN(*pObjectRefArray, pDE->m_argCount); // // An array to hold values that may be pointers into a managed object. This array // is protected from GCs. // if ((!ClrSafeInt<SIZE_T>::multiply(pDE->m_argCount, sizeof(void**), cbAllocSize)) || (cbAllocSize != (size_t)(cbAllocSize))) { ThrowHR(COR_E_OVERFLOW); } void ** pMaybeInteriorPtrArray = (void **)_alloca(cbAllocSize); memset(pMaybeInteriorPtrArray, 0, cbAllocSize); GCPROTECT_BEGININTERIOR_ARRAY(*pMaybeInteriorPtrArray, (UINT)(cbAllocSize/sizeof(OBJECTREF))); // // An array to hold values that may be pointers into a managed object. This array // is protected from GCs. This array protects the address of the arguments while the // pMaybeInteriorPtrArray protects the value of the arguments. We need to do this because // of by ref arguments. // if ((!ClrSafeInt<SIZE_T>::multiply(pDE->m_argCount, sizeof(void**), cbAllocSize)) || (cbAllocSize != (size_t)(cbAllocSize))) { ThrowHR(COR_E_OVERFLOW); } void ** pByRefMaybeInteriorPtrArray = (void **)_alloca(cbAllocSize); memset(pByRefMaybeInteriorPtrArray, 0, cbAllocSize); GCPROTECT_BEGININTERIOR_ARRAY(*pByRefMaybeInteriorPtrArray, (UINT)(cbAllocSize/sizeof(OBJECTREF))); // // A buffer of temporary scratch space for things that do not need to be protected, or // are protected for free (e.g. Handles). // if ((!ClrSafeInt<SIZE_T>::multiply(pDE->m_argCount, sizeof(INT64), cbAllocSize)) || (cbAllocSize != (size_t)(cbAllocSize))) { ThrowHR(COR_E_OVERFLOW); } INT64 *pBufferForArgsArray = (INT64*)_alloca(cbAllocSize); memset(pBufferForArgsArray, 0, cbAllocSize); FrameWithCookie<ProtectValueClassFrame> protectValueClassFrame; // // Initialize our tracking array // INDEBUG(memset(pDataLocationArray, 0, sizeof(DataLocation) * (MAX_DATA_LOCATIONS_TRACKED))); { GCX_FORBID(); // // Do step 1a // GCProtectAllPassedArgs(pDE, pObjectRefArray, pMaybeInteriorPtrArray, pByRefMaybeInteriorPtrArray, pBufferForArgsArray DEBUG_ARG(pDataLocationArray) ); } // // Do step 1b: we can switch domains since everything is now protected. // Note that before this point, it's unsafe to rely on pDE->m_module since it may be // invalid due to an AD unload. // All normal func evals should have an AppDomain specified. // // Wrap everything in a EX_TRY so we catch any exceptions that could be thrown. // Note that we don't let any thrown exceptions cross the AppDomain boundary because we don't // want them to get marshalled. EX_TRY { DoNormalFuncEval( pDE, pCatcherStackAddr, pObjectRefArray, pMaybeInteriorPtrArray, pByRefMaybeInteriorPtrArray, pBufferForArgsArray, protectValueClassFrame.GetValueClassInfoList() DEBUG_ARG(pDataLocationArray) ); } EX_CATCH { // We got an exception. Make the exception into our result. OBJECTREF ppException = GET_THROWABLE(); GCX_FORBID(); RecordFuncEvalException( pDE, ppException); } // Note: we need to catch all exceptioins here because they all get reported as the result of // the funceval. If a ThreadAbort occurred other than for a funcEval abort, we'll re-throw it manually. EX_END_CATCH(SwallowAllExceptions); protectValueClassFrame.Pop(); CleanUpTemporaryVariables(protectValueClassFrame.GetValueClassInfoList()); GCPROTECT_END(); // pByRefMaybeInteriorPtrArray GCPROTECT_END(); // pMaybeInteriorPtrArray GCPROTECT_END(); // pObjectRefArray LOG((LF_CORDB, LL_EVERYTHING, "DoNormalFuncEval: returning...\n")); } void FuncEvalHijackRealWorker(DebuggerEval *pDE, Thread* pThread, FuncEvalFrame* pFEFrame) { BYTE * pCatcherStackAddr = (BYTE*) pFEFrame; // Handle normal func evals in DoNormalFuncEval if ((pDE->m_evalType == DB_IPCE_FET_NEW_OBJECT) || (pDE->m_evalType == DB_IPCE_FET_NORMAL)) { GCProtectArgsAndDoNormalFuncEval(pDE, pCatcherStackAddr); LOG((LF_CORDB, LL_EVERYTHING, "DoNormalFuncEval has returned.\n")); return; } OBJECTREF newObj = NULL; GCPROTECT_BEGIN(newObj); // Wrap everything in a EX_TRY so we catch any exceptions that could be thrown. // Note that we don't let any thrown exceptions cross the AppDomain boundary because we don't // want them to get marshalled. EX_TRY { DebuggerIPCE_TypeArgData *firstdata = pDE->GetTypeArgData(); DWORD nGenericArgs = pDE->m_genericArgsCount; SIZE_T cbAllocSize; if ((!ClrSafeInt<SIZE_T>::multiply(nGenericArgs, sizeof(TypeHandle *), cbAllocSize)) || (cbAllocSize != (size_t)(cbAllocSize))) { ThrowHR(COR_E_OVERFLOW); } TypeHandle *pGenericArgs = (nGenericArgs == 0) ? NULL : (TypeHandle *) _alloca(cbAllocSize); // // Snag the type arguments from the input and get the // method desc that corresponds to the instantiated desc. // Debugger::TypeDataWalk walk(firstdata, pDE->m_genericArgsNodeCount); walk.ReadTypeHandles(nGenericArgs, pGenericArgs); // <TODO>better error message</TODO> if (!walk.Finished()) COMPlusThrow(kArgumentException, W("Argument_InvalidGenericArg")); switch (pDE->m_evalType) { case DB_IPCE_FET_NEW_OBJECT_NC: { // Find the class. TypeHandle thClass = g_pEEInterface->LoadClass(pDE->m_debuggerModule->GetRuntimeModule(), pDE->m_classToken); if (thClass.IsNull()) COMPlusThrow(kArgumentNullException, W("ArgumentNull_Type")); // Apply any type arguments TypeHandle th = (nGenericArgs == 0) ? thClass : g_pEEInterface->LoadInstantiation(pDE->m_debuggerModule->GetRuntimeModule(), pDE->m_classToken, nGenericArgs, pGenericArgs); if (th.IsNull() || th.ContainsGenericVariables()) COMPlusThrow(kArgumentException, W("Argument_InvalidGenericArg")); // Run the Class Init for this type, if necessary. MethodTable * pOwningMT = th.GetMethodTable(); pOwningMT->EnsureInstanceActive(); pOwningMT->CheckRunClassInitThrowing(); // Create a new instance of the class ValidateFuncEvalReturnType(DB_IPCE_FET_NEW_OBJECT_NC, th.GetMethodTable()); newObj = AllocateObject(th.GetMethodTable()); // No exception, so it worked. pDE->m_successful = true; // So is the result type. pDE->m_resultType = th; // // Box up all returned objects // pDE->m_retValueBoxing = Debugger::AllBoxed; // Make a strong handle for the result. OBJECTHANDLE oh = pDE->m_thread->GetDomain()->CreateStrongHandle(newObj); pDE->m_result[0] = (ARG_SLOT)(LONG_PTR)oh; pDE->m_vmObjectHandle = VMPTR_OBJECTHANDLE::MakePtr(oh); break; } case DB_IPCE_FET_NEW_STRING: { // Create the string. m_argData is not necessarily null terminated... // The numeration parameter represents the string length, not the buffer size, but // we have passed the buffer size across to copy our data properly, so must divide back out. // NewString will return NULL if pass null, but want an empty string in that case, so // just create an EmptyString explicitly. if ((pDE->m_argData == NULL) || (pDE->m_stringSize == 0)) { newObj = StringObject::GetEmptyString(); } else { newObj = StringObject::NewString(pDE->GetNewStringArgData(), (int)(pDE->m_stringSize/sizeof(WCHAR))); } // No exception, so it worked. pDE->m_successful = true; // Result type is, of course, a string. pDE->m_resultType = newObj->GetTypeHandle(); // Place the result in a strong handle to protect it from a collection. OBJECTHANDLE oh = pDE->m_thread->GetDomain()->CreateStrongHandle(newObj); pDE->m_result[0] = (ARG_SLOT)(LONG_PTR)oh; pDE->m_vmObjectHandle = VMPTR_OBJECTHANDLE::MakePtr(oh); break; } case DB_IPCE_FET_NEW_ARRAY: { // <TODO>@todo: We're only gonna handle SD arrays for right now.</TODO> if (pDE->m_arrayRank > 1) COMPlusThrow(kRankException, W("Rank_MultiDimNotSupported")); // Grab the elementType from the arg/data area. _ASSERTE(nGenericArgs == 1); TypeHandle th = pGenericArgs[0]; CorElementType et = th.GetSignatureCorElementType(); // Gotta be a primitive, class, or System.Object. if (((et < ELEMENT_TYPE_BOOLEAN) || (et > ELEMENT_TYPE_R8)) && !IsElementTypeSpecial(et)) { COMPlusThrow(kArgumentOutOfRangeException, W("ArgumentOutOfRange_Enum")); } // Grab the dims from the arg/data area. These come after the type arguments. SIZE_T *dims; dims = (SIZE_T*) (firstdata + pDE->m_genericArgsNodeCount); if (IsElementTypeSpecial(et)) { newObj = AllocateObjectArray((DWORD)dims[0], th); } else { // Create a simple array. Note: we can only do this type of create here due to the checks above. newObj = AllocatePrimitiveArray(et, (DWORD)dims[0]); } // No exception, so it worked. pDE->m_successful = true; // Result type is, of course, the type of the array. pDE->m_resultType = newObj->GetTypeHandle(); // Place the result in a strong handle to protect it from a collection. OBJECTHANDLE oh = pDE->m_thread->GetDomain()->CreateStrongHandle(newObj); pDE->m_result[0] = (ARG_SLOT)(LONG_PTR)oh; pDE->m_vmObjectHandle = VMPTR_OBJECTHANDLE::MakePtr(oh); break; } default: _ASSERTE(!"Invalid eval type!"); } } EX_CATCH { // We got an exception. Make the exception into our result. OBJECTREF ppException = GET_THROWABLE(); GCX_FORBID(); RecordFuncEvalException( pDE, ppException); } // Note: we need to catch all exceptioins here because they all get reported as the result of // the funceval. EX_END_CATCH(SwallowAllExceptions); GCPROTECT_END(); } // // FuncEvalHijackWorker is the function that managed threads start executing in order to perform a function // evaluation. Control is transfered here on the proper thread by hijacking that that's IP to this method in // Debugger::FuncEvalSetup. This function can also be called directly by a Runtime thread that is stopped sending a // first or second chance exception to the Right Side. // // The DebuggerEval object may get deleted by the helper thread doing a CleanupFuncEval while this thread is blocked // sending the eval complete. void * STDCALL FuncEvalHijackWorker(DebuggerEval *pDE) { CONTRACTL { MODE_COOPERATIVE; GC_TRIGGERS; THROWS; PRECONDITION(CheckPointer(pDE)); } CONTRACTL_END; Thread *pThread = NULL; CONTEXT *filterContext = NULL; { GCX_FORBID(); LOG((LF_CORDB, LL_INFO100000, "D:FEHW for pDE:%08x evalType:%d\n", pDE, pDE->m_evalType)); pThread = GetThread(); #ifndef DACCESS_COMPILE #ifdef _DEBUG // // Flush all debug tracking information for this thread on object refs as it // only approximates proper tracking and may have stale data, resulting in false // positives. We dont want that as func-eval runs a lot, so flush them now. // g_pEEInterface->ObjectRefFlush(pThread); #endif #endif if (!pDE->m_evalDuringException) { // // From this point forward we use FORBID regions to guard against GCs. // Refer to code:Debugger::FuncEvalSetup to see the increment was done. // g_pDebugger->DecThreadsAtUnsafePlaces(); } // Preemptive GC is disabled at the start of this method. _ASSERTE(g_pEEInterface->IsPreemptiveGCDisabled()); DebuggerController::DispatchFuncEvalEnter(pThread); // If we've got a filter context still installed, then remove it while we do the work... filterContext = g_pEEInterface->GetThreadFilterContext(pDE->m_thread); if (filterContext) { _ASSERTE(pDE->m_evalDuringException); g_pEEInterface->SetThreadFilterContext(pDE->m_thread, NULL); } } // // We cannot scope the following in a GCX_FORBID(), but we would like to. But we need the frames on the // stack here, so they must never go out of scope. // // // Push our FuncEvalFrame. The return address is equal to the IP in the saved context in the DebuggerEval. The // m_Datum becomes the ptr to the DebuggerEval. The frame address also serves as the address of the catch-handler-found. // FrameWithCookie<FuncEvalFrame> FEFrame(pDE, GetIP(&pDE->m_context), true); FEFrame.Push(); // On ARM/ARM64 the single step flag is per-thread and not per context. We need to make sure that the SS flag is cleared // for the funceval, and that the state is back to what it should be after the funceval completes. #ifdef FEATURE_EMULATE_SINGLESTEP bool ssEnabled = pDE->m_thread->IsSingleStepEnabled(); if (ssEnabled) pDE->m_thread->DisableSingleStep(); #endif FuncEvalHijackRealWorker(pDE, pThread, &FEFrame); #ifdef FEATURE_EMULATE_SINGLESTEP if (ssEnabled) pDE->m_thread->EnableSingleStep(); #endif LOG((LF_CORDB, LL_EVERYTHING, "FuncEval has finished its primary work.\n")); // // The func-eval is now completed, successfully or with failure, aborted or run-to-completion. // pDE->m_completed = true; if (pDE->m_thread->IsAbortRequested()) { // noone else shoud be requesting aborts, // so this must be our request that did not have a chance to run. _ASSERTE((pDE->m_aborting != DebuggerEval::FE_ABORT_NONE) && !pDE->m_aborted); // // Reset the abort request if a func-eval abort was submitted, but the func-eval completed // before the abort could take place, we want to make sure we do not throw an abort exception // in this case. // pDE->m_thread->ResetAbort(); } // Codepitching can hijack our frame's return address. That means that we'll need to update PC in our saved context // so that when its restored, its like we've returned to the codepitching hijack. At this point, the old value of // EIP is worthless anyway. if (!pDE->m_evalDuringException) { SetIP(&pDE->m_context, (SIZE_T)FEFrame.GetReturnAddress()); } // // Disable all steppers and breakpoints created during the func-eval // DebuggerController::DispatchFuncEvalExit(pThread); void *dest = NULL; if (!pDE->m_evalDuringException) { // Signal to the helper thread that we're done with our func eval. Start by creating a DebuggerFuncEvalComplete // object. Give it an address at which to create the patch, which is a chunk of memory specified by our // DebuggerEval big enough to hold a breakpoint instruction. #ifdef TARGET_ARM dest = (BYTE*)((DWORD)&(pDE->m_bpInfoSegment->m_breakpointInstruction) | THUMB_CODE); #else dest = &(pDE->m_bpInfoSegment->m_breakpointInstruction); #endif // // The created object below sets up itself as a hijack and will destroy itself when the hijack and work // is done. // DebuggerFuncEvalComplete *comp; comp = new (interopsafe) DebuggerFuncEvalComplete(pThread, dest); _ASSERTE(comp != NULL); // would have thrown // Pop the FuncEvalFrame now that we're pretty much done. Make sure we // don't pop the frame too early. Because GC can be triggered in our grabbing of // Debugger lock. If we pop the FE frame without setting back thread filter context, // the frames left uncrawlable. // FEFrame.Pop(); } else { // We don't have to setup any special hijacks to return from here when we've been processing during an // exception. We just go ahead and send the FuncEvalComplete event over now. Don't forget to enable/disable PGC // around the call... _ASSERTE(g_pEEInterface->IsPreemptiveGCDisabled()); if (filterContext != NULL) { g_pEEInterface->SetThreadFilterContext(pDE->m_thread, filterContext); } // Pop the FuncEvalFrame now that we're pretty much done. FEFrame.Pop(); { // // This also grabs the debugger lock, so we can atomically check if a detach has // happened. // SENDIPCEVENT_BEGIN(g_pDebugger, pDE->m_thread); if ((pDE->m_thread->GetDomain() != NULL) && pDE->m_thread->GetDomain()->IsDebuggerAttached()) { if (CORDebuggerAttached()) { g_pDebugger->FuncEvalComplete(pDE->m_thread, pDE); g_pDebugger->SyncAllThreads(SENDIPCEVENT_PtrDbgLockHolder); } } SENDIPCEVENT_END; } } // pDE may now point to deleted memory if the helper thread did a CleanupFuncEval while we // were blocked waiting for a continue after the func-eval complete. // We return the address that we want to resume executing at. return dest; } #if defined(FEATURE_EH_FUNCLETS) && !defined(TARGET_UNIX) EXTERN_C EXCEPTION_DISPOSITION FuncEvalHijackPersonalityRoutine(IN PEXCEPTION_RECORD pExceptionRecord BIT64_ARG(IN ULONG64 MemoryStackFp) NOT_BIT64_ARG(IN ULONG32 MemoryStackFp), IN OUT PCONTEXT pContextRecord, IN OUT PDISPATCHER_CONTEXT pDispatcherContext ) { DebuggerEval* pDE = NULL; #if defined(TARGET_AMD64) pDE = *(DebuggerEval**)(pDispatcherContext->EstablisherFrame); #elif defined(TARGET_ARM) // on ARM the establisher frame is the SP of the caller of FuncEvalHijack, on other platforms it's FuncEvalHijack's SP. // in FuncEvalHijack we allocate 8 bytes of stack space and then store R0 at the current SP, so if we subtract 8 from // the establisher frame we can get the stack location where R0 was stored. pDE = *(DebuggerEval**)(pDispatcherContext->EstablisherFrame - 8); #elif defined(TARGET_ARM64) // on ARM64 the establisher frame is the SP of the caller of FuncEvalHijack. // in FuncEvalHijack we allocate 32 bytes of stack space and then store R0 at the current SP + 16, so if we subtract 16 from // the establisher frame we can get the stack location where R0 was stored. pDE = *(DebuggerEval**)(pDispatcherContext->EstablisherFrame - 16); #else _ASSERTE(!"NYI - FuncEvalHijackPersonalityRoutine()"); #endif FixupDispatcherContext(pDispatcherContext, &(pDE->m_context), pContextRecord); // Returning ExceptionCollidedUnwind will cause the OS to take our new context record and // dispatcher context and restart the exception dispatching on this call frame, which is // exactly the behavior we want. return ExceptionCollidedUnwind; } #endif // FEATURE_EH_FUNCLETS && !TARGET_UNIX #endif // ifndef DACCESS_COMPILE
-1
dotnet/runtime
66,372
Add Stopwatch.GetElapsedTime
Fixes https://github.com/dotnet/runtime/issues/65858
stephentoub
2022-03-09T01:52:28Z
2022-03-09T12:42:15Z
ca731545a58307870a0baebb0ee43eeea61f175f
c9f7f7389e8e9a00d501aef696333b67d218baac
Add Stopwatch.GetElapsedTime. Fixes https://github.com/dotnet/runtime/issues/65858
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltScenarios/EXslt/string-tokenize.xsl
<?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:str="http://exslt.org/strings" exclude-result-prefixes="str"> <xsl:output indent="yes" omit-xml-declaration="yes"/> <xsl:template match="/"> <out> <test1> <xsl:copy-of select="str:tokenize('2001-06-03T11:40:23', '-T:')"/> </test1> <test2> <xsl:copy-of select="str:tokenize('date math str')"/> </test2> <test3> <xsl:copy-of select="str:tokenize('foo', '')"/> </test3> <test4> <xsl:copy-of select="str:tokenize('', '-')"/> </test4> </out> </xsl:template> </xsl:stylesheet>
<?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:str="http://exslt.org/strings" exclude-result-prefixes="str"> <xsl:output indent="yes" omit-xml-declaration="yes"/> <xsl:template match="/"> <out> <test1> <xsl:copy-of select="str:tokenize('2001-06-03T11:40:23', '-T:')"/> </test1> <test2> <xsl:copy-of select="str:tokenize('date math str')"/> </test2> <test3> <xsl:copy-of select="str:tokenize('foo', '')"/> </test3> <test4> <xsl:copy-of select="str:tokenize('', '-')"/> </test4> </out> </xsl:template> </xsl:stylesheet>
-1