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,193
Add xarch `blsi`
This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
Wraith2
2022-03-04T13:44:46Z
2022-03-15T00:53:39Z
436b97cc809a3db1d1a25faedbc64aa97875bae3
6bf873a991bcae3f80f5de155a594cefc8824eea
Add xarch `blsi`. This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
./src/libraries/System.Runtime/tests/System/PseudoCustomAttributeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization; using Xunit; namespace System.Tests { [ActiveIssue("https://github.com/dotnet/runtimelab/issues/830", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))] public static partial class PseudoCustomAttributeTests { [Theory] [MemberData(nameof(TestData_AttributeExists))] [MemberData(nameof(TestData_AttributeDoesNotExist))] public static void IsDefined(object target, Type attributeType, Attribute attribute) { switch (target) { case Type type: Assert.Equal(attribute != null, Attribute.IsDefined(type, attributeType)); Assert.Equal(attribute != null, Attribute.IsDefined(type, attributeType, true)); break; case MemberInfo memberInfo: Assert.Equal(attribute != null, Attribute.IsDefined(memberInfo, attributeType)); Assert.Equal(attribute != null, Attribute.IsDefined(memberInfo, attributeType, true)); break; case ParameterInfo parameterInfo: Assert.Equal(attribute != null, Attribute.IsDefined(parameterInfo, attributeType)); Assert.Equal(attribute != null, Attribute.IsDefined(parameterInfo, attributeType, true)); break; default: Assert.True(false); break; } } [Theory] [MemberData(nameof(TestData_AttributeExists))] [MemberData(nameof(TestData_AttributeDoesNotExist))] public static void GetCustomAttribute(object target, Type attributeType, Attribute attribute) { switch (target) { case Type type: Assert.Equal(attribute, Attribute.GetCustomAttribute(type, attributeType)); Assert.Equal(attribute, Attribute.GetCustomAttribute(type, attributeType, true)); break; case MemberInfo memberInfo: Assert.Equal(attribute, Attribute.GetCustomAttribute(memberInfo, attributeType)); Assert.Equal(attribute, Attribute.GetCustomAttribute(memberInfo, attributeType, true)); break; case ParameterInfo parameterInfo: Assert.Equal(attribute, Attribute.GetCustomAttribute(parameterInfo, attributeType)); Assert.Equal(attribute, Attribute.GetCustomAttribute(parameterInfo, attributeType, true)); break; default: Assert.True(false); break; } } [Theory] [MemberData(nameof(TestData_AttributeExists))] [MemberData(nameof(TestData_AttributeDoesNotExist))] public static void GetCustomAttributes(object target, Type attributeType, Attribute attribute) { switch (target) { case Type type: Assert.Equal(attribute, Attribute.GetCustomAttributes(type, typeof(Attribute)) .Where((e) => e.GetType() == attributeType).SingleOrDefault()); Assert.Equal(attribute, Attribute.GetCustomAttributes(type, typeof(Attribute), true) .Where((e) => e.GetType() == attributeType).SingleOrDefault()); break; case MemberInfo memberInfo: Assert.Equal(attribute, Attribute.GetCustomAttributes(memberInfo, typeof(Attribute)) .Where((e) => e.GetType() == attributeType).SingleOrDefault()); Assert.Equal(attribute, Attribute.GetCustomAttributes(memberInfo, typeof(Attribute), true) .Where((e) => e.GetType() == attributeType).SingleOrDefault()); break; case ParameterInfo parameterInfo: Assert.Equal(attribute, Attribute.GetCustomAttributes(parameterInfo, typeof(Attribute)) .Where((e) => e.GetType() == attributeType).SingleOrDefault()); Assert.Equal(attribute, Attribute.GetCustomAttributes(parameterInfo, typeof(Attribute), true) .Where((e) => e.GetType() == attributeType).SingleOrDefault()); break; default: Assert.True(false); break; } } public static IEnumerable<object[]> TestData_AttributeExists() { yield return new object[] { typeof(TestTypeWithAttributes), typeof(SerializableAttribute), new SerializableAttribute() }; yield return new object[] { typeof(ITestComInterface), typeof(ComImportAttribute), new ComImportAttribute() }; FieldInfo testField = typeof(TestTypeWithAttributes).GetField("_testField"); yield return new object[] { testField, typeof(FieldOffsetAttribute), new FieldOffsetAttribute(120) }; yield return new object[] { testField, typeof(NonSerializedAttribute), new NonSerializedAttribute() }; yield return new object[] { testField, typeof(MarshalAsAttribute), new MarshalAsAttribute(UnmanagedType.ByValTStr) { SizeConst = 100 } }; MethodInfo testMethod = typeof(TestTypeWithAttributes).GetMethod("TestMethod"); ParameterInfo testMethodParameter = testMethod.GetParameters()[0]; yield return new object[] { testMethodParameter, typeof(MarshalAsAttribute), new MarshalAsAttribute(UnmanagedType.LPArray) { ArraySubType = UnmanagedType.I4 } }; yield return new object[] { testMethodParameter, typeof(InAttribute), new InAttribute() }; yield return new object[] { testMethodParameter, typeof(OutAttribute), new OutAttribute() }; yield return new object[] { testMethodParameter, typeof(OptionalAttribute), new OptionalAttribute() }; yield return new object[] { testMethod.ReturnParameter, typeof(MarshalAsAttribute), new MarshalAsAttribute(UnmanagedType.Bool) }; yield return new object[] { testMethod, typeof(DllImportAttribute), new DllImportAttribute("nonexistent") { CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = true, EntryPoint = "MyEntryPoint" } }; yield return new object[] { testMethod, typeof(PreserveSigAttribute), new PreserveSigAttribute() }; } public static IEnumerable<object[]> TestData_AttributeDoesNotExist() { yield return new object[] { typeof(TestTypeWithoutAttributes), typeof(SerializableAttribute), null }; yield return new object[] { typeof(TestTypeWithoutAttributes), typeof(ComImportAttribute), null }; FieldInfo testField = typeof(TestTypeWithoutAttributes).GetField("_testField"); yield return new object[] { testField, typeof(FieldOffsetAttribute), null }; yield return new object[] { testField, typeof(NonSerializedAttribute), null }; yield return new object[] { testField, typeof(MarshalAsAttribute), null }; MethodInfo testMethod = typeof(TestTypeWithoutAttributes).GetMethod("TestMethod"); ParameterInfo testMethodParameter = testMethod.GetParameters()[0]; yield return new object[] { testMethodParameter, typeof(MarshalAsAttribute), null }; yield return new object[] { testMethodParameter, typeof(InAttribute), null }; yield return new object[] { testMethodParameter, typeof(OutAttribute), null }; yield return new object[] { testMethodParameter, typeof(OptionalAttribute), null }; yield return new object[] { testMethod.ReturnParameter, typeof(MarshalAsAttribute), null }; yield return new object[] { testMethod, typeof(DllImportAttribute), null }; yield return new object[] { testMethod, typeof(PreserveSigAttribute), null }; } [SerializableAttribute] [StructLayoutAttribute(LayoutKind.Explicit)] public class TestTypeWithAttributes { [FieldOffsetAttribute(120)] [NonSerializedAttribute] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)] public string _testField; [PreserveSigAttribute] [return: MarshalAsAttribute(UnmanagedType.Bool)] [DllImportAttribute("nonexistent", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = true, EntryPoint = "MyEntryPoint")] public static extern bool TestMethod([MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I4), In, Out, Optional] int[] x); } public class TestTypeWithoutAttributes { public string _testField; public static bool TestMethod(int[] x) => false; } [ComImport] [Guid("42424242-4242-4242-4242-424242424242"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface ITestComInterface { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization; using Xunit; namespace System.Tests { [ActiveIssue("https://github.com/dotnet/runtimelab/issues/830", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))] public static partial class PseudoCustomAttributeTests { [Theory] [MemberData(nameof(TestData_AttributeExists))] [MemberData(nameof(TestData_AttributeDoesNotExist))] public static void IsDefined(object target, Type attributeType, Attribute attribute) { switch (target) { case Type type: Assert.Equal(attribute != null, Attribute.IsDefined(type, attributeType)); Assert.Equal(attribute != null, Attribute.IsDefined(type, attributeType, true)); break; case MemberInfo memberInfo: Assert.Equal(attribute != null, Attribute.IsDefined(memberInfo, attributeType)); Assert.Equal(attribute != null, Attribute.IsDefined(memberInfo, attributeType, true)); break; case ParameterInfo parameterInfo: Assert.Equal(attribute != null, Attribute.IsDefined(parameterInfo, attributeType)); Assert.Equal(attribute != null, Attribute.IsDefined(parameterInfo, attributeType, true)); break; default: Assert.True(false); break; } } [Theory] [MemberData(nameof(TestData_AttributeExists))] [MemberData(nameof(TestData_AttributeDoesNotExist))] public static void GetCustomAttribute(object target, Type attributeType, Attribute attribute) { switch (target) { case Type type: Assert.Equal(attribute, Attribute.GetCustomAttribute(type, attributeType)); Assert.Equal(attribute, Attribute.GetCustomAttribute(type, attributeType, true)); break; case MemberInfo memberInfo: Assert.Equal(attribute, Attribute.GetCustomAttribute(memberInfo, attributeType)); Assert.Equal(attribute, Attribute.GetCustomAttribute(memberInfo, attributeType, true)); break; case ParameterInfo parameterInfo: Assert.Equal(attribute, Attribute.GetCustomAttribute(parameterInfo, attributeType)); Assert.Equal(attribute, Attribute.GetCustomAttribute(parameterInfo, attributeType, true)); break; default: Assert.True(false); break; } } [Theory] [MemberData(nameof(TestData_AttributeExists))] [MemberData(nameof(TestData_AttributeDoesNotExist))] public static void GetCustomAttributes(object target, Type attributeType, Attribute attribute) { switch (target) { case Type type: Assert.Equal(attribute, Attribute.GetCustomAttributes(type, typeof(Attribute)) .Where((e) => e.GetType() == attributeType).SingleOrDefault()); Assert.Equal(attribute, Attribute.GetCustomAttributes(type, typeof(Attribute), true) .Where((e) => e.GetType() == attributeType).SingleOrDefault()); break; case MemberInfo memberInfo: Assert.Equal(attribute, Attribute.GetCustomAttributes(memberInfo, typeof(Attribute)) .Where((e) => e.GetType() == attributeType).SingleOrDefault()); Assert.Equal(attribute, Attribute.GetCustomAttributes(memberInfo, typeof(Attribute), true) .Where((e) => e.GetType() == attributeType).SingleOrDefault()); break; case ParameterInfo parameterInfo: Assert.Equal(attribute, Attribute.GetCustomAttributes(parameterInfo, typeof(Attribute)) .Where((e) => e.GetType() == attributeType).SingleOrDefault()); Assert.Equal(attribute, Attribute.GetCustomAttributes(parameterInfo, typeof(Attribute), true) .Where((e) => e.GetType() == attributeType).SingleOrDefault()); break; default: Assert.True(false); break; } } public static IEnumerable<object[]> TestData_AttributeExists() { yield return new object[] { typeof(TestTypeWithAttributes), typeof(SerializableAttribute), new SerializableAttribute() }; yield return new object[] { typeof(ITestComInterface), typeof(ComImportAttribute), new ComImportAttribute() }; FieldInfo testField = typeof(TestTypeWithAttributes).GetField("_testField"); yield return new object[] { testField, typeof(FieldOffsetAttribute), new FieldOffsetAttribute(120) }; yield return new object[] { testField, typeof(NonSerializedAttribute), new NonSerializedAttribute() }; yield return new object[] { testField, typeof(MarshalAsAttribute), new MarshalAsAttribute(UnmanagedType.ByValTStr) { SizeConst = 100 } }; MethodInfo testMethod = typeof(TestTypeWithAttributes).GetMethod("TestMethod"); ParameterInfo testMethodParameter = testMethod.GetParameters()[0]; yield return new object[] { testMethodParameter, typeof(MarshalAsAttribute), new MarshalAsAttribute(UnmanagedType.LPArray) { ArraySubType = UnmanagedType.I4 } }; yield return new object[] { testMethodParameter, typeof(InAttribute), new InAttribute() }; yield return new object[] { testMethodParameter, typeof(OutAttribute), new OutAttribute() }; yield return new object[] { testMethodParameter, typeof(OptionalAttribute), new OptionalAttribute() }; yield return new object[] { testMethod.ReturnParameter, typeof(MarshalAsAttribute), new MarshalAsAttribute(UnmanagedType.Bool) }; yield return new object[] { testMethod, typeof(DllImportAttribute), new DllImportAttribute("nonexistent") { CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = true, EntryPoint = "MyEntryPoint" } }; yield return new object[] { testMethod, typeof(PreserveSigAttribute), new PreserveSigAttribute() }; } public static IEnumerable<object[]> TestData_AttributeDoesNotExist() { yield return new object[] { typeof(TestTypeWithoutAttributes), typeof(SerializableAttribute), null }; yield return new object[] { typeof(TestTypeWithoutAttributes), typeof(ComImportAttribute), null }; FieldInfo testField = typeof(TestTypeWithoutAttributes).GetField("_testField"); yield return new object[] { testField, typeof(FieldOffsetAttribute), null }; yield return new object[] { testField, typeof(NonSerializedAttribute), null }; yield return new object[] { testField, typeof(MarshalAsAttribute), null }; MethodInfo testMethod = typeof(TestTypeWithoutAttributes).GetMethod("TestMethod"); ParameterInfo testMethodParameter = testMethod.GetParameters()[0]; yield return new object[] { testMethodParameter, typeof(MarshalAsAttribute), null }; yield return new object[] { testMethodParameter, typeof(InAttribute), null }; yield return new object[] { testMethodParameter, typeof(OutAttribute), null }; yield return new object[] { testMethodParameter, typeof(OptionalAttribute), null }; yield return new object[] { testMethod.ReturnParameter, typeof(MarshalAsAttribute), null }; yield return new object[] { testMethod, typeof(DllImportAttribute), null }; yield return new object[] { testMethod, typeof(PreserveSigAttribute), null }; } [SerializableAttribute] [StructLayoutAttribute(LayoutKind.Explicit)] public class TestTypeWithAttributes { [FieldOffsetAttribute(120)] [NonSerializedAttribute] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)] public string _testField; [PreserveSigAttribute] [return: MarshalAsAttribute(UnmanagedType.Bool)] [DllImportAttribute("nonexistent", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = true, EntryPoint = "MyEntryPoint")] public static extern bool TestMethod([MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I4), In, Out, Optional] int[] x); } public class TestTypeWithoutAttributes { public string _testField; public static bool TestMethod(int[] x) => false; } [ComImport] [Guid("42424242-4242-4242-4242-424242424242"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface ITestComInterface { } } }
-1
dotnet/runtime
66,193
Add xarch `blsi`
This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
Wraith2
2022-03-04T13:44:46Z
2022-03-15T00:53:39Z
436b97cc809a3db1d1a25faedbc64aa97875bae3
6bf873a991bcae3f80f5de155a594cefc8824eea
Add xarch `blsi`. This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest459/Generated459.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated459 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public sequential sealed MyStruct509`2<T0, T1> extends [mscorlib]System.ValueType implements class IBase2`2<class BaseClass1,class BaseClass1>, class IBase2`2<!T1,class BaseClass1> { .pack 0 .size 1 .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "MyStruct509::Method7.3952<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase2<class BaseClass1,class BaseClass1>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<[1]>() ldstr "MyStruct509::Method7.MI.3953<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase2<T1,class BaseClass1>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<!T1,class BaseClass1>::Method7<[1]>() ldstr "MyStruct509::Method7.MI.3955<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance bool Equals(object obj) cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance int32 GetHashCode() cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance string ToString() cil managed { ldstr "" ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated459 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct509.T.T<T0,T1,(valuetype MyStruct509`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct509.T.T<T0,T1,(valuetype MyStruct509`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct509`2<!!T0,!!T1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct509`2<!!T0,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct509.A.T<T1,(valuetype MyStruct509`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct509.A.T<T1,(valuetype MyStruct509`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct509`2<class BaseClass0,!!T1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct509`2<class BaseClass0,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct509.A.A<(valuetype MyStruct509`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct509.A.A<(valuetype MyStruct509`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct509`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct509`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct509.B.T<T1,(valuetype MyStruct509`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct509.B.T<T1,(valuetype MyStruct509`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct509`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct509`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct509.B.A<(valuetype MyStruct509`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct509.B.A<(valuetype MyStruct509`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct509`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct509`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct509`2<class BaseClass0,class BaseClass0> V_1) ldloca V_1 initobj valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldloca V_1 dup call instance string valuetype MyStruct509`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct509::Method7.3952<System.Object>()" ldstr "valuetype MyStruct509`2<class BaseClass0,class BaseClass0> on type MyStruct509" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct509`2<class BaseClass0,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct509`2<class BaseClass0,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct509`2<class BaseClass0,class BaseClass0>::ToString() pop pop ldloc V_1 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct509::Method7.MI.3953<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct509`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct509::Method7.MI.3955<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct509`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct509`2<class BaseClass1,class BaseClass0> V_3) ldloca V_3 initobj valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldloca V_3 dup call instance string valuetype MyStruct509`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct509::Method7.3952<System.Object>()" ldstr "valuetype MyStruct509`2<class BaseClass1,class BaseClass0> on type MyStruct509" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct509`2<class BaseClass1,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct509`2<class BaseClass1,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct509`2<class BaseClass1,class BaseClass0>::ToString() pop pop ldloc V_3 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct509::Method7.MI.3953<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct509`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct509::Method7.MI.3955<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct509`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct509`2<class BaseClass0,class BaseClass0> V_5) ldloca V_5 initobj valuetype MyStruct509`2<class BaseClass0,class BaseClass0> .try { ldloc V_5 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" call void Generated459::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_5 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" call void Generated459::M.IBase2.B.T<class BaseClass1,valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_5 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" call void Generated459::M.IBase2.B.B<valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_5 ldstr "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_5 ldstr "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.IBase2.A.T<class BaseClass1,valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_5 ldstr "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.IBase2.A.B<valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .locals init (valuetype MyStruct509`2<class BaseClass1,class BaseClass0> V_7) ldloca V_7 initobj valuetype MyStruct509`2<class BaseClass1,class BaseClass0> .try { ldloc V_7 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" call void Generated459::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_7 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" call void Generated459::M.IBase2.B.T<class BaseClass1,valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_7 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" call void Generated459::M.IBase2.B.B<valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .try { ldloc V_7 ldstr "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_7 ldstr "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.IBase2.A.T<class BaseClass1,valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_7 ldstr "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.IBase2.A.B<valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct509`2<class BaseClass0,class BaseClass0> V_9) ldloca V_9 initobj valuetype MyStruct509`2<class BaseClass0,class BaseClass0> .try { ldloc V_9 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" + "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.MyStruct509.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_9 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" + "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.MyStruct509.A.T<class BaseClass0,valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_9 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" + "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.MyStruct509.A.A<valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .locals init (valuetype MyStruct509`2<class BaseClass1,class BaseClass0> V_11) ldloca V_11 initobj valuetype MyStruct509`2<class BaseClass1,class BaseClass0> .try { ldloc V_11 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" + "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.MyStruct509.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_11 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" + "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.MyStruct509.B.T<class BaseClass0,valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_11 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" + "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.MyStruct509.B.A<valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct509`2<class BaseClass0,class BaseClass0> V_13) ldloca V_13 initobj valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct509`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct509::Method7.3952<System.Object>()" ldstr "valuetype MyStruct509`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct509`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldnull ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldvirtftn instance bool valuetype MyStruct509`2<class BaseClass0,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct509`2<class BaseClass0,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct509`2<class BaseClass0,class BaseClass0>::ToString() calli default string(object) pop ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct509::Method7.MI.3953<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct509`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct509::Method7.MI.3955<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct509`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct509`2<class BaseClass1,class BaseClass0> V_15) ldloca V_15 initobj valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct509`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct509::Method7.3952<System.Object>()" ldstr "valuetype MyStruct509`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct509`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldnull ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldvirtftn instance bool valuetype MyStruct509`2<class BaseClass1,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct509`2<class BaseClass1,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct509`2<class BaseClass1,class BaseClass0>::ToString() calli default string(object) pop ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct509::Method7.MI.3953<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct509`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct509::Method7.MI.3955<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct509`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated459::MethodCallingTest() call void Generated459::ConstrainedCallsTest() call void Generated459::StructConstrainedInterfaceCallsTest() call void Generated459::CalliTest() ldc.i4 100 ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated459 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public sequential sealed MyStruct509`2<T0, T1> extends [mscorlib]System.ValueType implements class IBase2`2<class BaseClass1,class BaseClass1>, class IBase2`2<!T1,class BaseClass1> { .pack 0 .size 1 .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "MyStruct509::Method7.3952<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase2<class BaseClass1,class BaseClass1>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<[1]>() ldstr "MyStruct509::Method7.MI.3953<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase2<T1,class BaseClass1>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<!T1,class BaseClass1>::Method7<[1]>() ldstr "MyStruct509::Method7.MI.3955<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance bool Equals(object obj) cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance int32 GetHashCode() cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance string ToString() cil managed { ldstr "" ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated459 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct509.T.T<T0,T1,(valuetype MyStruct509`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct509.T.T<T0,T1,(valuetype MyStruct509`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct509`2<!!T0,!!T1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct509`2<!!T0,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct509.A.T<T1,(valuetype MyStruct509`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct509.A.T<T1,(valuetype MyStruct509`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct509`2<class BaseClass0,!!T1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct509`2<class BaseClass0,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct509.A.A<(valuetype MyStruct509`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct509.A.A<(valuetype MyStruct509`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct509`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct509`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct509.B.T<T1,(valuetype MyStruct509`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct509.B.T<T1,(valuetype MyStruct509`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct509`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct509`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct509.B.A<(valuetype MyStruct509`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct509.B.A<(valuetype MyStruct509`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct509`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct509`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct509`2<class BaseClass0,class BaseClass0> V_1) ldloca V_1 initobj valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldloca V_1 dup call instance string valuetype MyStruct509`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct509::Method7.3952<System.Object>()" ldstr "valuetype MyStruct509`2<class BaseClass0,class BaseClass0> on type MyStruct509" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct509`2<class BaseClass0,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct509`2<class BaseClass0,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct509`2<class BaseClass0,class BaseClass0>::ToString() pop pop ldloc V_1 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct509::Method7.MI.3953<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct509`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct509::Method7.MI.3955<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct509`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct509`2<class BaseClass1,class BaseClass0> V_3) ldloca V_3 initobj valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldloca V_3 dup call instance string valuetype MyStruct509`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct509::Method7.3952<System.Object>()" ldstr "valuetype MyStruct509`2<class BaseClass1,class BaseClass0> on type MyStruct509" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct509`2<class BaseClass1,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct509`2<class BaseClass1,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct509`2<class BaseClass1,class BaseClass0>::ToString() pop pop ldloc V_3 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct509::Method7.MI.3953<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct509`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct509::Method7.MI.3955<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct509`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct509`2<class BaseClass0,class BaseClass0> V_5) ldloca V_5 initobj valuetype MyStruct509`2<class BaseClass0,class BaseClass0> .try { ldloc V_5 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" call void Generated459::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_5 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" call void Generated459::M.IBase2.B.T<class BaseClass1,valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_5 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" call void Generated459::M.IBase2.B.B<valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_5 ldstr "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_5 ldstr "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.IBase2.A.T<class BaseClass1,valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_5 ldstr "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.IBase2.A.B<valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .locals init (valuetype MyStruct509`2<class BaseClass1,class BaseClass0> V_7) ldloca V_7 initobj valuetype MyStruct509`2<class BaseClass1,class BaseClass0> .try { ldloc V_7 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" call void Generated459::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_7 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" call void Generated459::M.IBase2.B.T<class BaseClass1,valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_7 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" call void Generated459::M.IBase2.B.B<valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .try { ldloc V_7 ldstr "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_7 ldstr "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.IBase2.A.T<class BaseClass1,valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_7 ldstr "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.IBase2.A.B<valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct509`2<class BaseClass0,class BaseClass0> V_9) ldloca V_9 initobj valuetype MyStruct509`2<class BaseClass0,class BaseClass0> .try { ldloc V_9 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" + "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.MyStruct509.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_9 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" + "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.MyStruct509.A.T<class BaseClass0,valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_9 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" + "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.MyStruct509.A.A<valuetype MyStruct509`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .locals init (valuetype MyStruct509`2<class BaseClass1,class BaseClass0> V_11) ldloca V_11 initobj valuetype MyStruct509`2<class BaseClass1,class BaseClass0> .try { ldloc V_11 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" + "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.MyStruct509.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_11 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" + "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.MyStruct509.B.T<class BaseClass0,valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_11 ldstr "MyStruct509::Method7.MI.3953<System.Object>()#" + "MyStruct509::Method7.MI.3955<System.Object>()#" call void Generated459::M.MyStruct509.B.A<valuetype MyStruct509`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct509`2<class BaseClass0,class BaseClass0> V_13) ldloca V_13 initobj valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct509`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct509::Method7.3952<System.Object>()" ldstr "valuetype MyStruct509`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct509`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldnull ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldvirtftn instance bool valuetype MyStruct509`2<class BaseClass0,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct509`2<class BaseClass0,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct509`2<class BaseClass0,class BaseClass0>::ToString() calli default string(object) pop ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct509::Method7.MI.3953<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct509`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct509`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct509::Method7.MI.3955<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct509`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct509`2<class BaseClass1,class BaseClass0> V_15) ldloca V_15 initobj valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct509`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct509::Method7.3952<System.Object>()" ldstr "valuetype MyStruct509`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct509`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldnull ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldvirtftn instance bool valuetype MyStruct509`2<class BaseClass1,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct509`2<class BaseClass1,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct509`2<class BaseClass1,class BaseClass0>::ToString() calli default string(object) pop ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct509::Method7.MI.3953<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct509`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct509`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct509::Method7.MI.3955<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct509`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated459::MethodCallingTest() call void Generated459::ConstrainedCallsTest() call void Generated459::StructConstrainedInterfaceCallsTest() call void Generated459::CalliTest() ldc.i4 100 ret } }
-1
dotnet/runtime
66,193
Add xarch `blsi`
This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
Wraith2
2022-03-04T13:44:46Z
2022-03-15T00:53:39Z
436b97cc809a3db1d1a25faedbc64aa97875bae3
6bf873a991bcae3f80f5de155a594cefc8824eea
Add xarch `blsi`. This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
./src/libraries/System.Net.Http/tests/FunctionalTests/HttpConnectionKeyTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Xunit; namespace System.Net.Http.Functional.Tests { [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))] public class HttpConnectionKeyTest { public static IEnumerable<object[]> KeyComponents() { yield return new object[] { "Https", "localhost", 80, "localhost-ssl", new Uri("http://localhost"), "domain1/userA", false}; yield return new object[] { "Http", "localhost1", 80, "localhost-ssl", new Uri("http://localhost"), "domain1/userA", false }; yield return new object[] { "Http", "localhost", 81, "localhost-ssl", new Uri("http://localhost"), "domain1/userA", false }; yield return new object[] { "Http", "localhost", 80, "localhost-ssl1", new Uri("http://localhost"), "domain1/userA", false }; yield return new object[] { "Http", "localhost", 80, "localhost-ssl", new Uri("http://localhost1"), "domain1/userA", false }; yield return new object[] { "Http", "localhost", 80, "localhost-ssl", new Uri("http://localhost"), "domain1/userB", false }; yield return new object[] { "Http", "localhost", 80, "localhost-ssl", new Uri("http://localhost"), "domain1/userA", true }; } [Theory, MemberData(nameof(KeyComponents))] public void Equals_DifferentParameters_ReturnsTrueIfAllEqual(string kindString, string host, int port, string sslHostName, Uri proxyUri, string identity, bool expected) { Assembly assembly = typeof(HttpClientHandler).Assembly; Type connectionKindType = assembly.GetTypes().Where(t => t.Name == "HttpConnectionKind").First(); Type poolManagerType = assembly.GetTypes().Where(t => t.Name == "HttpConnectionPoolManager").First(); Type keyType = poolManagerType.GetNestedType("HttpConnectionKey", BindingFlags.NonPublic); dynamic referenceKey = Activator.CreateInstance(keyType, Enum.Parse(connectionKindType, "Http"), "localhost", 80, "localhost-ssl", new Uri("http://localhost"), "domain1/userA"); dynamic actualKey = Activator.CreateInstance(keyType, Enum.Parse(connectionKindType, kindString), host, port, sslHostName, proxyUri, identity); Assert.Equal(expected, referenceKey.Equals(actualKey)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Xunit; namespace System.Net.Http.Functional.Tests { [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))] public class HttpConnectionKeyTest { public static IEnumerable<object[]> KeyComponents() { yield return new object[] { "Https", "localhost", 80, "localhost-ssl", new Uri("http://localhost"), "domain1/userA", false}; yield return new object[] { "Http", "localhost1", 80, "localhost-ssl", new Uri("http://localhost"), "domain1/userA", false }; yield return new object[] { "Http", "localhost", 81, "localhost-ssl", new Uri("http://localhost"), "domain1/userA", false }; yield return new object[] { "Http", "localhost", 80, "localhost-ssl1", new Uri("http://localhost"), "domain1/userA", false }; yield return new object[] { "Http", "localhost", 80, "localhost-ssl", new Uri("http://localhost1"), "domain1/userA", false }; yield return new object[] { "Http", "localhost", 80, "localhost-ssl", new Uri("http://localhost"), "domain1/userB", false }; yield return new object[] { "Http", "localhost", 80, "localhost-ssl", new Uri("http://localhost"), "domain1/userA", true }; } [Theory, MemberData(nameof(KeyComponents))] public void Equals_DifferentParameters_ReturnsTrueIfAllEqual(string kindString, string host, int port, string sslHostName, Uri proxyUri, string identity, bool expected) { Assembly assembly = typeof(HttpClientHandler).Assembly; Type connectionKindType = assembly.GetTypes().Where(t => t.Name == "HttpConnectionKind").First(); Type poolManagerType = assembly.GetTypes().Where(t => t.Name == "HttpConnectionPoolManager").First(); Type keyType = poolManagerType.GetNestedType("HttpConnectionKey", BindingFlags.NonPublic); dynamic referenceKey = Activator.CreateInstance(keyType, Enum.Parse(connectionKindType, "Http"), "localhost", 80, "localhost-ssl", new Uri("http://localhost"), "domain1/userA"); dynamic actualKey = Activator.CreateInstance(keyType, Enum.Parse(connectionKindType, kindString), host, port, sslHostName, proxyUri, identity); Assert.Equal(expected, referenceKey.Equals(actualKey)); } } }
-1
dotnet/runtime
66,193
Add xarch `blsi`
This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
Wraith2
2022-03-04T13:44:46Z
2022-03-15T00:53:39Z
436b97cc809a3db1d1a25faedbc64aa97875bae3
6bf873a991bcae3f80f5de155a594cefc8824eea
Add xarch `blsi`. This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
./src/tests/JIT/Directed/debugging/poisoning/poison.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <DebugType>PdbOnly</DebugType> <Optimize>False</Optimize> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <DebugType>PdbOnly</DebugType> <Optimize>False</Optimize> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,193
Add xarch `blsi`
This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
Wraith2
2022-03-04T13:44:46Z
2022-03-15T00:53:39Z
436b97cc809a3db1d1a25faedbc64aa97875bae3
6bf873a991bcae3f80f5de155a594cefc8824eea
Add xarch `blsi`. This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
./src/tests/JIT/Regression/CLR-x86-JIT/V1-QFE/b147814/rembug.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly rembug {} .method public static unmanagedexp int32 modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) main() cil managed { .entrypoint .maxstack 3 .locals (int32* V_0, int32 V_1) ldloca.s V_1 stloc.0 ldloc.0 ldloc.0 ldind.i4 ldc.i4 0x80000000 rem stind.i4 ldc.i4 100 ret }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly rembug {} .method public static unmanagedexp int32 modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) main() cil managed { .entrypoint .maxstack 3 .locals (int32* V_0, int32 V_1) ldloca.s V_1 stloc.0 ldloc.0 ldloc.0 ldind.i4 ldc.i4 0x80000000 rem stind.i4 ldc.i4 100 ret }
-1
dotnet/runtime
66,193
Add xarch `blsi`
This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
Wraith2
2022-03-04T13:44:46Z
2022-03-15T00:53:39Z
436b97cc809a3db1d1a25faedbc64aa97875bae3
6bf873a991bcae3f80f5de155a594cefc8824eea
Add xarch `blsi`. This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
./src/installer/pkg/sfx/bundle/osx_resources/tr.lproj/eula.rtf
{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}} {\*\generator Riched20 10.0.15063}\viewkind4\uc1 \pard\sa200\sl276\slmult1\f0\fs22\lang9 The MIT License (MIT)\par Copyright (c) 2015 .NET Foundation\par Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\par The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\par THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\par }
{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}} {\*\generator Riched20 10.0.15063}\viewkind4\uc1 \pard\sa200\sl276\slmult1\f0\fs22\lang9 The MIT License (MIT)\par Copyright (c) 2015 .NET Foundation\par Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\par The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\par THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\par }
-1
dotnet/runtime
66,193
Add xarch `blsi`
This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
Wraith2
2022-03-04T13:44:46Z
2022-03-15T00:53:39Z
436b97cc809a3db1d1a25faedbc64aa97875bae3
6bf873a991bcae3f80f5de155a594cefc8824eea
Add xarch `blsi`. This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
./src/tests/baseservices/exceptions/regressions/V1/SEH/asm/NestedExcept.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="NestedExcept.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="NestedExcept.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,193
Add xarch `blsi`
This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
Wraith2
2022-03-04T13:44:46Z
2022-03-15T00:53:39Z
436b97cc809a3db1d1a25faedbc64aa97875bae3
6bf873a991bcae3f80f5de155a594cefc8824eea
Add xarch `blsi`. This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
./src/coreclr/inc/CMakeLists.txt
set( CORGUIDS_IDL_SOURCES cordebug.idl xcordebug.idl clrdata.idl clrinternal.idl xclrdata.idl corprof.idl corpub.idl corsym.idl sospriv.idl ) if(CLR_CMAKE_HOST_WIN32) #Build for corguids is done in two steps: #1. compile .idl to *_i.c : This is done using custom midl command #2. compile *_i.c to .lib # Get the current list of definitions to pass to midl get_compile_definitions(MIDL_DEFINITIONS) get_include_directories(MIDL_INCLUDE_DIRECTORIES) # Run custom midl command over each idl file FIND_PROGRAM( MIDL midl.exe ) foreach(GENERATE_IDL IN LISTS CORGUIDS_IDL_SOURCES) get_filename_component(IDLNAME ${GENERATE_IDL} NAME_WE) set(OUT_NAME ${CMAKE_CURRENT_BINARY_DIR}/idls_out/${IDLNAME}_i.c) list(APPEND CORGUIDS_SOURCES ${OUT_NAME}) add_custom_command(OUTPUT ${OUT_NAME} COMMAND ${MIDL} ${MIDL_INCLUDE_DIRECTORIES} /no_stamp /h ${CMAKE_CURRENT_BINARY_DIR}/idls_out/${IDLNAME}.h ${MIDL_DEFINITIONS} /out ${CMAKE_CURRENT_BINARY_DIR}/idls_out ${CMAKE_CURRENT_SOURCE_DIR}/${GENERATE_IDL} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${GENERATE_IDL} COMMENT "Compiling ${GENERATE_IDL}") endforeach(GENERATE_IDL) set_source_files_properties(${CORGUIDS_SOURCES} PROPERTIES GENERATED TRUE) # Compile *_i.c as C files add_compile_options(/TC) else(CLR_CMAKE_HOST_WIN32) #The MIDL tool exists for Windows only, so for other systems, we have the prebuilt xxx_i.cpp files checked in add_compile_options(-D_MIDL_USE_GUIDDEF_) foreach(IDL_SOURCE IN LISTS CORGUIDS_IDL_SOURCES) get_filename_component(IDLNAME ${IDL_SOURCE} NAME_WE) set(C_SOURCE ../pal/prebuilt/idl/${IDLNAME}_i.cpp) list(APPEND CORGUIDS_SOURCES ${C_SOURCE}) endforeach(IDL_SOURCE) endif(CLR_CMAKE_HOST_WIN32) if(FEATURE_JIT_PITCHING) add_definitions(-DFEATURE_JIT_PITCHING) endif(FEATURE_JIT_PITCHING) # Compile *_i.cpp to lib add_library_clr(corguids_obj OBJECT ${CORGUIDS_SOURCES}) add_library(corguids INTERFACE) target_sources(corguids INTERFACE $<TARGET_OBJECTS:corguids_obj>) # Binplace the inc files for packaging later. install (FILES cfi.h cor.h cordebuginfo.h coredistools.h corhdr.h corinfo.h corjit.h corjithost.h opcode.def openum.h gcinfoencoder.h gcinfotypes.h DESTINATION inc)
set( CORGUIDS_IDL_SOURCES cordebug.idl xcordebug.idl clrdata.idl clrinternal.idl xclrdata.idl corprof.idl corpub.idl corsym.idl sospriv.idl ) if(CLR_CMAKE_HOST_WIN32) #Build for corguids is done in two steps: #1. compile .idl to *_i.c : This is done using custom midl command #2. compile *_i.c to .lib # Get the current list of definitions to pass to midl get_compile_definitions(MIDL_DEFINITIONS) get_include_directories(MIDL_INCLUDE_DIRECTORIES) # Run custom midl command over each idl file FIND_PROGRAM( MIDL midl.exe ) foreach(GENERATE_IDL IN LISTS CORGUIDS_IDL_SOURCES) get_filename_component(IDLNAME ${GENERATE_IDL} NAME_WE) set(OUT_NAME ${CMAKE_CURRENT_BINARY_DIR}/idls_out/${IDLNAME}_i.c) list(APPEND CORGUIDS_SOURCES ${OUT_NAME}) add_custom_command(OUTPUT ${OUT_NAME} COMMAND ${MIDL} ${MIDL_INCLUDE_DIRECTORIES} /no_stamp /h ${CMAKE_CURRENT_BINARY_DIR}/idls_out/${IDLNAME}.h ${MIDL_DEFINITIONS} /out ${CMAKE_CURRENT_BINARY_DIR}/idls_out ${CMAKE_CURRENT_SOURCE_DIR}/${GENERATE_IDL} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${GENERATE_IDL} COMMENT "Compiling ${GENERATE_IDL}") endforeach(GENERATE_IDL) set_source_files_properties(${CORGUIDS_SOURCES} PROPERTIES GENERATED TRUE) # Compile *_i.c as C files add_compile_options(/TC) else(CLR_CMAKE_HOST_WIN32) #The MIDL tool exists for Windows only, so for other systems, we have the prebuilt xxx_i.cpp files checked in add_compile_options(-D_MIDL_USE_GUIDDEF_) foreach(IDL_SOURCE IN LISTS CORGUIDS_IDL_SOURCES) get_filename_component(IDLNAME ${IDL_SOURCE} NAME_WE) set(C_SOURCE ../pal/prebuilt/idl/${IDLNAME}_i.cpp) list(APPEND CORGUIDS_SOURCES ${C_SOURCE}) endforeach(IDL_SOURCE) endif(CLR_CMAKE_HOST_WIN32) if(FEATURE_JIT_PITCHING) add_definitions(-DFEATURE_JIT_PITCHING) endif(FEATURE_JIT_PITCHING) # Compile *_i.cpp to lib add_library_clr(corguids_obj OBJECT ${CORGUIDS_SOURCES}) add_library(corguids INTERFACE) target_sources(corguids INTERFACE $<TARGET_OBJECTS:corguids_obj>) # Binplace the inc files for packaging later. install (FILES cfi.h cor.h cordebuginfo.h coredistools.h corhdr.h corinfo.h corjit.h corjithost.h opcode.def openum.h gcinfoencoder.h gcinfotypes.h DESTINATION inc)
-1
dotnet/runtime
66,193
Add xarch `blsi`
This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
Wraith2
2022-03-04T13:44:46Z
2022-03-15T00:53:39Z
436b97cc809a3db1d1a25faedbc64aa97875bae3
6bf873a991bcae3f80f5de155a594cefc8824eea
Add xarch `blsi`. This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
./src/libraries/System.Memory/tests/ReadOnlyBuffer/BufferSegment.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; namespace System.Memory.Tests { internal class BufferSegment<T> : ReadOnlySequenceSegment<T> { public BufferSegment(ReadOnlyMemory<T> memory) { Memory = memory; } public BufferSegment<T> Append(ReadOnlyMemory<T> memory) { var segment = new BufferSegment<T>(memory) { RunningIndex = RunningIndex + Memory.Length }; Next = segment; return segment; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; namespace System.Memory.Tests { internal class BufferSegment<T> : ReadOnlySequenceSegment<T> { public BufferSegment(ReadOnlyMemory<T> memory) { Memory = memory; } public BufferSegment<T> Append(ReadOnlyMemory<T> memory) { var segment = new BufferSegment<T>(memory) { RunningIndex = RunningIndex + Memory.Length }; Next = segment; return segment; } } }
-1
dotnet/runtime
66,193
Add xarch `blsi`
This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
Wraith2
2022-03-04T13:44:46Z
2022-03-15T00:53:39Z
436b97cc809a3db1d1a25faedbc64aa97875bae3
6bf873a991bcae3f80f5de155a594cefc8824eea
Add xarch `blsi`. This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
./src/libraries/System.Private.CoreLib/src/System/Threading/SendOrPostCallback.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 delegate void SendOrPostCallback(object? state); }
// 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 delegate void SendOrPostCallback(object? state); }
-1
dotnet/runtime
66,193
Add xarch `blsi`
This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
Wraith2
2022-03-04T13:44:46Z
2022-03-15T00:53:39Z
436b97cc809a3db1d1a25faedbc64aa97875bae3
6bf873a991bcae3f80f5de155a594cefc8824eea
Add xarch `blsi`. This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
./src/libraries/Microsoft.CSharp/src/Resources/Strings.ru.resx
<root> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="InternalCompilerError" xml:space="preserve"> <value>Возникло непредвиденное исключение при выполнении привязки динамической операции</value> </data> <data name="BindRequireArguments" xml:space="preserve"> <value>Невозможно выполнить привязку вызова к невызывающему объекту</value> </data> <data name="BindCallFailedOverloadResolution" xml:space="preserve"> <value>Сбой при разрешении перегрузки</value> </data> <data name="BindBinaryOperatorRequireTwoArguments" xml:space="preserve"> <value>Бинарные операторы должны вызываться с использованием двух аргументов</value> </data> <data name="BindUnaryOperatorRequireOneArgument" xml:space="preserve"> <value>Унарные операторы должны быть вызваны с использованием одного аргумента</value> </data> <data name="BindPropertyFailedMethodGroup" xml:space="preserve"> <value>Для имени "{0}" выполнена привязка к методу. Невозможно использовать его как свойство</value> </data> <data name="BindPropertyFailedEvent" xml:space="preserve"> <value>Событие «{0}» может появляться только на стороне левой руки +</value> </data> <data name="BindInvokeFailedNonDelegate" xml:space="preserve"> <value>Не удалось вызвать тип, не являющийся делегатом</value> </data> <data name="BindBinaryAssignmentRequireTwoArguments" xml:space="preserve"> <value>Невозможно вызвать бинарные операторы с использованием одного аргумента</value> </data> <data name="BindBinaryAssignmentFailedNullReference" xml:space="preserve"> <value>Не удается выполнить присваивание члена по нулевой ссылке</value> </data> <data name="NullReferenceOnMemberException" xml:space="preserve"> <value>Не удается выполнить привязки исполняющей среды по нулевой ссылке</value> </data> <data name="BindCallToConditionalMethod" xml:space="preserve"> <value>Не удается динамически вызвать метод "{0}", так как у него есть условный атрибут</value> </data> <data name="BindToVoidMethodButExpectResult" xml:space="preserve"> <value>Нельзя неявно преобразовать тип "void" to "object"</value> </data> <data name="BadBinaryOps" xml:space="preserve"> <value>Не удается применить оператор "{0}" к операндам типа "{1}" и "{2}"</value> </data> <data name="BadIndexLHS" xml:space="preserve"> <value>Невозможно применить индексирование через [] к выражению типа "{0}"</value> </data> <data name="BadIndexCount" xml:space="preserve"> <value>Неверное количество индексов внутри []; ожидалось "{0}"</value> </data> <data name="BadUnaryOp" xml:space="preserve"> <value>Не удается применить операнд "{0}" типа "{1}"</value> </data> <data name="NoImplicitConv" xml:space="preserve"> <value>Не удается неявно преобразовать тип "{0}" в "{1}"</value> </data> <data name="NoExplicitConv" xml:space="preserve"> <value>Невозможно преобразовать тип "{0}" в "{1}"</value> </data> <data name="ConstOutOfRange" xml:space="preserve"> <value>Постоянное значение "{0}" не может быть преобразовано в "{1}"</value> </data> <data name="AmbigBinaryOps" xml:space="preserve"> <value>Оператор "{0}" является неоднозначным по отношению к операндам типа "{1}" и "{2}"</value> </data> <data name="AmbigUnaryOp" xml:space="preserve"> <value>Оператор "{0}" является неоднозначным по отношению к операнду типа "{1}"</value> </data> <data name="ValueCantBeNull" xml:space="preserve"> <value>Cannot convert null to "{0}" because it is a non-nullable value type</value> </data> <data name="NoSuchMember" xml:space="preserve"> <value>"{0}" не содержит определения для "{1}"</value> </data> <data name="ObjectRequired" xml:space="preserve"> <value>Для нестатического поля, метода или свойства "{0}" требуется ссылка на объект</value> </data> <data name="AmbigCall" xml:space="preserve"> <value>Понятие "вызов" трактуется неоднозначно в следующих методах или свойствах: "{0}" и "{1}"</value> </data> <data name="BadAccess" xml:space="preserve"> <value>"{0}" недоступен из-за его уровня защиты</value> </data> <data name="MethDelegateMismatch" xml:space="preserve"> <value>Нет перегрузки для "{0}", соответствующей делегату "{1}"</value> </data> <data name="AssgLvalueExpected" xml:space="preserve"> <value>Левая часть выражения присваивания должна быть переменной, свойством или индексатором</value> </data> <data name="NoConstructors" xml:space="preserve"> <value>Для типа "{0}" нет определенных конструкторов</value> </data> <data name="PropertyLacksGet" xml:space="preserve"> <value>The property or indexer "{0}" cannot be used in this context because it lacks the get accessor</value> </data> <data name="ObjectProhibited" xml:space="preserve"> <value>Доступ к члену "{0}" через ссылку на экземпляр невозможен; вместо этого уточните его, указав имя типа</value> </data> <data name="AssgReadonly" xml:space="preserve"> <value>Присваивание значений доступному только для чтения полю допускается только в конструкторе и в инициализаторе переменных</value> </data> <data name="RefReadonly" xml:space="preserve"> <value>Доступное только для чтения поле может передаваться как параметр с ключевым словом ref или out только в конструкторе</value> </data> <data name="AssgReadonlyStatic" xml:space="preserve"> <value>Присваивание значений доступному только для чтения статическому полю допускается только в статическом конструкторе и в инициализаторе переменных</value> </data> <data name="RefReadonlyStatic" xml:space="preserve"> <value>Доступное только для чтения статическое поле может передаваться как параметр с ключевым словом ref или out только в статическом конструкторе</value> </data> <data name="AssgReadonlyProp" xml:space="preserve"> <value>Невозможно присвоить значение свойству или индексатору "{0}" -- доступ только для чтения</value> </data> <data name="RefProperty" xml:space="preserve"> <value>Свойства и индексаторы не могут передаваться как параметры с ключевыми словами out и ref</value> </data> <data name="UnsafeNeeded" xml:space="preserve"> <value>Динамические вызовы нельзя использовать в сопряжении с указателями</value> </data> <data name="BadBoolOp" xml:space="preserve"> <value>Для использования в качестве логического оператора краткой записи тип возвращаемого значения пользовательского логического оператора ("{0}") должен быть аналогичен типам двух его параметров</value> </data> <data name="MustHaveOpTF" xml:space="preserve"> <value>Тип ("{0}") должен содержать объявления оператора true и оператора false</value> </data> <data name="ConstOutOfRangeChecked" xml:space="preserve"> <value>Постоянное значение "{0}" не может быть преобразовано в "{1}" (для обхода используйте синтаксис "unchecked")</value> </data> <data name="AmbigMember" xml:space="preserve"> <value>Неоднозначность между "{0}" и "{1}"</value> </data> <data name="NoImplicitConvCast" xml:space="preserve"> <value>Не удается неявно преобразовать тип "{0}" в "{1}". Существует явное преобразование (требуется приведение типа?)</value> </data> <data name="InaccessibleGetter" xml:space="preserve"> <value>Свойство или индексатор "{0}" невозможно использовать в данном контексте, поскольку метод доступа get недоступен</value> </data> <data name="InaccessibleSetter" xml:space="preserve"> <value>Свойство или индексатор "{0}" невозможно использовать в данном контексте, поскольку метод доступа set недоступен</value> </data> <data name="BadArity" xml:space="preserve"> <value>Использование универсального {1} "{0}" требует аргументов типа "{2}"</value> </data> <data name="TypeArgsNotAllowed" xml:space="preserve"> <value>{1} "{0}" не может использоваться с аргументами типа</value> </data> <data name="HasNoTypeVars" xml:space="preserve"> <value>Неуниверсальный {1} "{0}" не может использоваться с аргументами типа</value> </data> <data name="NewConstraintNotSatisfied" xml:space="preserve"> <value>"Для использования в качестве параметра "{1}" в универсальном типе или методе "{0}" тип "{2}" должен быть неабстрактным и иметь открытый конструктор без параметров</value> </data> <data name="GenericConstraintNotSatisfiedRefType" xml:space="preserve"> <value>Невозможно использовать тип "{3}" в качестве параметра типа "{2}" в универсальном типе или методе "{0}". Нет неявного преобразования ссылки из "{3}" в "{1}".</value> </data> <data name="GenericConstraintNotSatisfiedNullableEnum" xml:space="preserve"> <value>Невозможно использовать тип "{3}" в качестве параметра типа "{2}" в универсальном типе или методе "{0}". Для типа "{3}", допускающего значение null, не выполняется ограничение "{1}".</value> </data> <data name="GenericConstraintNotSatisfiedNullableInterface" xml:space="preserve"> <value>Невозможно использовать тип "{3}" в качестве параметра типа "{2}" в универсальном типе или методе "{0}". Для типа "{3}", допускающего значение null, не выполняется ограничение "{1}". Типы, допускающие значение null, не могут удовлетворять ни одному интерфейсному ограничению.</value> </data> <data name="GenericConstraintNotSatisfiedValType" xml:space="preserve"> <value>Невозможно использовать тип "{3}" в качестве параметра типа "{2}" в универсальном типе или методе "{0}". Нет преобразования-упаковки из "{3}" в "{1}".</value> </data> <data name="CantInferMethTypeArgs" xml:space="preserve"> <value>The type arguments for method "{0}" cannot be inferred from the usage. Попытайтесь явно определить аргументы-типы.</value> </data> <data name="RefConstraintNotSatisfied" xml:space="preserve"> <value>Для использования в качестве параметра "{1}" в универсальном типе или методе "{0}" тип "{2}" должен быть ссылочным типом</value> </data> <data name="ValConstraintNotSatisfied" xml:space="preserve"> <value>Для использования в качестве параметра "{1}" в универсальном типе или методе "{0}" тип "{2}" должен быть типом значения, не допускающим значения NULL</value> </data> <data name="AmbigUDConv" xml:space="preserve"> <value>Неоднозначные пользовательские преобразования "{0}" и "{1}" при преобразовании из "{2}" в "{3}"</value> </data> <data name="BindToBogus" xml:space="preserve"> <value>"{0}" не поддерживается языком</value> </data> <data name="CantCallSpecialMethod" xml:space="preserve"> <value>"{0}": явный вызов оператора или метода доступа невозможен</value> </data> <data name="ConvertToStaticClass" xml:space="preserve"> <value>Не удается выполнить преобразование к статическому типу "{0}"</value> </data> <data name="IncrementLvalueExpected" xml:space="preserve"> <value>Операндом оператора инкремента или декремента должна быть переменная, свойство или индексатор</value> </data> <data name="BadArgCount" xml:space="preserve"> <value>Отсутствие перегрузки для метода "{0}" принимает"{1}" аргументы</value> </data> <data name="BadArgTypes" xml:space="preserve"> <value>Наиболее подходящий перегруженный метод для "{0}" имеет несколько недопустимых аргументов</value> </data> <data name="RefLvalueExpected" xml:space="preserve"> <value>Аргумент с ключевым словом ref или out должен быть переменной, которой можно присвоить значение</value> </data> <data name="BadProtectedAccess" xml:space="preserve"> <value>Не удается получить доступ к защищенному члену "{0}" через квалификатор типа "{1}"; квалификатор должен иметь тип "{2}" (или производный от него)</value> </data> <data name="BindToBogusProp2" xml:space="preserve"> <value>Свойство, индексатор или событие "{0}" не поддерживается в данном языке; попробуйте вызвать метод доступа "{1}" или "{2}"</value> </data> <data name="BindToBogusProp1" xml:space="preserve"> <value>Свойство, индексатор или событие "{0}" не поддерживается в данном языке; попробуйте вызвать метод доступа "{1}" или "{2}"</value> </data> <data name="BadDelArgCount" xml:space="preserve"> <value>Делегат "{0}" не принимает аргументы "{1}"</value> </data> <data name="BadDelArgTypes" xml:space="preserve"> <value>Делегат "{0}" имеет недопустимые аргументы</value> </data> <data name="AssgReadonlyLocal" xml:space="preserve"> <value>Не удается выполнить присвоение параметру "{0}", так как он доступен только для чтения</value> </data> <data name="RefReadonlyLocal" xml:space="preserve"> <value>Cannot pass "{0}" as a ref or out argument because it is read-only</value> </data> <data name="ReturnNotLValue" xml:space="preserve"> <value>Cannot modify the return value of "{0}" because it is not a variable</value> </data> <data name="AssgReadonly2" xml:space="preserve"> <value>Члены поля "{0}", предназначенного только для чтения, могут быть изменены только в конструкторе или инициализаторе переменных</value> </data> <data name="RefReadonly2" xml:space="preserve"> <value>Members of readonly field "{0}" cannot be passed ref or out (except in a constructor)</value> </data> <data name="AssgReadonlyStatic2" xml:space="preserve"> <value>Присваивание значений полям доступного только для чтения статического поля "{0}" допускается только в статическом конструкторе и в инициализаторе переменных</value> </data> <data name="RefReadonlyStatic2" xml:space="preserve"> <value>Fields of static readonly field "{0}" cannot be passed ref or out (except in a static constructor)</value> </data> <data name="AssgReadonlyLocalCause" xml:space="preserve"> <value>Не удается выполнить присвоение параметру "{0}", так как он является "{1}"</value> </data> <data name="RefReadonlyLocalCause" xml:space="preserve"> <value>Не удалось передать "{0}" как ссылку или аргумент out, так как это "{1}"</value> </data> <data name="BadCtorArgCount" xml:space="preserve"> <value>"{0}" не содержит конструктор, принимающий аргументов: {1}</value> </data> <data name="NonInvocableMemberCalled" xml:space="preserve"> <value>Невызываемый член "{0}" не может использоваться как метод.</value> </data> <data name="NamedArgumentSpecificationBeforeFixedArgument" xml:space="preserve"> <value>Спецификации именованного аргумента должны появляться во всех указанных фиксированных аргументах</value> </data> <data name="BadNamedArgument" xml:space="preserve"> <value>Наиболее подходящий перегруженный метод для "{0}" не имеет параметра "{1}"</value> </data> <data name="BadNamedArgumentForDelegateInvoke" xml:space="preserve"> <value>Делегат "{0}" не имеет параметра "{1}"</value> </data> <data name="DuplicateNamedArgument" xml:space="preserve"> <value>Не удается задать именованный аргумент "{0}" несколько раз</value> </data> <data name="NamedArgumentUsedInPositional" xml:space="preserve"> <value>Именованный аргумент "{0}" задает параметр, для которого уже был установлен позиционный аргумент.</value> </data> </root>
<root> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="InternalCompilerError" xml:space="preserve"> <value>Возникло непредвиденное исключение при выполнении привязки динамической операции</value> </data> <data name="BindRequireArguments" xml:space="preserve"> <value>Невозможно выполнить привязку вызова к невызывающему объекту</value> </data> <data name="BindCallFailedOverloadResolution" xml:space="preserve"> <value>Сбой при разрешении перегрузки</value> </data> <data name="BindBinaryOperatorRequireTwoArguments" xml:space="preserve"> <value>Бинарные операторы должны вызываться с использованием двух аргументов</value> </data> <data name="BindUnaryOperatorRequireOneArgument" xml:space="preserve"> <value>Унарные операторы должны быть вызваны с использованием одного аргумента</value> </data> <data name="BindPropertyFailedMethodGroup" xml:space="preserve"> <value>Для имени "{0}" выполнена привязка к методу. Невозможно использовать его как свойство</value> </data> <data name="BindPropertyFailedEvent" xml:space="preserve"> <value>Событие «{0}» может появляться только на стороне левой руки +</value> </data> <data name="BindInvokeFailedNonDelegate" xml:space="preserve"> <value>Не удалось вызвать тип, не являющийся делегатом</value> </data> <data name="BindBinaryAssignmentRequireTwoArguments" xml:space="preserve"> <value>Невозможно вызвать бинарные операторы с использованием одного аргумента</value> </data> <data name="BindBinaryAssignmentFailedNullReference" xml:space="preserve"> <value>Не удается выполнить присваивание члена по нулевой ссылке</value> </data> <data name="NullReferenceOnMemberException" xml:space="preserve"> <value>Не удается выполнить привязки исполняющей среды по нулевой ссылке</value> </data> <data name="BindCallToConditionalMethod" xml:space="preserve"> <value>Не удается динамически вызвать метод "{0}", так как у него есть условный атрибут</value> </data> <data name="BindToVoidMethodButExpectResult" xml:space="preserve"> <value>Нельзя неявно преобразовать тип "void" to "object"</value> </data> <data name="BadBinaryOps" xml:space="preserve"> <value>Не удается применить оператор "{0}" к операндам типа "{1}" и "{2}"</value> </data> <data name="BadIndexLHS" xml:space="preserve"> <value>Невозможно применить индексирование через [] к выражению типа "{0}"</value> </data> <data name="BadIndexCount" xml:space="preserve"> <value>Неверное количество индексов внутри []; ожидалось "{0}"</value> </data> <data name="BadUnaryOp" xml:space="preserve"> <value>Не удается применить операнд "{0}" типа "{1}"</value> </data> <data name="NoImplicitConv" xml:space="preserve"> <value>Не удается неявно преобразовать тип "{0}" в "{1}"</value> </data> <data name="NoExplicitConv" xml:space="preserve"> <value>Невозможно преобразовать тип "{0}" в "{1}"</value> </data> <data name="ConstOutOfRange" xml:space="preserve"> <value>Постоянное значение "{0}" не может быть преобразовано в "{1}"</value> </data> <data name="AmbigBinaryOps" xml:space="preserve"> <value>Оператор "{0}" является неоднозначным по отношению к операндам типа "{1}" и "{2}"</value> </data> <data name="AmbigUnaryOp" xml:space="preserve"> <value>Оператор "{0}" является неоднозначным по отношению к операнду типа "{1}"</value> </data> <data name="ValueCantBeNull" xml:space="preserve"> <value>Cannot convert null to "{0}" because it is a non-nullable value type</value> </data> <data name="NoSuchMember" xml:space="preserve"> <value>"{0}" не содержит определения для "{1}"</value> </data> <data name="ObjectRequired" xml:space="preserve"> <value>Для нестатического поля, метода или свойства "{0}" требуется ссылка на объект</value> </data> <data name="AmbigCall" xml:space="preserve"> <value>Понятие "вызов" трактуется неоднозначно в следующих методах или свойствах: "{0}" и "{1}"</value> </data> <data name="BadAccess" xml:space="preserve"> <value>"{0}" недоступен из-за его уровня защиты</value> </data> <data name="MethDelegateMismatch" xml:space="preserve"> <value>Нет перегрузки для "{0}", соответствующей делегату "{1}"</value> </data> <data name="AssgLvalueExpected" xml:space="preserve"> <value>Левая часть выражения присваивания должна быть переменной, свойством или индексатором</value> </data> <data name="NoConstructors" xml:space="preserve"> <value>Для типа "{0}" нет определенных конструкторов</value> </data> <data name="PropertyLacksGet" xml:space="preserve"> <value>The property or indexer "{0}" cannot be used in this context because it lacks the get accessor</value> </data> <data name="ObjectProhibited" xml:space="preserve"> <value>Доступ к члену "{0}" через ссылку на экземпляр невозможен; вместо этого уточните его, указав имя типа</value> </data> <data name="AssgReadonly" xml:space="preserve"> <value>Присваивание значений доступному только для чтения полю допускается только в конструкторе и в инициализаторе переменных</value> </data> <data name="RefReadonly" xml:space="preserve"> <value>Доступное только для чтения поле может передаваться как параметр с ключевым словом ref или out только в конструкторе</value> </data> <data name="AssgReadonlyStatic" xml:space="preserve"> <value>Присваивание значений доступному только для чтения статическому полю допускается только в статическом конструкторе и в инициализаторе переменных</value> </data> <data name="RefReadonlyStatic" xml:space="preserve"> <value>Доступное только для чтения статическое поле может передаваться как параметр с ключевым словом ref или out только в статическом конструкторе</value> </data> <data name="AssgReadonlyProp" xml:space="preserve"> <value>Невозможно присвоить значение свойству или индексатору "{0}" -- доступ только для чтения</value> </data> <data name="RefProperty" xml:space="preserve"> <value>Свойства и индексаторы не могут передаваться как параметры с ключевыми словами out и ref</value> </data> <data name="UnsafeNeeded" xml:space="preserve"> <value>Динамические вызовы нельзя использовать в сопряжении с указателями</value> </data> <data name="BadBoolOp" xml:space="preserve"> <value>Для использования в качестве логического оператора краткой записи тип возвращаемого значения пользовательского логического оператора ("{0}") должен быть аналогичен типам двух его параметров</value> </data> <data name="MustHaveOpTF" xml:space="preserve"> <value>Тип ("{0}") должен содержать объявления оператора true и оператора false</value> </data> <data name="ConstOutOfRangeChecked" xml:space="preserve"> <value>Постоянное значение "{0}" не может быть преобразовано в "{1}" (для обхода используйте синтаксис "unchecked")</value> </data> <data name="AmbigMember" xml:space="preserve"> <value>Неоднозначность между "{0}" и "{1}"</value> </data> <data name="NoImplicitConvCast" xml:space="preserve"> <value>Не удается неявно преобразовать тип "{0}" в "{1}". Существует явное преобразование (требуется приведение типа?)</value> </data> <data name="InaccessibleGetter" xml:space="preserve"> <value>Свойство или индексатор "{0}" невозможно использовать в данном контексте, поскольку метод доступа get недоступен</value> </data> <data name="InaccessibleSetter" xml:space="preserve"> <value>Свойство или индексатор "{0}" невозможно использовать в данном контексте, поскольку метод доступа set недоступен</value> </data> <data name="BadArity" xml:space="preserve"> <value>Использование универсального {1} "{0}" требует аргументов типа "{2}"</value> </data> <data name="TypeArgsNotAllowed" xml:space="preserve"> <value>{1} "{0}" не может использоваться с аргументами типа</value> </data> <data name="HasNoTypeVars" xml:space="preserve"> <value>Неуниверсальный {1} "{0}" не может использоваться с аргументами типа</value> </data> <data name="NewConstraintNotSatisfied" xml:space="preserve"> <value>"Для использования в качестве параметра "{1}" в универсальном типе или методе "{0}" тип "{2}" должен быть неабстрактным и иметь открытый конструктор без параметров</value> </data> <data name="GenericConstraintNotSatisfiedRefType" xml:space="preserve"> <value>Невозможно использовать тип "{3}" в качестве параметра типа "{2}" в универсальном типе или методе "{0}". Нет неявного преобразования ссылки из "{3}" в "{1}".</value> </data> <data name="GenericConstraintNotSatisfiedNullableEnum" xml:space="preserve"> <value>Невозможно использовать тип "{3}" в качестве параметра типа "{2}" в универсальном типе или методе "{0}". Для типа "{3}", допускающего значение null, не выполняется ограничение "{1}".</value> </data> <data name="GenericConstraintNotSatisfiedNullableInterface" xml:space="preserve"> <value>Невозможно использовать тип "{3}" в качестве параметра типа "{2}" в универсальном типе или методе "{0}". Для типа "{3}", допускающего значение null, не выполняется ограничение "{1}". Типы, допускающие значение null, не могут удовлетворять ни одному интерфейсному ограничению.</value> </data> <data name="GenericConstraintNotSatisfiedValType" xml:space="preserve"> <value>Невозможно использовать тип "{3}" в качестве параметра типа "{2}" в универсальном типе или методе "{0}". Нет преобразования-упаковки из "{3}" в "{1}".</value> </data> <data name="CantInferMethTypeArgs" xml:space="preserve"> <value>The type arguments for method "{0}" cannot be inferred from the usage. Попытайтесь явно определить аргументы-типы.</value> </data> <data name="RefConstraintNotSatisfied" xml:space="preserve"> <value>Для использования в качестве параметра "{1}" в универсальном типе или методе "{0}" тип "{2}" должен быть ссылочным типом</value> </data> <data name="ValConstraintNotSatisfied" xml:space="preserve"> <value>Для использования в качестве параметра "{1}" в универсальном типе или методе "{0}" тип "{2}" должен быть типом значения, не допускающим значения NULL</value> </data> <data name="AmbigUDConv" xml:space="preserve"> <value>Неоднозначные пользовательские преобразования "{0}" и "{1}" при преобразовании из "{2}" в "{3}"</value> </data> <data name="BindToBogus" xml:space="preserve"> <value>"{0}" не поддерживается языком</value> </data> <data name="CantCallSpecialMethod" xml:space="preserve"> <value>"{0}": явный вызов оператора или метода доступа невозможен</value> </data> <data name="ConvertToStaticClass" xml:space="preserve"> <value>Не удается выполнить преобразование к статическому типу "{0}"</value> </data> <data name="IncrementLvalueExpected" xml:space="preserve"> <value>Операндом оператора инкремента или декремента должна быть переменная, свойство или индексатор</value> </data> <data name="BadArgCount" xml:space="preserve"> <value>Отсутствие перегрузки для метода "{0}" принимает"{1}" аргументы</value> </data> <data name="BadArgTypes" xml:space="preserve"> <value>Наиболее подходящий перегруженный метод для "{0}" имеет несколько недопустимых аргументов</value> </data> <data name="RefLvalueExpected" xml:space="preserve"> <value>Аргумент с ключевым словом ref или out должен быть переменной, которой можно присвоить значение</value> </data> <data name="BadProtectedAccess" xml:space="preserve"> <value>Не удается получить доступ к защищенному члену "{0}" через квалификатор типа "{1}"; квалификатор должен иметь тип "{2}" (или производный от него)</value> </data> <data name="BindToBogusProp2" xml:space="preserve"> <value>Свойство, индексатор или событие "{0}" не поддерживается в данном языке; попробуйте вызвать метод доступа "{1}" или "{2}"</value> </data> <data name="BindToBogusProp1" xml:space="preserve"> <value>Свойство, индексатор или событие "{0}" не поддерживается в данном языке; попробуйте вызвать метод доступа "{1}" или "{2}"</value> </data> <data name="BadDelArgCount" xml:space="preserve"> <value>Делегат "{0}" не принимает аргументы "{1}"</value> </data> <data name="BadDelArgTypes" xml:space="preserve"> <value>Делегат "{0}" имеет недопустимые аргументы</value> </data> <data name="AssgReadonlyLocal" xml:space="preserve"> <value>Не удается выполнить присвоение параметру "{0}", так как он доступен только для чтения</value> </data> <data name="RefReadonlyLocal" xml:space="preserve"> <value>Cannot pass "{0}" as a ref or out argument because it is read-only</value> </data> <data name="ReturnNotLValue" xml:space="preserve"> <value>Cannot modify the return value of "{0}" because it is not a variable</value> </data> <data name="AssgReadonly2" xml:space="preserve"> <value>Члены поля "{0}", предназначенного только для чтения, могут быть изменены только в конструкторе или инициализаторе переменных</value> </data> <data name="RefReadonly2" xml:space="preserve"> <value>Members of readonly field "{0}" cannot be passed ref or out (except in a constructor)</value> </data> <data name="AssgReadonlyStatic2" xml:space="preserve"> <value>Присваивание значений полям доступного только для чтения статического поля "{0}" допускается только в статическом конструкторе и в инициализаторе переменных</value> </data> <data name="RefReadonlyStatic2" xml:space="preserve"> <value>Fields of static readonly field "{0}" cannot be passed ref or out (except in a static constructor)</value> </data> <data name="AssgReadonlyLocalCause" xml:space="preserve"> <value>Не удается выполнить присвоение параметру "{0}", так как он является "{1}"</value> </data> <data name="RefReadonlyLocalCause" xml:space="preserve"> <value>Не удалось передать "{0}" как ссылку или аргумент out, так как это "{1}"</value> </data> <data name="BadCtorArgCount" xml:space="preserve"> <value>"{0}" не содержит конструктор, принимающий аргументов: {1}</value> </data> <data name="NonInvocableMemberCalled" xml:space="preserve"> <value>Невызываемый член "{0}" не может использоваться как метод.</value> </data> <data name="NamedArgumentSpecificationBeforeFixedArgument" xml:space="preserve"> <value>Спецификации именованного аргумента должны появляться во всех указанных фиксированных аргументах</value> </data> <data name="BadNamedArgument" xml:space="preserve"> <value>Наиболее подходящий перегруженный метод для "{0}" не имеет параметра "{1}"</value> </data> <data name="BadNamedArgumentForDelegateInvoke" xml:space="preserve"> <value>Делегат "{0}" не имеет параметра "{1}"</value> </data> <data name="DuplicateNamedArgument" xml:space="preserve"> <value>Не удается задать именованный аргумент "{0}" несколько раз</value> </data> <data name="NamedArgumentUsedInPositional" xml:space="preserve"> <value>Именованный аргумент "{0}" задает параметр, для которого уже был установлен позиционный аргумент.</value> </data> </root>
-1
dotnet/runtime
66,193
Add xarch `blsi`
This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
Wraith2
2022-03-04T13:44:46Z
2022-03-15T00:53:39Z
436b97cc809a3db1d1a25faedbc64aa97875bae3
6bf873a991bcae3f80f5de155a594cefc8824eea
Add xarch `blsi`. This adds a lowering for the pattern `AND(x, NEG(x))` to the ExtractLowestSetBit hwintrinsic. The spmi replay is clean and there is only one asm diff: ```diff ; Assembly listing for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; Emitting BLENDED_CODE for X64 CPU with AVX - Windows ; optimized code ; rsp based frame ; partially interruptible ; No matching PGO data ; 0 inlinees with PGO data; 1 single block inlinees; 1 inlinees without PGO data ; Final local variable assignments ; -; V00 arg0 [V00,T00] ( 6, 5.50) int -> rsi single-def +; V00 arg0 [V00,T00] ( 5, 4.50) int -> rsi single-def ;* V01 loc0 [V01 ] ( 0, 0 ) int -> zero-ref ; V02 OutArgs [V02 ] ( 1, 1 ) lclBlk (32) [rsp+00H] "OutgoingArgSpace" ; V03 tmp1 [V03,T02] ( 3, 2 ) int -> rcx ; V04 tmp2 [V04,T01] ( 2, 4 ) bool -> rcx "Inlining Arg" ; V05 cse0 [V05,T03] ( 3, 1.50) ref -> rdx "CSE - moderate" ; ; Lcl frame size = 32 G_M29069_IG01: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, nogc <-- Prolog IG push rsi sub rsp, 32 mov esi, ecx ;; bbWeight=1 PerfScore 1.50 G_M29069_IG02: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 4 je SHORT G_M29069_IG04 ;; bbWeight=1 PerfScore 1.25 G_M29069_IG03: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz cmp esi, 5 sete cl movzx rcx, cl jmp SHORT G_M29069_IG05 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG04: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov ecx, 1 ;; bbWeight=0.50 PerfScore 0.12 G_M29069_IG05: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref, isz movzx rcx, cl test ecx, ecx jne SHORT G_M29069_IG07 ;; bbWeight=1 PerfScore 1.50 G_M29069_IG06: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref mov rcx, 0xD1FFAB1E ; string handle mov rdx, gword ptr [rcx] ; gcrRegs +[rdx] mov rcx, rdx ; gcrRegs +[rcx] call hackishModuleName:hackishMethodName() ; gcrRegs -[rcx rdx] ; gcr arg pop 0 ;; bbWeight=0.50 PerfScore 1.75 G_M29069_IG07: ; gcrefRegs=00000000 {}, byrefRegs=00000000 {}, byref + blsi eax, esi - mov eax, esi - neg eax - and eax, esi shl eax, 28 + ;; bbWeight=1 PerfScore 1.00 - ;; bbWeight=1 PerfScore 1.25 G_M29069_IG08: ; , epilog, nogc, extend add rsp, 32 pop rsi ret ;; bbWeight=1 PerfScore 1.75 +; Total bytes of code 70, prolog size 5, PerfScore 17.63, instruction count 22, allocated bytes for code 70 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int -; Total bytes of code 71, prolog size 5, PerfScore 17.98, instruction count 24, allocated bytes for code 71 (MethodHash=20958e72) for method System.String:GetCompareOptionsFromOrdinalStringComparison(int):int ; ============================================================ Unwind Info: >> Start offset : 0x000000 (not in unwind data) >> End offset : 0xd1ffab1e (not in unwind data) Version : 1 Flags : 0x00 SizeOfProlog : 0x05 CountOfUnwindCodes: 2 FrameRegister : none (0) FrameOffset : N/A (no FrameRegister) (Value=0) UnwindCodes : CodeOffset: 0x05 UnwindOp: UWOP_ALLOC_SMALL (2) OpInfo: 3 * 8 + 8 = 32 = 0x20 CodeOffset: 0x01 UnwindOp: UWOP_PUSH_NONVOL (0) OpInfo: rsi (6) ``` The value is low but if it is ever used it is an improvement. I chose to open the PR even though the value is low so that even if this is closed anyone else ever wonders why `blsi` isn't used can see the results of implementing it. /cc @dotnet/jit-contrib
./src/coreclr/pal/src/libunwind/src/x86/Gos-freebsd.c
/* libunwind - a platform-independent unwind library Copyright (C) 2010 Konstantin Belousov <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <sys/types.h> #include <signal.h> #include <stddef.h> #include <ucontext.h> #include <machine/sigframe.h> #include "unwind_i.h" #include "offsets.h" int unw_is_signal_frame (unw_cursor_t *cursor) { struct cursor *c = (struct cursor *) cursor; unw_word_t w0, w1, w2, w3, w4, w5, ip; unw_addr_space_t as; unw_accessors_t *a; void *arg; int ret; as = c->dwarf.as; a = unw_get_accessors_int (as); arg = c->dwarf.as_arg; /* Check if EIP points at sigreturn() sequence. It can be: sigcode+4: from amd64 freebsd32 environment 8d 44 24 20 lea 0x20(%esp),%eax 50 push %eax b8 a1 01 00 00 mov $0x1a1,%eax 50 push %eax cd 80 int $0x80 sigcode+4: from real i386 8d 44 24 20 lea 0x20(%esp),%eax 50 push %eax f7 40 54 00 02 00 testl $0x20000,0x54(%eax) 75 03 jne sigcode+21 8e 68 14 mov 0x14(%eax),%gs b8 a1 01 00 00 mov $0x1a1,%eax 50 push %eax cd 80 int $0x80 freebsd4_sigcode+4: XXX osigcode: XXX */ ip = c->dwarf.ip; ret = X86_SCF_NONE; c->sigcontext_format = ret; if ((*a->access_mem) (as, ip, &w0, 0, arg) < 0 || (*a->access_mem) (as, ip + 4, &w1, 0, arg) < 0 || (*a->access_mem) (as, ip + 8, &w2, 0, arg) < 0 || (*a->access_mem) (as, ip + 12, &w3, 0, arg) < 0) return ret; if (w0 == 0x2024448d && w1 == 0x01a1b850 && w2 == 0xcd500000 && (w3 & 0xff) == 0x80) ret = X86_SCF_FREEBSD_SIGFRAME; else { if ((*a->access_mem) (as, ip + 16, &w4, 0, arg) < 0 || (*a->access_mem) (as, ip + 20, &w5, 0, arg) < 0) return ret; if (w0 == 0x2024448d && w1 == 0x5440f750 && w2 == 0x75000200 && w3 == 0x14688e03 && w4 == 0x0001a1b8 && w5 == 0x80cd5000) ret = X86_SCF_FREEBSD_SIGFRAME; } /* Check for syscall */ if (ret == X86_SCF_NONE && (*a->access_mem) (as, ip - 2, &w0, 0, arg) >= 0 && (w0 & 0xffff) == 0x80cd) ret = X86_SCF_FREEBSD_SYSCALL; Debug (16, "returning %d\n", ret); c->sigcontext_format = ret; return (ret); } HIDDEN int x86_handle_signal_frame (unw_cursor_t *cursor) { struct cursor *c = (struct cursor *) cursor; int ret; if (c->sigcontext_format == X86_SCF_FREEBSD_SIGFRAME) { struct sigframe *sf; uintptr_t uc_addr; struct dwarf_loc esp_loc; sf = (struct sigframe *)c->dwarf.cfa; uc_addr = (uintptr_t)&(sf->sf_uc); c->sigcontext_addr = c->dwarf.cfa; esp_loc = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_ESP_OFF, 0); ret = dwarf_get (&c->dwarf, esp_loc, &c->dwarf.cfa); if (ret < 0) { Debug (2, "returning 0\n"); return 0; } c->dwarf.loc[EIP] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_EIP_OFF, 0); c->dwarf.loc[ESP] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_ESP_OFF, 0); c->dwarf.loc[EAX] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_EAX_OFF, 0); c->dwarf.loc[ECX] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_ECX_OFF, 0); c->dwarf.loc[EDX] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_EDX_OFF, 0); c->dwarf.loc[EBX] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_EBX_OFF, 0); c->dwarf.loc[EBP] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_EBP_OFF, 0); c->dwarf.loc[ESI] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_ESI_OFF, 0); c->dwarf.loc[EDI] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_EDI_OFF, 0); c->dwarf.loc[EFLAGS] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_EFLAGS_OFF, 0); c->dwarf.loc[TRAPNO] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_TRAPNO_OFF, 0); c->dwarf.loc[ST0] = DWARF_NULL_LOC; } else if (c->sigcontext_format == X86_SCF_FREEBSD_SYSCALL) { c->dwarf.loc[EIP] = DWARF_LOC (c->dwarf.cfa, 0); c->dwarf.loc[EAX] = DWARF_NULL_LOC; c->dwarf.cfa += 4; c->dwarf.use_prev_instr = 1; } else { Debug (8, "Gstep: not handling frame format %d\n", c->sigcontext_format); abort(); } return 0; } HIDDEN dwarf_loc_t x86_get_scratch_loc (struct cursor *c, unw_regnum_t reg) { unw_word_t addr = c->sigcontext_addr, off, xmm_off; unw_word_t fpstate, fpformat; int ret, is_fpstate = 0, is_xmmstate = 0; switch (c->sigcontext_format) { case X86_SCF_NONE: return DWARF_REG_LOC (&c->dwarf, reg); case X86_SCF_FREEBSD_SIGFRAME: addr += offsetof(struct sigframe, sf_uc) + FREEBSD_UC_MCONTEXT_OFF; break; case X86_SCF_FREEBSD_SIGFRAME4: abort(); break; case X86_SCF_FREEBSD_OSIGFRAME: /* XXXKIB */ abort(); break; case X86_SCF_FREEBSD_SYSCALL: /* XXXKIB */ abort(); break; default: /* XXXKIB */ abort(); break; } off = 0; /* shut gcc warning */ switch (reg) { case UNW_X86_GS: off = FREEBSD_UC_MCONTEXT_GS_OFF; break; case UNW_X86_FS: off = FREEBSD_UC_MCONTEXT_FS_OFF; break; case UNW_X86_ES: off = FREEBSD_UC_MCONTEXT_ES_OFF; break; case UNW_X86_DS: off = FREEBSD_UC_MCONTEXT_SS_OFF; break; case UNW_X86_EDI: off = FREEBSD_UC_MCONTEXT_EDI_OFF; break; case UNW_X86_ESI: off = FREEBSD_UC_MCONTEXT_ESI_OFF; break; case UNW_X86_EBP: off = FREEBSD_UC_MCONTEXT_EBP_OFF; break; case UNW_X86_ESP: off = FREEBSD_UC_MCONTEXT_ESP_OFF; break; case UNW_X86_EBX: off = FREEBSD_UC_MCONTEXT_EBX_OFF; break; case UNW_X86_EDX: off = FREEBSD_UC_MCONTEXT_EDX_OFF; break; case UNW_X86_ECX: off = FREEBSD_UC_MCONTEXT_ECX_OFF; break; case UNW_X86_EAX: off = FREEBSD_UC_MCONTEXT_EAX_OFF; break; case UNW_X86_TRAPNO: off = FREEBSD_UC_MCONTEXT_TRAPNO_OFF; break; case UNW_X86_EIP: off = FREEBSD_UC_MCONTEXT_EIP_OFF; break; case UNW_X86_CS: off = FREEBSD_UC_MCONTEXT_CS_OFF; break; case UNW_X86_EFLAGS: off = FREEBSD_UC_MCONTEXT_EFLAGS_OFF; break; case UNW_X86_SS: off = FREEBSD_UC_MCONTEXT_SS_OFF; break; case UNW_X86_FCW: is_fpstate = 1; off = FREEBSD_UC_MCONTEXT_CW_OFF; xmm_off = FREEBSD_UC_MCONTEXT_CW_XMM_OFF; break; case UNW_X86_FSW: is_fpstate = 1; off = FREEBSD_UC_MCONTEXT_SW_OFF; xmm_off = FREEBSD_UC_MCONTEXT_SW_XMM_OFF; break; case UNW_X86_FTW: is_fpstate = 1; xmm_off = FREEBSD_UC_MCONTEXT_TAG_XMM_OFF; off = FREEBSD_UC_MCONTEXT_TAG_OFF; break; case UNW_X86_FCS: is_fpstate = 1; off = FREEBSD_UC_MCONTEXT_CSSEL_OFF; xmm_off = FREEBSD_UC_MCONTEXT_CSSEL_XMM_OFF; break; case UNW_X86_FIP: is_fpstate = 1; off = FREEBSD_UC_MCONTEXT_IPOFF_OFF; xmm_off = FREEBSD_UC_MCONTEXT_IPOFF_XMM_OFF; break; case UNW_X86_FEA: is_fpstate = 1; off = FREEBSD_UC_MCONTEXT_DATAOFF_OFF; xmm_off = FREEBSD_UC_MCONTEXT_DATAOFF_XMM_OFF; break; case UNW_X86_FDS: is_fpstate = 1; off = FREEBSD_US_MCONTEXT_DATASEL_OFF; xmm_off = FREEBSD_US_MCONTEXT_DATASEL_XMM_OFF; break; case UNW_X86_MXCSR: is_fpstate = 1; is_xmmstate = 1; xmm_off = FREEBSD_UC_MCONTEXT_MXCSR_XMM_OFF; break; /* stacked fp registers */ case UNW_X86_ST0: case UNW_X86_ST1: case UNW_X86_ST2: case UNW_X86_ST3: case UNW_X86_ST4: case UNW_X86_ST5: case UNW_X86_ST6: case UNW_X86_ST7: is_fpstate = 1; off = FREEBSD_UC_MCONTEXT_ST0_OFF + 10*(reg - UNW_X86_ST0); xmm_off = FREEBSD_UC_MCONTEXT_ST0_XMM_OFF + 10*(reg - UNW_X86_ST0); break; /* SSE fp registers */ case UNW_X86_XMM0_lo: case UNW_X86_XMM0_hi: case UNW_X86_XMM1_lo: case UNW_X86_XMM1_hi: case UNW_X86_XMM2_lo: case UNW_X86_XMM2_hi: case UNW_X86_XMM3_lo: case UNW_X86_XMM3_hi: case UNW_X86_XMM4_lo: case UNW_X86_XMM4_hi: case UNW_X86_XMM5_lo: case UNW_X86_XMM5_hi: case UNW_X86_XMM6_lo: case UNW_X86_XMM6_hi: case UNW_X86_XMM7_lo: case UNW_X86_XMM7_hi: is_fpstate = 1; is_xmmstate = 1; xmm_off = FREEBSD_UC_MCONTEXT_XMM0_OFF + 8*(reg - UNW_X86_XMM0_lo); break; case UNW_X86_XMM0: case UNW_X86_XMM1: case UNW_X86_XMM2: case UNW_X86_XMM3: case UNW_X86_XMM4: case UNW_X86_XMM5: case UNW_X86_XMM6: case UNW_X86_XMM7: is_fpstate = 1; is_xmmstate = 1; xmm_off = FREEBSD_UC_MCONTEXT_XMM0_OFF + 16*(reg - UNW_X86_XMM0); break; case UNW_X86_FOP: case UNW_X86_TSS: case UNW_X86_LDT: default: return DWARF_REG_LOC (&c->dwarf, reg); } if (is_fpstate) { if ((ret = dwarf_get (&c->dwarf, DWARF_MEM_LOC (&c->dwarf, addr + FREEBSD_UC_MCONTEXT_FPSTATE_OFF), &fpstate)) < 0) return DWARF_NULL_LOC; if (fpstate == FREEBSD_UC_MCONTEXT_FPOWNED_NONE) return DWARF_NULL_LOC; if ((ret = dwarf_get (&c->dwarf, DWARF_MEM_LOC (&c->dwarf, addr + FREEBSD_UC_MCONTEXT_FPFORMAT_OFF), &fpformat)) < 0) return DWARF_NULL_LOC; if (fpformat == FREEBSD_UC_MCONTEXT_FPFMT_NODEV || (is_xmmstate && fpformat != FREEBSD_UC_MCONTEXT_FPFMT_XMM)) return DWARF_NULL_LOC; if (is_xmmstate) off = xmm_off; } return DWARF_MEM_LOC (c, addr + off); } #ifndef UNW_REMOTE_ONLY HIDDEN void * x86_r_uc_addr (ucontext_t *uc, int reg) { void *addr; switch (reg) { case UNW_X86_GS: addr = &uc->uc_mcontext.mc_gs; break; case UNW_X86_FS: addr = &uc->uc_mcontext.mc_fs; break; case UNW_X86_ES: addr = &uc->uc_mcontext.mc_es; break; case UNW_X86_DS: addr = &uc->uc_mcontext.mc_ds; break; case UNW_X86_EAX: addr = &uc->uc_mcontext.mc_eax; break; case UNW_X86_EBX: addr = &uc->uc_mcontext.mc_ebx; break; case UNW_X86_ECX: addr = &uc->uc_mcontext.mc_ecx; break; case UNW_X86_EDX: addr = &uc->uc_mcontext.mc_edx; break; case UNW_X86_ESI: addr = &uc->uc_mcontext.mc_esi; break; case UNW_X86_EDI: addr = &uc->uc_mcontext.mc_edi; break; case UNW_X86_EBP: addr = &uc->uc_mcontext.mc_ebp; break; case UNW_X86_EIP: addr = &uc->uc_mcontext.mc_eip; break; case UNW_X86_ESP: addr = &uc->uc_mcontext.mc_esp; break; case UNW_X86_TRAPNO: addr = &uc->uc_mcontext.mc_trapno; break; case UNW_X86_CS: addr = &uc->uc_mcontext.mc_cs; break; case UNW_X86_EFLAGS: addr = &uc->uc_mcontext.mc_eflags; break; case UNW_X86_SS: addr = &uc->uc_mcontext.mc_ss; break; default: addr = NULL; } return addr; } HIDDEN int x86_local_resume (unw_addr_space_t as, unw_cursor_t *cursor, void *arg) { struct cursor *c = (struct cursor *) cursor; ucontext_t *uc = c->uc; /* Ensure c->pi is up-to-date. On x86, it's relatively common to be missing DWARF unwind info. We don't want to fail in that case, because the frame-chain still would let us do a backtrace at least. */ dwarf_make_proc_info (&c->dwarf); if (c->sigcontext_format == X86_SCF_NONE) { Debug (8, "resuming at ip=%x via setcontext()\n", c->dwarf.ip); setcontext (uc); abort(); } else if (c->sigcontext_format == X86_SCF_FREEBSD_SIGFRAME) { struct sigcontext *sc = (struct sigcontext *) c->sigcontext_addr; Debug (8, "resuming at ip=%x via sigreturn(%p)\n", c->dwarf.ip, sc); sigreturn((ucontext_t *)((const char *)sc + FREEBSD_SC_UCONTEXT_OFF)); abort(); } else { Debug (8, "resuming at ip=%x for sigcontext format %d not implemented\n", c->dwarf.ip, c->sigcontext_format); abort(); } return -UNW_EINVAL; } #endif
/* libunwind - a platform-independent unwind library Copyright (C) 2010 Konstantin Belousov <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <sys/types.h> #include <signal.h> #include <stddef.h> #include <ucontext.h> #include <machine/sigframe.h> #include "unwind_i.h" #include "offsets.h" int unw_is_signal_frame (unw_cursor_t *cursor) { struct cursor *c = (struct cursor *) cursor; unw_word_t w0, w1, w2, w3, w4, w5, ip; unw_addr_space_t as; unw_accessors_t *a; void *arg; int ret; as = c->dwarf.as; a = unw_get_accessors_int (as); arg = c->dwarf.as_arg; /* Check if EIP points at sigreturn() sequence. It can be: sigcode+4: from amd64 freebsd32 environment 8d 44 24 20 lea 0x20(%esp),%eax 50 push %eax b8 a1 01 00 00 mov $0x1a1,%eax 50 push %eax cd 80 int $0x80 sigcode+4: from real i386 8d 44 24 20 lea 0x20(%esp),%eax 50 push %eax f7 40 54 00 02 00 testl $0x20000,0x54(%eax) 75 03 jne sigcode+21 8e 68 14 mov 0x14(%eax),%gs b8 a1 01 00 00 mov $0x1a1,%eax 50 push %eax cd 80 int $0x80 freebsd4_sigcode+4: XXX osigcode: XXX */ ip = c->dwarf.ip; ret = X86_SCF_NONE; c->sigcontext_format = ret; if ((*a->access_mem) (as, ip, &w0, 0, arg) < 0 || (*a->access_mem) (as, ip + 4, &w1, 0, arg) < 0 || (*a->access_mem) (as, ip + 8, &w2, 0, arg) < 0 || (*a->access_mem) (as, ip + 12, &w3, 0, arg) < 0) return ret; if (w0 == 0x2024448d && w1 == 0x01a1b850 && w2 == 0xcd500000 && (w3 & 0xff) == 0x80) ret = X86_SCF_FREEBSD_SIGFRAME; else { if ((*a->access_mem) (as, ip + 16, &w4, 0, arg) < 0 || (*a->access_mem) (as, ip + 20, &w5, 0, arg) < 0) return ret; if (w0 == 0x2024448d && w1 == 0x5440f750 && w2 == 0x75000200 && w3 == 0x14688e03 && w4 == 0x0001a1b8 && w5 == 0x80cd5000) ret = X86_SCF_FREEBSD_SIGFRAME; } /* Check for syscall */ if (ret == X86_SCF_NONE && (*a->access_mem) (as, ip - 2, &w0, 0, arg) >= 0 && (w0 & 0xffff) == 0x80cd) ret = X86_SCF_FREEBSD_SYSCALL; Debug (16, "returning %d\n", ret); c->sigcontext_format = ret; return (ret); } HIDDEN int x86_handle_signal_frame (unw_cursor_t *cursor) { struct cursor *c = (struct cursor *) cursor; int ret; if (c->sigcontext_format == X86_SCF_FREEBSD_SIGFRAME) { struct sigframe *sf; uintptr_t uc_addr; struct dwarf_loc esp_loc; sf = (struct sigframe *)c->dwarf.cfa; uc_addr = (uintptr_t)&(sf->sf_uc); c->sigcontext_addr = c->dwarf.cfa; esp_loc = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_ESP_OFF, 0); ret = dwarf_get (&c->dwarf, esp_loc, &c->dwarf.cfa); if (ret < 0) { Debug (2, "returning 0\n"); return 0; } c->dwarf.loc[EIP] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_EIP_OFF, 0); c->dwarf.loc[ESP] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_ESP_OFF, 0); c->dwarf.loc[EAX] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_EAX_OFF, 0); c->dwarf.loc[ECX] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_ECX_OFF, 0); c->dwarf.loc[EDX] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_EDX_OFF, 0); c->dwarf.loc[EBX] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_EBX_OFF, 0); c->dwarf.loc[EBP] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_EBP_OFF, 0); c->dwarf.loc[ESI] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_ESI_OFF, 0); c->dwarf.loc[EDI] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_EDI_OFF, 0); c->dwarf.loc[EFLAGS] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_EFLAGS_OFF, 0); c->dwarf.loc[TRAPNO] = DWARF_LOC (uc_addr + FREEBSD_UC_MCONTEXT_TRAPNO_OFF, 0); c->dwarf.loc[ST0] = DWARF_NULL_LOC; } else if (c->sigcontext_format == X86_SCF_FREEBSD_SYSCALL) { c->dwarf.loc[EIP] = DWARF_LOC (c->dwarf.cfa, 0); c->dwarf.loc[EAX] = DWARF_NULL_LOC; c->dwarf.cfa += 4; c->dwarf.use_prev_instr = 1; } else { Debug (8, "Gstep: not handling frame format %d\n", c->sigcontext_format); abort(); } return 0; } HIDDEN dwarf_loc_t x86_get_scratch_loc (struct cursor *c, unw_regnum_t reg) { unw_word_t addr = c->sigcontext_addr, off, xmm_off; unw_word_t fpstate, fpformat; int ret, is_fpstate = 0, is_xmmstate = 0; switch (c->sigcontext_format) { case X86_SCF_NONE: return DWARF_REG_LOC (&c->dwarf, reg); case X86_SCF_FREEBSD_SIGFRAME: addr += offsetof(struct sigframe, sf_uc) + FREEBSD_UC_MCONTEXT_OFF; break; case X86_SCF_FREEBSD_SIGFRAME4: abort(); break; case X86_SCF_FREEBSD_OSIGFRAME: /* XXXKIB */ abort(); break; case X86_SCF_FREEBSD_SYSCALL: /* XXXKIB */ abort(); break; default: /* XXXKIB */ abort(); break; } off = 0; /* shut gcc warning */ switch (reg) { case UNW_X86_GS: off = FREEBSD_UC_MCONTEXT_GS_OFF; break; case UNW_X86_FS: off = FREEBSD_UC_MCONTEXT_FS_OFF; break; case UNW_X86_ES: off = FREEBSD_UC_MCONTEXT_ES_OFF; break; case UNW_X86_DS: off = FREEBSD_UC_MCONTEXT_SS_OFF; break; case UNW_X86_EDI: off = FREEBSD_UC_MCONTEXT_EDI_OFF; break; case UNW_X86_ESI: off = FREEBSD_UC_MCONTEXT_ESI_OFF; break; case UNW_X86_EBP: off = FREEBSD_UC_MCONTEXT_EBP_OFF; break; case UNW_X86_ESP: off = FREEBSD_UC_MCONTEXT_ESP_OFF; break; case UNW_X86_EBX: off = FREEBSD_UC_MCONTEXT_EBX_OFF; break; case UNW_X86_EDX: off = FREEBSD_UC_MCONTEXT_EDX_OFF; break; case UNW_X86_ECX: off = FREEBSD_UC_MCONTEXT_ECX_OFF; break; case UNW_X86_EAX: off = FREEBSD_UC_MCONTEXT_EAX_OFF; break; case UNW_X86_TRAPNO: off = FREEBSD_UC_MCONTEXT_TRAPNO_OFF; break; case UNW_X86_EIP: off = FREEBSD_UC_MCONTEXT_EIP_OFF; break; case UNW_X86_CS: off = FREEBSD_UC_MCONTEXT_CS_OFF; break; case UNW_X86_EFLAGS: off = FREEBSD_UC_MCONTEXT_EFLAGS_OFF; break; case UNW_X86_SS: off = FREEBSD_UC_MCONTEXT_SS_OFF; break; case UNW_X86_FCW: is_fpstate = 1; off = FREEBSD_UC_MCONTEXT_CW_OFF; xmm_off = FREEBSD_UC_MCONTEXT_CW_XMM_OFF; break; case UNW_X86_FSW: is_fpstate = 1; off = FREEBSD_UC_MCONTEXT_SW_OFF; xmm_off = FREEBSD_UC_MCONTEXT_SW_XMM_OFF; break; case UNW_X86_FTW: is_fpstate = 1; xmm_off = FREEBSD_UC_MCONTEXT_TAG_XMM_OFF; off = FREEBSD_UC_MCONTEXT_TAG_OFF; break; case UNW_X86_FCS: is_fpstate = 1; off = FREEBSD_UC_MCONTEXT_CSSEL_OFF; xmm_off = FREEBSD_UC_MCONTEXT_CSSEL_XMM_OFF; break; case UNW_X86_FIP: is_fpstate = 1; off = FREEBSD_UC_MCONTEXT_IPOFF_OFF; xmm_off = FREEBSD_UC_MCONTEXT_IPOFF_XMM_OFF; break; case UNW_X86_FEA: is_fpstate = 1; off = FREEBSD_UC_MCONTEXT_DATAOFF_OFF; xmm_off = FREEBSD_UC_MCONTEXT_DATAOFF_XMM_OFF; break; case UNW_X86_FDS: is_fpstate = 1; off = FREEBSD_US_MCONTEXT_DATASEL_OFF; xmm_off = FREEBSD_US_MCONTEXT_DATASEL_XMM_OFF; break; case UNW_X86_MXCSR: is_fpstate = 1; is_xmmstate = 1; xmm_off = FREEBSD_UC_MCONTEXT_MXCSR_XMM_OFF; break; /* stacked fp registers */ case UNW_X86_ST0: case UNW_X86_ST1: case UNW_X86_ST2: case UNW_X86_ST3: case UNW_X86_ST4: case UNW_X86_ST5: case UNW_X86_ST6: case UNW_X86_ST7: is_fpstate = 1; off = FREEBSD_UC_MCONTEXT_ST0_OFF + 10*(reg - UNW_X86_ST0); xmm_off = FREEBSD_UC_MCONTEXT_ST0_XMM_OFF + 10*(reg - UNW_X86_ST0); break; /* SSE fp registers */ case UNW_X86_XMM0_lo: case UNW_X86_XMM0_hi: case UNW_X86_XMM1_lo: case UNW_X86_XMM1_hi: case UNW_X86_XMM2_lo: case UNW_X86_XMM2_hi: case UNW_X86_XMM3_lo: case UNW_X86_XMM3_hi: case UNW_X86_XMM4_lo: case UNW_X86_XMM4_hi: case UNW_X86_XMM5_lo: case UNW_X86_XMM5_hi: case UNW_X86_XMM6_lo: case UNW_X86_XMM6_hi: case UNW_X86_XMM7_lo: case UNW_X86_XMM7_hi: is_fpstate = 1; is_xmmstate = 1; xmm_off = FREEBSD_UC_MCONTEXT_XMM0_OFF + 8*(reg - UNW_X86_XMM0_lo); break; case UNW_X86_XMM0: case UNW_X86_XMM1: case UNW_X86_XMM2: case UNW_X86_XMM3: case UNW_X86_XMM4: case UNW_X86_XMM5: case UNW_X86_XMM6: case UNW_X86_XMM7: is_fpstate = 1; is_xmmstate = 1; xmm_off = FREEBSD_UC_MCONTEXT_XMM0_OFF + 16*(reg - UNW_X86_XMM0); break; case UNW_X86_FOP: case UNW_X86_TSS: case UNW_X86_LDT: default: return DWARF_REG_LOC (&c->dwarf, reg); } if (is_fpstate) { if ((ret = dwarf_get (&c->dwarf, DWARF_MEM_LOC (&c->dwarf, addr + FREEBSD_UC_MCONTEXT_FPSTATE_OFF), &fpstate)) < 0) return DWARF_NULL_LOC; if (fpstate == FREEBSD_UC_MCONTEXT_FPOWNED_NONE) return DWARF_NULL_LOC; if ((ret = dwarf_get (&c->dwarf, DWARF_MEM_LOC (&c->dwarf, addr + FREEBSD_UC_MCONTEXT_FPFORMAT_OFF), &fpformat)) < 0) return DWARF_NULL_LOC; if (fpformat == FREEBSD_UC_MCONTEXT_FPFMT_NODEV || (is_xmmstate && fpformat != FREEBSD_UC_MCONTEXT_FPFMT_XMM)) return DWARF_NULL_LOC; if (is_xmmstate) off = xmm_off; } return DWARF_MEM_LOC (c, addr + off); } #ifndef UNW_REMOTE_ONLY HIDDEN void * x86_r_uc_addr (ucontext_t *uc, int reg) { void *addr; switch (reg) { case UNW_X86_GS: addr = &uc->uc_mcontext.mc_gs; break; case UNW_X86_FS: addr = &uc->uc_mcontext.mc_fs; break; case UNW_X86_ES: addr = &uc->uc_mcontext.mc_es; break; case UNW_X86_DS: addr = &uc->uc_mcontext.mc_ds; break; case UNW_X86_EAX: addr = &uc->uc_mcontext.mc_eax; break; case UNW_X86_EBX: addr = &uc->uc_mcontext.mc_ebx; break; case UNW_X86_ECX: addr = &uc->uc_mcontext.mc_ecx; break; case UNW_X86_EDX: addr = &uc->uc_mcontext.mc_edx; break; case UNW_X86_ESI: addr = &uc->uc_mcontext.mc_esi; break; case UNW_X86_EDI: addr = &uc->uc_mcontext.mc_edi; break; case UNW_X86_EBP: addr = &uc->uc_mcontext.mc_ebp; break; case UNW_X86_EIP: addr = &uc->uc_mcontext.mc_eip; break; case UNW_X86_ESP: addr = &uc->uc_mcontext.mc_esp; break; case UNW_X86_TRAPNO: addr = &uc->uc_mcontext.mc_trapno; break; case UNW_X86_CS: addr = &uc->uc_mcontext.mc_cs; break; case UNW_X86_EFLAGS: addr = &uc->uc_mcontext.mc_eflags; break; case UNW_X86_SS: addr = &uc->uc_mcontext.mc_ss; break; default: addr = NULL; } return addr; } HIDDEN int x86_local_resume (unw_addr_space_t as, unw_cursor_t *cursor, void *arg) { struct cursor *c = (struct cursor *) cursor; ucontext_t *uc = c->uc; /* Ensure c->pi is up-to-date. On x86, it's relatively common to be missing DWARF unwind info. We don't want to fail in that case, because the frame-chain still would let us do a backtrace at least. */ dwarf_make_proc_info (&c->dwarf); if (c->sigcontext_format == X86_SCF_NONE) { Debug (8, "resuming at ip=%x via setcontext()\n", c->dwarf.ip); setcontext (uc); abort(); } else if (c->sigcontext_format == X86_SCF_FREEBSD_SIGFRAME) { struct sigcontext *sc = (struct sigcontext *) c->sigcontext_addr; Debug (8, "resuming at ip=%x via sigreturn(%p)\n", c->dwarf.ip, sc); sigreturn((ucontext_t *)((const char *)sc + FREEBSD_SC_UCONTEXT_OFF)); abort(); } else { Debug (8, "resuming at ip=%x for sigcontext format %d not implemented\n", c->dwarf.ip, c->sigcontext_format); abort(); } return -UNW_EINVAL; } #endif
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.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 Microsoft.Win32.SafeHandles; using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; using System.Text; namespace System.IO { /// <summary>Base class for test classes the use temporary files that need to be cleaned up.</summary> public abstract partial class FileCleanupTestBase : IDisposable { private static readonly Lazy<bool> s_isElevated = new Lazy<bool>(() => AdminHelpers.IsProcessElevated()); private string fallbackGuid = Guid.NewGuid().ToString("N").Substring(0, 10); protected static bool IsProcessElevated => s_isElevated.Value; /// <summary>Initialize the test class base. This creates the associated test directory.</summary> protected FileCleanupTestBase(string tempDirectory = null) { tempDirectory ??= Path.GetTempPath(); // Use a unique test directory per test class. The test directory lives in the user's temp directory, // and includes both the name of the test class and a random string. The test class name is included // so that it can be easily correlated if necessary, and the random string to helps avoid conflicts if // the same test should be run concurrently with itself (e.g. if a [Fact] method lives on a base class) // or if some stray files were left over from a previous run. // Make 3 attempts since we have seen this on rare occasions fail with access denied, perhaps due to machine // configuration, and it doesn't make sense to fail arbitrary tests for this reason. string failure = string.Empty; for (int i = 0; i <= 2; i++) { TestDirectory = Path.Combine(tempDirectory, GetType().Name + "_" + Path.GetRandomFileName()); try { Directory.CreateDirectory(TestDirectory); break; } catch (Exception ex) { failure += ex.ToString() + Environment.NewLine; Thread.Sleep(10); // Give a transient condition like antivirus/indexing a chance to go away } } Assert.True(Directory.Exists(TestDirectory), $"FileCleanupTestBase failed to create {TestDirectory}. {failure}"); } /// <summary>Delete the associated test directory.</summary> ~FileCleanupTestBase() { Dispose(false); } /// <summary>Delete the associated test directory.</summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary>Delete the associated test directory.</summary> protected virtual void Dispose(bool disposing) { // No managed resources to clean up, so disposing is ignored. try { Directory.Delete(TestDirectory, recursive: true); } catch { } // avoid exceptions escaping Dispose } /// <summary> /// Gets the test directory into which all files and directories created by tests should be stored. /// This directory is isolated per test class. /// </summary> protected string TestDirectory { get; } protected string GetRandomFileName() => GetTestFileName() + ".txt"; protected string GetRandomLinkName() => GetTestFileName() + ".link"; protected string GetRandomDirName() => GetTestFileName() + "_dir"; protected string GetRandomFilePath() => Path.Combine(ActualTestDirectory.Value, GetRandomFileName()); protected string GetRandomLinkPath() => Path.Combine(ActualTestDirectory.Value, GetRandomLinkName()); protected string GetRandomDirPath() => Path.Combine(ActualTestDirectory.Value, GetRandomDirName()); private Lazy<string> ActualTestDirectory => new Lazy<string>(() => GetTestDirectoryActualCasing()); /// <summary>Gets a test file full path that is associated with the call site.</summary> /// <param name="index">An optional index value to use as a suffix on the file name. Typically a loop index.</param> /// <param name="memberName">The member name of the function calling this method.</param> /// <param name="lineNumber">The line number of the function calling this method.</param> protected virtual string GetTestFilePath(int? index = null, [CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0) => Path.Combine(TestDirectory, GetTestFileName(index, memberName, lineNumber)); /// <summary>Gets a test file name that is associated with the call site.</summary> /// <param name="index">An optional index value to use as a suffix on the file name. Typically a loop index.</param> /// <param name="memberName">The member name of the function calling this method.</param> /// <param name="lineNumber">The line number of the function calling this method.</param> protected string GetTestFileName(int? index = null, [CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0) { string testFileName = GenerateTestFileName(index, memberName, lineNumber); string testFilePath = Path.Combine(TestDirectory, testFileName); const int maxLength = 260 - 5; // Windows MAX_PATH minus a bit int excessLength = testFilePath.Length - maxLength; if (excessLength > 0) { // The path will be too long for Windows -- can we // trim memberName to fix it? if (excessLength < memberName.Length + "...".Length) { // Take a chunk out of the middle as perhaps it's the least interesting part of the name int halfMemberNameLength = (int)Math.Floor((double)memberName.Length / 2); int halfExcessLength = (int)Math.Ceiling((double)excessLength / 2); memberName = memberName.Substring(0, halfMemberNameLength - halfExcessLength) + "..." + memberName.Substring(halfMemberNameLength + halfExcessLength); testFileName = GenerateTestFileName(index, memberName, lineNumber); testFilePath = Path.Combine(TestDirectory, testFileName); } else { return fallbackGuid; } } Debug.Assert(testFilePath.Length <= maxLength + "...".Length); return testFileName; } protected static string GetNamedPipeServerStreamName() { if (PlatformDetection.IsInAppContainer) { return @"LOCAL\" + Guid.NewGuid().ToString("N"); } if (PlatformDetection.IsWindows) { return Guid.NewGuid().ToString("N"); } if (!PlatformDetection.IsCaseSensitiveOS) { return $"/tmp/{Guid.NewGuid().ToString("N")}"; } const int MinUdsPathLength = 104; // required min is 92, but every platform we currently target is at least 104 const int MinAvailableForSufficientRandomness = 5; // we want enough randomness in the name to avoid conflicts between concurrent tests string prefix = Path.Combine(Path.GetTempPath(), "CoreFxPipe_"); int availableLength = MinUdsPathLength - prefix.Length - 1; // 1 - for possible null terminator Assert.True(availableLength >= MinAvailableForSufficientRandomness, $"UDS prefix {prefix} length {prefix.Length} is too long"); StringBuilder sb = new(availableLength); Random random = new Random(); for (int i = 0; i < availableLength; i++) { sb.Append((char)('a' + random.Next(0, 26))); } return sb.ToString(); } private string GenerateTestFileName(int? index, string memberName, int lineNumber) => string.Format( index.HasValue ? "{0}_{1}_{2}_{3}" : "{0}_{1}_{3}", memberName ?? "TestBase", lineNumber, index.GetValueOrDefault(), Guid.NewGuid().ToString("N").Substring(0, 8)); // randomness to avoid collisions between derived test classes using same base method concurrently // Some Windows versions like Windows Nano Server have the %TEMP% environment variable set to "C:\TEMP" but the // actual folder name is "C:\Temp", which prevents asserting path values using Assert.Equal due to case sensitiveness. // So instead of using TestDirectory directly, we retrieve the real path with proper casing of the initial folder path. private unsafe string GetTestDirectoryActualCasing() { if (!PlatformDetection.IsWindows) return TestDirectory; try { using SafeFileHandle handle = Interop.Kernel32.CreateFile( TestDirectory, dwDesiredAccess: 0, dwShareMode: FileShare.ReadWrite | FileShare.Delete, dwCreationDisposition: FileMode.Open, dwFlagsAndAttributes: Interop.Kernel32.FileOperations.OPEN_EXISTING | Interop.Kernel32.FileOperations.FILE_FLAG_BACKUP_SEMANTICS // Necessary to obtain a handle to a directory ); if (!handle.IsInvalid) { const int InitialBufferSize = 4096; char[]? buffer = ArrayPool<char>.Shared.Rent(InitialBufferSize); uint result = GetFinalPathNameByHandle(handle, buffer); // Remove extended prefix int skip = PathInternal.IsExtended(buffer) ? 4 : 0; return new string( buffer, skip, (int)result - skip); } } catch { } return TestDirectory; } private unsafe uint GetFinalPathNameByHandle(SafeFileHandle handle, char[] buffer) { fixed (char* bufPtr = buffer) { return Interop.Kernel32.GetFinalPathNameByHandle(handle, bufPtr, (uint)buffer.Length, Interop.Kernel32.FILE_NAME_NORMALIZED); } } } }
// 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 Microsoft.Win32.SafeHandles; using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; using System.Text; namespace System.IO { /// <summary>Base class for test classes the use temporary files that need to be cleaned up.</summary> public abstract partial class FileCleanupTestBase : IDisposable { private static readonly Lazy<bool> s_isElevated = new Lazy<bool>(() => AdminHelpers.IsProcessElevated()); private string fallbackGuid = Guid.NewGuid().ToString("N").Substring(0, 10); protected static bool IsProcessElevated => s_isElevated.Value; /// <summary>Initialize the test class base. This creates the associated test directory.</summary> protected FileCleanupTestBase(string tempDirectory = null) { tempDirectory ??= Path.GetTempPath(); // Use a unique test directory per test class. The test directory lives in the user's temp directory, // and includes both the name of the test class and a random string. The test class name is included // so that it can be easily correlated if necessary, and the random string to helps avoid conflicts if // the same test should be run concurrently with itself (e.g. if a [Fact] method lives on a base class) // or if some stray files were left over from a previous run. // Make 3 attempts since we have seen this on rare occasions fail with access denied, perhaps due to machine // configuration, and it doesn't make sense to fail arbitrary tests for this reason. string failure = string.Empty; for (int i = 0; i <= 2; i++) { TestDirectory = Path.Combine(tempDirectory, GetType().Name + "_" + Path.GetRandomFileName()); try { Directory.CreateDirectory(TestDirectory); break; } catch (Exception ex) { failure += ex.ToString() + Environment.NewLine; Thread.Sleep(10); // Give a transient condition like antivirus/indexing a chance to go away } } Assert.True(Directory.Exists(TestDirectory), $"FileCleanupTestBase failed to create {TestDirectory}. {failure}"); } /// <summary>Delete the associated test directory.</summary> ~FileCleanupTestBase() { Dispose(false); } /// <summary>Delete the associated test directory.</summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary>Delete the associated test directory.</summary> protected virtual void Dispose(bool disposing) { // No managed resources to clean up, so disposing is ignored. try { Directory.Delete(TestDirectory, recursive: true); } catch { } // avoid exceptions escaping Dispose } /// <summary> /// Gets the test directory into which all files and directories created by tests should be stored. /// This directory is isolated per test class. /// </summary> protected string TestDirectory { get; } protected string GetRandomFileName() => GetTestFileName() + ".txt"; protected string GetRandomLinkName() => GetTestFileName() + ".link"; protected string GetRandomDirName() => GetTestFileName() + "_dir"; protected string GetRandomFilePath() => Path.Combine(ActualTestDirectory.Value, GetRandomFileName()); protected string GetRandomLinkPath() => Path.Combine(ActualTestDirectory.Value, GetRandomLinkName()); protected string GetRandomDirPath() => Path.Combine(ActualTestDirectory.Value, GetRandomDirName()); private Lazy<string> ActualTestDirectory => new Lazy<string>(() => GetTestDirectoryActualCasing()); /// <summary>Gets a test file full path that is associated with the call site.</summary> /// <param name="index">An optional index value to use as a suffix on the file name. Typically a loop index.</param> /// <param name="memberName">The member name of the function calling this method.</param> /// <param name="lineNumber">The line number of the function calling this method.</param> protected virtual string GetTestFilePath(int? index = null, [CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0) => Path.Combine(TestDirectory, GetTestFileName(index, memberName, lineNumber)); /// <summary>Gets a test file name that is associated with the call site.</summary> /// <param name="index">An optional index value to use as a suffix on the file name. Typically a loop index.</param> /// <param name="memberName">The member name of the function calling this method.</param> /// <param name="lineNumber">The line number of the function calling this method.</param> protected string GetTestFileName(int? index = null, [CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0) { string testFileName = PathGenerator.GenerateTestFileName(index, memberName, lineNumber); string testFilePath = Path.Combine(TestDirectory, testFileName); const int maxLength = 260 - 5; // Windows MAX_PATH minus a bit int excessLength = testFilePath.Length - maxLength; if (excessLength > 0) { // The path will be too long for Windows -- can we // trim memberName to fix it? if (excessLength < memberName.Length + "...".Length) { // Take a chunk out of the middle as perhaps it's the least interesting part of the name int halfMemberNameLength = (int)Math.Floor((double)memberName.Length / 2); int halfExcessLength = (int)Math.Ceiling((double)excessLength / 2); memberName = memberName.Substring(0, halfMemberNameLength - halfExcessLength) + "..." + memberName.Substring(halfMemberNameLength + halfExcessLength); testFileName = PathGenerator.GenerateTestFileName(index, memberName, lineNumber); testFilePath = Path.Combine(TestDirectory, testFileName); } else { return fallbackGuid; } } Debug.Assert(testFilePath.Length <= maxLength + "...".Length); return testFileName; } protected static string GetNamedPipeServerStreamName() { if (PlatformDetection.IsInAppContainer) { return @"LOCAL\" + Guid.NewGuid().ToString("N"); } if (PlatformDetection.IsWindows) { return Guid.NewGuid().ToString("N"); } if (!PlatformDetection.IsCaseSensitiveOS) { return $"/tmp/{Guid.NewGuid().ToString("N")}"; } const int MinUdsPathLength = 104; // required min is 92, but every platform we currently target is at least 104 const int MinAvailableForSufficientRandomness = 5; // we want enough randomness in the name to avoid conflicts between concurrent tests string prefix = Path.Combine(Path.GetTempPath(), "CoreFxPipe_"); int availableLength = MinUdsPathLength - prefix.Length - 1; // 1 - for possible null terminator Assert.True(availableLength >= MinAvailableForSufficientRandomness, $"UDS prefix {prefix} length {prefix.Length} is too long"); StringBuilder sb = new(availableLength); Random random = new Random(); for (int i = 0; i < availableLength; i++) { sb.Append((char)('a' + random.Next(0, 26))); } return sb.ToString(); } // Some Windows versions like Windows Nano Server have the %TEMP% environment variable set to "C:\TEMP" but the // actual folder name is "C:\Temp", which prevents asserting path values using Assert.Equal due to case sensitiveness. // So instead of using TestDirectory directly, we retrieve the real path with proper casing of the initial folder path. private unsafe string GetTestDirectoryActualCasing() { if (!PlatformDetection.IsWindows) return TestDirectory; try { using SafeFileHandle handle = Interop.Kernel32.CreateFile( TestDirectory, dwDesiredAccess: 0, dwShareMode: FileShare.ReadWrite | FileShare.Delete, dwCreationDisposition: FileMode.Open, dwFlagsAndAttributes: Interop.Kernel32.FileOperations.OPEN_EXISTING | Interop.Kernel32.FileOperations.FILE_FLAG_BACKUP_SEMANTICS // Necessary to obtain a handle to a directory ); if (!handle.IsInvalid) { const int InitialBufferSize = 4096; char[]? buffer = ArrayPool<char>.Shared.Rent(InitialBufferSize); uint result = GetFinalPathNameByHandle(handle, buffer); // Remove extended prefix int skip = PathInternal.IsExtended(buffer) ? 4 : 0; return new string( buffer, skip, (int)result - skip); } } catch { } return TestDirectory; } private unsafe uint GetFinalPathNameByHandle(SafeFileHandle handle, char[] buffer) { fixed (char* bufPtr = buffer) { return Interop.Kernel32.GetFinalPathNameByHandle(handle, bufPtr, (uint)buffer.Length, Interop.Kernel32.FILE_NAME_NORMALIZED); } } } }
1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/Common/tests/TestUtilities/TestUtilities.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- For some reason, xunit.core.props isn't excluded in VS and sets this to true. --> <IsTestProject>false</IsTestProject> <!-- This assembly is referenced from rid agnostic configurations therefore we can't make it RID specific and instead use runtime checks. --> <TargetFrameworks>$(NetCoreAppMinimum);$(NetFrameworkMinimum)</TargetFrameworks> <EnableLibraryImportGenerator>true</EnableLibraryImportGenerator> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="$(MSBuildThisFileDirectory)ILLink.Substitutions.AggressiveTrimming.xml" LogicalName="ILLink.Substitutions.xml" Condition="'$(EnableAggressiveTrimming)' == 'true'" /> <Compile Include="System\AdminHelpers.cs" /> <Compile Include="System\AssertExtensions.cs" /> <Compile Include="System\IO\StreamExtensions.cs" /> <Compile Include="System\RetryHelper.cs" /> <Compile Include="System\Buffers\BoundedMemory.cs" /> <Compile Include="System\Buffers\BoundedMemory.Creation.cs" /> <Compile Include="System\Buffers\BoundedMemory.Unix.cs" /> <Compile Include="System\Buffers\BoundedMemory.Windows.cs" /> <Compile Include="System\Buffers\PoisonPagePlacement.cs" /> <Compile Include="System\Runtime\InteropServices\SafeBufferUtil.cs" /> <Compile Include="System\IO\FileCleanupTestBase.cs" /> <Compile Include="System\LineEndingsHelper.cs" /> <Compile Include="System\TestEnvironment.cs" /> <Compile Include="System\ThreadCultureChange.cs" /> <Compile Include="System\AssemblyPathHelper.cs" /> <!-- We don't compile per but and instead use runtime platform checks. --> <Compile Include="System\PlatformDetection.cs" /> <Compile Include="System\PlatformDetection.Unix.cs" /> <Compile Include="System\PlatformDetection.Windows.cs" /> <Compile Include="System\WindowsIdentityFixture.cs" /> <Compile Include="$(CommonPath)System\Text\ValueStringBuilder.cs" Link="Common\System\Text\ValueStringBuilder.cs" /> <!-- Interop.Library is not designed to support runtime checks therefore we are picking the Windows variant from the Common folder and adding the missing members manually. --> <Compile Include="Interop\Interop.Libraries.cs" /> <Compile Include="RandomTestCaseOrderer.cs" /> <Compile Include="RandomTestCollectionOrderer.cs" /> </ItemGroup> <!-- Windows imports --> <ItemGroup> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CreateFile.cs" Link="Common\Interop\Windows\Kernel32\Interop.CreateFile.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FileOperations.cs" Link="Common\Interop\Windows\Kernel32\Interop.FileOperations.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCurrentProcess.cs" Link="Common\Interop\Windows\Kernel32\Interop.GetCurrentProcess.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetFinalPathNameByHandle.cs" Link="Common\Interop\Windows\Kernel32\Interop.GetFinalPathNameByHandle.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SECURITY_ATTRIBUTES.cs" Link="Common\Interop\Windows\Kernel32\Interop.SECURITY_ATTRIBUTES.cs" /> <Compile Include="$(CommonPath)Interop\Windows\NtDll\Interop.RtlGetVersion.cs" Link="Common\Interop\Windows\NtDll\Interop.RtlGetVersion.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.OpenProcessToken_SafeAccessTokenHandle.cs" Link="Common\Interop\Windows\Advapi32\Interop.OpenProcessToken_SafeAccessTokenHandle.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs" Link="Common\Interop\Windows\Interop.Libraries.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CloseHandle.cs" Link="Common\Interop\Windows\Kernel32\Interop.CloseHandle.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.TOKEN_INFORMATION_CLASS.cs" Link="Common\Interop\Windows\Advapi32\Interop.TOKEN_INFORMATION_CLASS.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.GetTokenInformation_void.cs" Link="Common\Interop\Windows\Advapi32\Interop.GetTokenInformation_void.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.TOKEN_ELEVATION.cs" Link="Common\Interop\Windows\Advapi32\Interop.TOKEN_ELEVATION.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Interop.BOOL.cs" Link="Common\Interop\Windows\Interop.BOOL.cs" /> <Compile Include="$(CommonPath)System\IO\PathInternal.Windows.cs" Link="Common\System\IO\PathInternal.Windows.cs" /> </ItemGroup> <!-- Unix imports --> <ItemGroup> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.Initialization.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.Initialization.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslAvailable.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslAvailable.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslVersion.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslVersion.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslGetProtocolSupport.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslGetProtocolSupport.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.GetEUid.cs" Link="Common\Interop\Unix\Interop.GetEUid.cs" /> </ItemGroup> <!-- Android imports --> <ItemGroup> <Compile Include="$(CommonPath)Interop\Android\Interop.Libraries.cs" Link="Common\Interop\Android\Interop.Libraries.cs" /> <Compile Include="$(CommonPath)Interop\Android\System.Security.Cryptography.Native.Android\Interop.Ssl.ProtocolSupport.cs" Link="Common\Interop\Android\System.Security.Cryptography.Native.Android\Interop.Ssl.ProtocolSupport.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.DotNet.XUnitExtensions" Version="$(MicrosoftDotNetXUnitExtensionsVersion)" /> <PackageReference Include="xunit.core" Version="$(XUnitVersion)" ExcludeAssets="build" /> <PackageReference Include="xunit.assert" Version="$(XUnitVersion)" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'"> <!-- Upgrade the NetStandard.Library transitive xunit dependency to avoid 1.x NS dependencies. --> <PackageReference Include="NETStandard.Library" Version="$(NetStandardLibraryVersion)" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'"> <PackageReference Include="System.Memory" Version="$(SystemMemoryVersion)" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- For some reason, xunit.core.props isn't excluded in VS and sets this to true. --> <IsTestProject>false</IsTestProject> <!-- This assembly is referenced from rid agnostic configurations therefore we can't make it RID specific and instead use runtime checks. --> <TargetFrameworks>$(NetCoreAppMinimum);$(NetFrameworkMinimum)</TargetFrameworks> <EnableLibraryImportGenerator>true</EnableLibraryImportGenerator> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="$(MSBuildThisFileDirectory)ILLink.Substitutions.AggressiveTrimming.xml" LogicalName="ILLink.Substitutions.xml" Condition="'$(EnableAggressiveTrimming)' == 'true'" /> <Compile Include="System\AdminHelpers.cs" /> <Compile Include="System\AssertExtensions.cs" /> <Compile Include="System\IO\StreamExtensions.cs" /> <Compile Include="System\IO\PathGenerator.cs" /> <Compile Include="System\RetryHelper.cs" /> <Compile Include="System\Buffers\BoundedMemory.cs" /> <Compile Include="System\Buffers\BoundedMemory.Creation.cs" /> <Compile Include="System\Buffers\BoundedMemory.Unix.cs" /> <Compile Include="System\Buffers\BoundedMemory.Windows.cs" /> <Compile Include="System\Buffers\PoisonPagePlacement.cs" /> <Compile Include="System\Runtime\InteropServices\SafeBufferUtil.cs" /> <Compile Include="System\IO\FileCleanupTestBase.cs" /> <Compile Include="System\LineEndingsHelper.cs" /> <Compile Include="System\TestEnvironment.cs" /> <Compile Include="System\ThreadCultureChange.cs" /> <Compile Include="System\AssemblyPathHelper.cs" /> <!-- We don't compile per but and instead use runtime platform checks. --> <Compile Include="System\PlatformDetection.cs" /> <Compile Include="System\PlatformDetection.Unix.cs" /> <Compile Include="System\PlatformDetection.Windows.cs" /> <Compile Include="System\WindowsIdentityFixture.cs" /> <Compile Include="$(CommonPath)System\Text\ValueStringBuilder.cs" Link="Common\System\Text\ValueStringBuilder.cs" /> <!-- Interop.Library is not designed to support runtime checks therefore we are picking the Windows variant from the Common folder and adding the missing members manually. --> <Compile Include="Interop\Interop.Libraries.cs" /> <Compile Include="RandomTestCaseOrderer.cs" /> <Compile Include="RandomTestCollectionOrderer.cs" /> </ItemGroup> <!-- Windows imports --> <ItemGroup> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CreateFile.cs" Link="Common\Interop\Windows\Kernel32\Interop.CreateFile.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FileOperations.cs" Link="Common\Interop\Windows\Kernel32\Interop.FileOperations.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCurrentProcess.cs" Link="Common\Interop\Windows\Kernel32\Interop.GetCurrentProcess.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetFinalPathNameByHandle.cs" Link="Common\Interop\Windows\Kernel32\Interop.GetFinalPathNameByHandle.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SECURITY_ATTRIBUTES.cs" Link="Common\Interop\Windows\Kernel32\Interop.SECURITY_ATTRIBUTES.cs" /> <Compile Include="$(CommonPath)Interop\Windows\NtDll\Interop.RtlGetVersion.cs" Link="Common\Interop\Windows\NtDll\Interop.RtlGetVersion.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.OpenProcessToken_SafeAccessTokenHandle.cs" Link="Common\Interop\Windows\Advapi32\Interop.OpenProcessToken_SafeAccessTokenHandle.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs" Link="Common\Interop\Windows\Interop.Libraries.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CloseHandle.cs" Link="Common\Interop\Windows\Kernel32\Interop.CloseHandle.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.TOKEN_INFORMATION_CLASS.cs" Link="Common\Interop\Windows\Advapi32\Interop.TOKEN_INFORMATION_CLASS.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.GetTokenInformation_void.cs" Link="Common\Interop\Windows\Advapi32\Interop.GetTokenInformation_void.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.TOKEN_ELEVATION.cs" Link="Common\Interop\Windows\Advapi32\Interop.TOKEN_ELEVATION.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Interop.BOOL.cs" Link="Common\Interop\Windows\Interop.BOOL.cs" /> <Compile Include="$(CommonPath)System\IO\PathInternal.Windows.cs" Link="Common\System\IO\PathInternal.Windows.cs" /> </ItemGroup> <!-- Unix imports --> <ItemGroup> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.Initialization.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.Initialization.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslAvailable.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslAvailable.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslVersion.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslVersion.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslGetProtocolSupport.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslGetProtocolSupport.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Native\Interop.GetEUid.cs" Link="Common\Interop\Unix\Interop.GetEUid.cs" /> </ItemGroup> <!-- Android imports --> <ItemGroup> <Compile Include="$(CommonPath)Interop\Android\Interop.Libraries.cs" Link="Common\Interop\Android\Interop.Libraries.cs" /> <Compile Include="$(CommonPath)Interop\Android\System.Security.Cryptography.Native.Android\Interop.Ssl.ProtocolSupport.cs" Link="Common\Interop\Android\System.Security.Cryptography.Native.Android\Interop.Ssl.ProtocolSupport.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.DotNet.XUnitExtensions" Version="$(MicrosoftDotNetXUnitExtensionsVersion)" /> <PackageReference Include="xunit.core" Version="$(XUnitVersion)" ExcludeAssets="build" /> <PackageReference Include="xunit.assert" Version="$(XUnitVersion)" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'"> <!-- Upgrade the NetStandard.Library transitive xunit dependency to avoid 1.x NS dependencies. --> <PackageReference Include="NETStandard.Library" Version="$(NetStandardLibraryVersion)" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'"> <PackageReference Include="System.Memory" Version="$(SystemMemoryVersion)" /> </ItemGroup> </Project>
1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/System.IO.FileSystem.AccessControl/tests/FileSystemAclExtensionsTests.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.Linq; using System.Security.AccessControl; using System.Security.Principal; using Xunit; namespace System.IO { public class FileSystemAclExtensionsTests { private const int DefaultBufferSize = 4096; #region Test methods #region GetAccessControl [Fact] public void GetAccessControl_DirectoryInfo_InvalidArguments() { Assert.Throws<ArgumentNullException>(() => FileSystemAclExtensions.GetAccessControl((DirectoryInfo)null)); } [Fact] public void GetAccessControl_DirectoryInfo_ReturnsValidObject() { using var directory = new TempAclDirectory(); var directoryInfo = new DirectoryInfo(directory.Path); DirectorySecurity directorySecurity = directoryInfo.GetAccessControl(); Assert.NotNull(directorySecurity); Assert.Equal(typeof(FileSystemRights), directorySecurity.AccessRightType); } [Fact] public void GetAccessControl_DirectoryInfo_AccessControlSections_InvalidArguments() { Assert.Throws<ArgumentNullException>(() => FileSystemAclExtensions.GetAccessControl((DirectoryInfo)null, new AccessControlSections())); } [Fact] public void GetAccessControl_DirectoryInfo_AccessControlSections_ReturnsValidObject() { using var directory = new TempAclDirectory(); var directoryInfo = new DirectoryInfo(directory.Path); var accessControlSections = new AccessControlSections(); DirectorySecurity directorySecurity = directoryInfo.GetAccessControl(accessControlSections); Assert.NotNull(directorySecurity); Assert.Equal(typeof(FileSystemRights), directorySecurity.AccessRightType); } [Fact] public void GetAccessControl_FileInfo_InvalidArguments() { Assert.Throws<ArgumentNullException>(() => FileSystemAclExtensions.GetAccessControl((FileInfo)null)); } [Fact] public void GetAccessControl_FileInfo_ReturnsValidObject() { using var directory = new TempAclDirectory(); using var file = new TempFile(Path.Combine(directory.Path, "file.txt")); var fileInfo = new FileInfo(file.Path); FileSecurity fileSecurity = fileInfo.GetAccessControl(); Assert.NotNull(fileSecurity); Assert.Equal(typeof(FileSystemRights), fileSecurity.AccessRightType); } [Fact] public void GetAccessControl_FileInfo_AccessControlSections_InvalidArguments() { Assert.Throws<ArgumentNullException>(() => FileSystemAclExtensions.GetAccessControl((FileInfo)null, new AccessControlSections())); } [Fact] public void GetAccessControl_FileInfo_AccessControlSections_ReturnsValidObject() { using var directory = new TempAclDirectory(); using var file = new TempFile(Path.Combine(directory.Path, "file.txt")); var fileInfo = new FileInfo(file.Path); var accessControlSections = new AccessControlSections(); FileSecurity fileSecurity = fileInfo.GetAccessControl(accessControlSections); Assert.NotNull(fileSecurity); Assert.Equal(typeof(FileSystemRights), fileSecurity.AccessRightType); } [Fact] public void GetAccessControl_Filestream_InvalidArguments() { Assert.Throws<ArgumentNullException>("fileStream", () => FileSystemAclExtensions.GetAccessControl((FileStream)null)); } [Fact] public void GetAccessControl_Filestream_ReturnValidObject() { using var directory = new TempAclDirectory(); using var file = new TempFile(Path.Combine(directory.Path, "file.txt")); using FileStream fileStream = File.Open(file.Path, FileMode.Append, FileAccess.Write, FileShare.None); FileSecurity fileSecurity = FileSystemAclExtensions.GetAccessControl(fileStream); Assert.NotNull(fileSecurity); Assert.Equal(typeof(FileSystemRights), fileSecurity.AccessRightType); } #endregion #region SetAccessControl [Fact] public void SetAccessControl_DirectoryInfo_DirectorySecurity_InvalidArguments() { using var directory = new TempAclDirectory(); var directoryInfo = new DirectoryInfo(directory.Path); AssertExtensions.Throws<ArgumentNullException>("directorySecurity", () => directoryInfo.SetAccessControl(directorySecurity: null)); } [Fact] public void SetAccessControl_DirectoryInfo_DirectorySecurity_Success() { using var directory = new TempAclDirectory(); var directoryInfo = new DirectoryInfo(directory.Path); var directorySecurity = new DirectorySecurity(); directoryInfo.SetAccessControl(directorySecurity); } [Fact] public void SetAccessControl_FileInfo_FileSecurity_InvalidArguments() { using var directory = new TempAclDirectory(); using var file = new TempFile(Path.Combine(directory.Path, "file.txt")); var fileInfo = new FileInfo(file.Path); AssertExtensions.Throws<ArgumentNullException>("fileSecurity", () => fileInfo.SetAccessControl(fileSecurity: null)); } [Fact] public void SetAccessControl_FileInfo_FileSecurity_Success() { using var directory = new TempAclDirectory(); using var file = new TempFile(Path.Combine(directory.Path, "file.txt")); var fileInfo = new FileInfo(file.Path); var fileSecurity = new FileSecurity(); fileInfo.SetAccessControl(fileSecurity); } [Fact] public void SetAccessControl_FileStream_FileSecurity_InvalidArguments() { Assert.Throws<ArgumentNullException>("fileStream", () => FileSystemAclExtensions.SetAccessControl((FileStream)null, fileSecurity: null)); } [Fact] public void SetAccessControl_FileStream_FileSecurity_InvalidFileSecurityObject() { using var directory = new TempAclDirectory(); using var file = new TempFile(Path.Combine(directory.Path, "file.txt")); using FileStream fileStream = File.Open(file.Path, FileMode.Append, FileAccess.Write, FileShare.None); AssertExtensions.Throws<ArgumentNullException>("fileSecurity", () => FileSystemAclExtensions.SetAccessControl(fileStream, fileSecurity: null)); } [Fact] public void SetAccessControl_FileStream_FileSecurity_Success() { using var directory = new TempAclDirectory(); using var file = new TempFile(Path.Combine(directory.Path, "file.txt")); using FileStream fileStream = File.Open(file.Path, FileMode.Append, FileAccess.Write, FileShare.None); var fileSecurity = new FileSecurity(); FileSystemAclExtensions.SetAccessControl(fileStream, fileSecurity); } #endregion #region DirectoryInfo Create [Fact] public void DirectoryInfo_Create_NullDirectoryInfo() { DirectoryInfo info = null; var security = new DirectorySecurity(); Assert.Throws<ArgumentNullException>("directoryInfo", () => CreateDirectoryWithSecurity(info, security)); } [Fact] public void DirectoryInfo_Create_NullDirectorySecurity() { var info = new DirectoryInfo("path"); Assert.Throws<ArgumentNullException>("directorySecurity", () => CreateDirectoryWithSecurity(info, null)); } [Fact] public void DirectoryInfo_Create_NotFound() { using var tempRootDir = new TempAclDirectory(); string dirPath = Path.Combine(tempRootDir.Path, Guid.NewGuid().ToString(), "ParentDoesNotExist"); var dirInfo = new DirectoryInfo(dirPath); var security = new DirectorySecurity(); // Fails because the DirectorySecurity lacks any rights to create parent folder Assert.Throws<UnauthorizedAccessException>(() => CreateDirectoryWithSecurity(dirInfo, security)); } [Fact] public void DirectoryInfo_Create_NotFound_FullControl() { using var tempRootDir = new TempAclDirectory(); string dirPath = Path.Combine(tempRootDir.Path, Guid.NewGuid().ToString(), "ParentDoesNotExist"); var dirInfo = new DirectoryInfo(dirPath); var security = GetDirectorySecurity(FileSystemRights.FullControl); // Succeeds because it creates the missing parent folder CreateDirectoryWithSecurity(dirInfo, security); } private void CreateDirectoryWithSecurity(DirectoryInfo info, DirectorySecurity security) { if (PlatformDetection.IsNetFramework) { FileSystemAclExtensions.Create(info, security); } else { info.Create(security); } } [Fact] public void DirectoryInfo_Create_DefaultDirectorySecurity() { var security = new DirectorySecurity(); Verify_DirectorySecurity_CreateDirectory(security); } [Theory] // Must have at least one ReadData, otherwise the TempAclDirectory will fail to delete that item on dispose [MemberData(nameof(RightsToAllow))] public void DirectoryInfo_Create_AllowSpecific_AccessRules(FileSystemRights rights) { using var tempRootDir = new TempAclDirectory(); string path = Path.Combine(tempRootDir.Path, "directory"); var dirInfo = new DirectoryInfo(path); DirectorySecurity expectedSecurity = GetDirectorySecurity(rights); dirInfo.Create(expectedSecurity); Assert.True(dirInfo.Exists); tempRootDir.CreatedSubdirectories.Add(dirInfo); var actualInfo = new DirectoryInfo(dirInfo.FullName); DirectorySecurity actualSecurity = actualInfo.GetAccessControl(AccessControlSections.Access); VerifyAccessSecurity(expectedSecurity, actualSecurity); } [Theory] [MemberData(nameof(RightsToDeny))] public void DirectoryInfo_Create_DenySpecific_AddAccessRules(FileSystemRights rightsToDeny) { var expectedSecurity = new DirectorySecurity(); var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); var allowAccessRule = new FileSystemAccessRule(identity, FileSystemRights.Read, AccessControlType.Allow); expectedSecurity.AddAccessRule(allowAccessRule); var denyAccessRule = new FileSystemAccessRule(identity, rightsToDeny, AccessControlType.Deny); expectedSecurity.AddAccessRule(denyAccessRule); using var tempRootDir = new TempAclDirectory(); string path = Path.Combine(tempRootDir.Path, "directory"); var dirInfo = new DirectoryInfo(path); dirInfo.Create(expectedSecurity); Assert.True(dirInfo.Exists); tempRootDir.CreatedSubdirectories.Add(dirInfo); var actualInfo = new DirectoryInfo(dirInfo.FullName); DirectorySecurity actualSecurity = actualInfo.GetAccessControl(AccessControlSections.Access); VerifyAccessSecurity(expectedSecurity, actualSecurity); } #endregion #region FileInfo Create [Fact] public void FileInfo_Create_NullFileInfo() { FileInfo info = null; var security = new FileSecurity(); Assert.Throws<ArgumentNullException>("fileInfo", () => info.Create(FileMode.CreateNew, FileSystemRights.FullControl, FileShare.None, DefaultBufferSize, FileOptions.None, security)); } [Fact] public void FileInfo_Create_DirectoryNotFound() { using var tempRootDir = new TempAclDirectory(); string path = Path.Combine(tempRootDir.Path, Guid.NewGuid().ToString(), "file.txt"); var info = new FileInfo(path); var security = new FileSecurity(); Assert.Throws<DirectoryNotFoundException>(() => info.Create(FileMode.CreateNew, FileSystemRights.FullControl, FileShare.None, DefaultBufferSize, FileOptions.None, security)); } [Theory] [InlineData((FileMode)int.MinValue)] [InlineData((FileMode)0)] [InlineData((FileMode)int.MaxValue)] public void FileInfo_Create_FileSecurity_OutOfRange_FileMode(FileMode invalidMode) => FileInfo_Create_FileSecurity_ArgumentOutOfRangeException("mode", mode: invalidMode); [Theory] [InlineData((FileShare)(-1))] [InlineData((FileShare)int.MaxValue)] public void FileInfo_Create_FileSecurity_OutOfRange_FileShare(FileShare invalidFileShare) => FileInfo_Create_FileSecurity_ArgumentOutOfRangeException("share", share: invalidFileShare); [Theory] [InlineData(int.MinValue)] [InlineData(0)] public void FileInfo_Create_FileSecurity_OutOfRange_BufferSize(int invalidBufferSize) => FileInfo_Create_FileSecurity_ArgumentOutOfRangeException("bufferSize", bufferSize: invalidBufferSize); public static IEnumerable<object[]> WriteModes_ReadRights_ForbiddenCombo_Data() => from mode in s_writableModes from rights in s_readableRights where // These combinations are allowed, exclude them !(rights == FileSystemRights.CreateFiles && (mode == FileMode.Append || mode == FileMode.Create || mode == FileMode.CreateNew)) select new object[] { mode, rights }; // Do not combine writing modes with exclusively read rights [Theory] [MemberData(nameof(WriteModes_ReadRights_ForbiddenCombo_Data))] public void FileInfo_Create_FileSecurity_WriteModes_ReadRights_ForbiddenCombo(FileMode mode, FileSystemRights rights) => FileInfo_Create_FileSecurity_ArgumentException(mode, rights); public static IEnumerable<object[]> OpenOrCreateMode_ReadRights_AllowedCombo_Data() => from rights in s_readableRights select new object[] { rights }; // OpenOrCreate allows using exclusively read rights [Theory] [MemberData(nameof(OpenOrCreateMode_ReadRights_AllowedCombo_Data))] public void FileInfo_Create_FileSecurity_OpenOrCreateMode_ReadRights_AllowedCombo(FileSystemRights rights) => FileInfo_Create_FileSecurity_Successful(FileMode.OpenOrCreate, rights); // Append, Create and CreateNew allow using CreateFiles rights // These combinations were excluded from WriteModes_ReadRights_ForbiddenCombo_Data [Theory] [InlineData(FileMode.Append)] [InlineData(FileMode.Create)] [InlineData(FileMode.CreateNew)] public void FileInfo_Create_FileSecurity_WriteModes_CreateFilesRights_AllowedCombo(FileMode mode) => FileInfo_Create_FileSecurity_Successful(mode, FileSystemRights.CreateFiles); public static IEnumerable<object[]> AppendMode_UnexpectedReadRights_Data() => from writeRights in s_writableRights from readRights in new[] { FileSystemRights.ExecuteFile, FileSystemRights.ReadAttributes, FileSystemRights.ReadData, FileSystemRights.ReadExtendedAttributes, FileSystemRights.ReadPermissions, FileSystemRights.Read, // Contains ReadAttributes, ReadData, ReadExtendedAttributes, ReadPermissions FileSystemRights.ReadAndExecute, // Contains Read and ExecuteFile } select new object[] { writeRights | readRights }; // Append is allowed if at least one write permission is provided // But append is disallowed if any read rights are provided [Theory] [MemberData(nameof(AppendMode_UnexpectedReadRights_Data))] public void FileInfo_Create_FileSecurity_AppendMode_UnexpectedReadRights(FileSystemRights rights) => FileInfo_Create_FileSecurity_ArgumentException(FileMode.Append, rights); public static IEnumerable<object[]> AppendMode_OnlyWriteRights_Data() => from writeRights in s_writableRights select new object[] { writeRights }; // Append succeeds if only write permissions were provided (no read permissions) [Theory] [MemberData(nameof(AppendMode_OnlyWriteRights_Data))] public void FileInfo_Create_FileSecurity_AppendMode_OnlyWriteRights(FileSystemRights rights) => FileInfo_Create_FileSecurity_Successful(FileMode.Append, rights); public static IEnumerable<object[]> WritableRights_Data() => from rights in s_writableRights select new object[] { rights }; // Cannot truncate unless all write rights are provided [Theory] [MemberData(nameof(WritableRights_Data))] public void FileInfo_Create_FileSecurity_TruncateMode_IncompleteWriteRights(FileSystemRights rights) => FileInfo_Create_FileSecurity_ArgumentException(FileMode.Truncate, rights); [Fact] public void FileInfo_Create_FileSecurity_TruncateMode_AllWriteRights_Throws() { // Truncate, with all write rights, throws with different messages in each framework: // - In .NET Framework, throws "Could not find file" // - In .NET, throws IOException: "The parameter is incorrect" var security = new FileSecurity(); var info = new FileInfo(Guid.NewGuid().ToString()); Assert.Throws<IOException>(() => info.Create(FileMode.Truncate, FileSystemRights.Write | FileSystemRights.ReadData, FileShare.None, DefaultBufferSize, FileOptions.None, security)); } public static IEnumerable<object[]> WriteRights_AllArguments_Data() => from mode in s_writableModes from rights in s_writableRights from share in Enum.GetValues<FileShare>() from options in Enum.GetValues<FileOptions>() where !(rights == FileSystemRights.CreateFiles && (mode == FileMode.Append || mode == FileMode.Create || mode == FileMode.CreateNew)) && !(mode == FileMode.Truncate && rights != FileSystemRights.Write) && (options != FileOptions.Encrypted && // Using FileOptions.Encrypted throws UnauthorizedAccessException when attempting to read the created file !(options == FileOptions.Asynchronous && !PlatformDetection.IsAsyncFileIOSupported))// Async IO not supported on Windows using Mono runtime https://github.com/dotnet/runtime/issues/34582 select new object[] { mode, rights, share, options }; [Theory] [MemberData(nameof(WriteRights_AllArguments_Data))] public void FileInfo_WriteRights_WithSecurity_Null(FileMode mode, FileSystemRights rights, FileShare share, FileOptions options) => Verify_FileSecurity_CreateFile(mode, rights, share, DefaultBufferSize, options, expectedSecurity: null); // Null security [Theory] [MemberData(nameof(WriteRights_AllArguments_Data))] public void FileInfo_WriteRights_WithSecurity_Default(FileMode mode, FileSystemRights rights, FileShare share, FileOptions options) => Verify_FileSecurity_CreateFile(mode, rights, share, DefaultBufferSize, options, new FileSecurity()); // Default security [Theory] [MemberData(nameof(WriteRights_AllArguments_Data))] public void FileInfo_WriteRights_WithSecurity_Custom(FileMode mode, FileSystemRights rights, FileShare share, FileOptions options) => Verify_FileSecurity_CreateFile(mode, rights, share, DefaultBufferSize, options, GetFileSecurity(rights)); // Custom security (AccessRule Allow) public static IEnumerable<object[]> ReadRights_AllArguments_Data() => from mode in new[] { FileMode.Create, FileMode.CreateNew, FileMode.OpenOrCreate } from rights in s_readableRights from share in Enum.GetValues<FileShare>() from options in Enum.GetValues<FileOptions>() where options != FileOptions.Encrypted && // Using FileOptions.Encrypted throws UnauthorizedAccessException when attempting to read the created file !(options == FileOptions.Asynchronous && !PlatformDetection.IsAsyncFileIOSupported) // Async IO not supported on Windows using Mono runtime https://github.com/dotnet/runtime/issues/34582 select new object[] { mode, rights, share, options }; [Theory] [MemberData(nameof(ReadRights_AllArguments_Data))] public void FileInfo_ReadRights_WithSecurity_Null(FileMode mode, FileSystemRights rights, FileShare share, FileOptions options) => // Writable FileModes require at least one write right Verify_FileSecurity_CreateFile(mode, rights | FileSystemRights.WriteData, share, DefaultBufferSize, options, expectedSecurity: null); // Null security [Theory] [MemberData(nameof(ReadRights_AllArguments_Data))] public void FileInfo_ReadRights_WithSecurity_Default(FileMode mode, FileSystemRights rights, FileShare share, FileOptions options) => // Writable FileModes require at least one write right Verify_FileSecurity_CreateFile(mode, rights | FileSystemRights.WriteData, share, DefaultBufferSize, options, new FileSecurity()); // Default security [Theory] [MemberData(nameof(ReadRights_AllArguments_Data))] public void FileInfo_ReadRights_WithSecurity_Custom(FileMode mode, FileSystemRights rights, FileShare share, FileOptions options) => // Writable FileModes require at least one write right Verify_FileSecurity_CreateFile(mode, rights | FileSystemRights.WriteData, share, DefaultBufferSize, options, GetFileSecurity(rights)); // Custom security (AccessRule Allow) [Theory] [MemberData(nameof(RightsToDeny))] public void FileInfo_Create_FileSecurity_DenyAccessRule(FileSystemRights rightsToDeny) { var expectedSecurity = new FileSecurity(); var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); // Add write deny rule var denyAccessRule = new FileSystemAccessRule(identity, rightsToDeny, AccessControlType.Deny); expectedSecurity.AddAccessRule(denyAccessRule); using var tempRootDir = new TempAclDirectory(); string path = Path.Combine(tempRootDir.Path, Guid.NewGuid().ToString()); var fileInfo = new FileInfo(path); using FileStream stream = fileInfo.Create( FileMode.CreateNew, FileSystemRights.Write, // Create expects at least one write right FileShare.None, DefaultBufferSize, FileOptions.None, expectedSecurity); Assert.True(fileInfo.Exists); tempRootDir.CreatedSubfiles.Add(fileInfo); var actualInfo = new FileInfo(fileInfo.FullName); FileSecurity actualSecurity = actualInfo.GetAccessControl(AccessControlSections.Access); VerifyAccessSecurity(expectedSecurity, actualSecurity); } #endregion #region DirectorySecurity CreateDirectory [Fact] public void DirectorySecurity_CreateDirectory_NullSecurity() { DirectorySecurity security = null; string path = "whatever"; Assert.Throws<ArgumentNullException>("directorySecurity", () => security.CreateDirectory(path)); Assert.Throws<ArgumentNullException>("directorySecurity", () => FileSystemAclExtensions.CreateDirectory(security, path)); } [Fact] public void DirectorySecurity_CreateDirectory_InvalidPath() { var security = new DirectorySecurity(); Assert.Throws<ArgumentNullException>("path", () => security.CreateDirectory(null)); Assert.Throws<ArgumentException>(() => security.CreateDirectory("")); } [Fact] public void DirectorySecurity_CreateDirectory_DirectoryAlreadyExists() { using var tempRootDir = new TempAclDirectory(); string path = Path.Combine(tempRootDir.Path, Guid.NewGuid().ToString()); DirectorySecurity expectedSecurity = GetDirectorySecurity(FileSystemRights.FullControl); DirectoryInfo dirInfo = expectedSecurity.CreateDirectory(path); Assert.True(dirInfo.Exists); tempRootDir.CreatedSubdirectories.Add(dirInfo); var basicSecurity = new DirectorySecurity(); // Already exists, existingDirInfo should have the original security, not the new basic security DirectoryInfo existingDirInfo = basicSecurity.CreateDirectory(path); DirectorySecurity actualSecurity = existingDirInfo.GetAccessControl(AccessControlSections.Access); VerifyAccessSecurity(expectedSecurity, actualSecurity); } #endregion #endregion #region Helper methods public static IEnumerable<object[]> RightsToDeny() => from rights in new[] { FileSystemRights.AppendData, // Same as CreateDirectories FileSystemRights.ChangePermissions, FileSystemRights.Delete, FileSystemRights.DeleteSubdirectoriesAndFiles, FileSystemRights.ExecuteFile, // Same as Traverse FileSystemRights.ReadAttributes, FileSystemRights.ReadExtendedAttributes, FileSystemRights.ReadPermissions, FileSystemRights.TakeOwnership, FileSystemRights.Write, // Contains AppendData, WriteData, WriteAttributes, WriteExtendedAttributes FileSystemRights.WriteAttributes, FileSystemRights.WriteData, // Same as CreateFiles FileSystemRights.WriteExtendedAttributes, // Rights that should not be denied: // - Synchronize: CreateFile always requires Synchronize access // - ReadData: Minimum right required to delete a file or directory // - ListDirectory: Equivalent to ReadData // - Modify: Contains ReadData // - Read: Contains ReadData // - ReadAndExecute: Contains ReadData // - FullControl: Contains ReadData and Synchronize } select new object[] { rights }; public static IEnumerable<object[]> RightsToAllow() => from rights in new[] { FileSystemRights.AppendData, // Same as CreateDirectories FileSystemRights.ChangePermissions, FileSystemRights.Delete, FileSystemRights.DeleteSubdirectoriesAndFiles, FileSystemRights.ExecuteFile, // Same as Traverse FileSystemRights.Modify, // Contains Read, Write and ReadAndExecute FileSystemRights.Read, // Contains ReadData, ReadPermissions, ReadAttributes, ReadExtendedAttributes FileSystemRights.ReadAndExecute, // Contains Read and ExecuteFile FileSystemRights.ReadAttributes, FileSystemRights.ReadData, // Minimum right required to delete a file or directory. Equivalent to ListDirectory FileSystemRights.ReadExtendedAttributes, FileSystemRights.ReadPermissions, FileSystemRights.Synchronize, // CreateFile always requires Synchronize access FileSystemRights.TakeOwnership, FileSystemRights.Write, // Contains AppendData, WriteData, WriteAttributes, WriteExtendedAttributes FileSystemRights.WriteAttributes, FileSystemRights.WriteData, // Same as CreateFiles FileSystemRights.WriteExtendedAttributes, FileSystemRights.FullControl, // Contains Modify, DeleteSubdirectoriesAndFiles, Delete, ChangePermissions, TakeOwnership, Synchronize } select new object[] { rights }; private static readonly FileMode[] s_writableModes = new[] { FileMode.Append, FileMode.Create, FileMode.CreateNew, FileMode.Truncate // Excludes OpenOrCreate because it has a different behavior compared to Create/CreateNew }; private static readonly FileSystemRights[] s_readableRights = new[] { // Excludes combined rights FileSystemRights.ExecuteFile, FileSystemRights.ReadAttributes, FileSystemRights.ReadData, FileSystemRights.ReadExtendedAttributes, FileSystemRights.ReadPermissions }; private static readonly FileSystemRights[] s_writableRights = new[] { // Excludes combined rights FileSystemRights.AppendData, // Same as CreateDirectories FileSystemRights.WriteAttributes, FileSystemRights.WriteData, FileSystemRights.WriteExtendedAttributes }; private void FileInfo_Create_FileSecurity_ArgumentOutOfRangeException(string paramName, FileMode mode = FileMode.CreateNew, FileShare share = FileShare.None, int bufferSize = DefaultBufferSize) { var security = new FileSecurity(); var info = new FileInfo(Guid.NewGuid().ToString()); Assert.Throws<ArgumentOutOfRangeException>(paramName, () => info.Create(mode, FileSystemRights.FullControl, share, bufferSize, FileOptions.None, security)); } private void FileInfo_Create_FileSecurity_ArgumentException(FileMode mode, FileSystemRights rights) { var security = new FileSecurity(); var info = new FileInfo(Guid.NewGuid().ToString()); Assert.Throws<ArgumentException>(() => info.Create(mode, rights, FileShare.None, DefaultBufferSize, FileOptions.None, security)); } private void FileInfo_Create_FileSecurity_Successful(FileMode mode, FileSystemRights rights) { var security = new FileSecurity(); var info = new FileInfo(Guid.NewGuid().ToString()); info.Create(mode, rights, FileShare.None, DefaultBufferSize, FileOptions.None, security).Dispose(); } private void Verify_FileSecurity_CreateFile(FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity expectedSecurity) { using var tempRootDir = new TempAclDirectory(); string path = Path.Combine(tempRootDir.Path, Guid.NewGuid().ToString()); var fileInfo = new FileInfo(path); using (FileStream fs = fileInfo.Create(mode, rights, share, bufferSize, options, expectedSecurity)) { Assert.True(fileInfo.Exists); tempRootDir.CreatedSubfiles.Add(fileInfo); var actualFileInfo = new FileInfo(path); FileSecurity actualSecurity = actualFileInfo.GetAccessControl(); if (expectedSecurity != null) { VerifyAccessSecurity(expectedSecurity, actualSecurity); } else { int count = actualSecurity.GetAccessRules(includeExplicit: true, includeInherited: false, typeof(SecurityIdentifier)).Count; Assert.Equal(0, count); } } } private void Verify_DirectorySecurity_CreateDirectory(DirectorySecurity expectedSecurity) { using var tempRootDir = new TempAclDirectory(); string path = Path.Combine(tempRootDir.Path, Guid.NewGuid().ToString()); DirectoryInfo dirInfo = expectedSecurity.CreateDirectory(path); Assert.True(dirInfo.Exists); tempRootDir.CreatedSubdirectories.Add(dirInfo); var actualDirInfo = new DirectoryInfo(path); DirectorySecurity actualSecurity = actualDirInfo.GetAccessControl(AccessControlSections.Access); VerifyAccessSecurity(expectedSecurity, actualSecurity); } private DirectorySecurity GetDirectorySecurity(FileSystemRights rights) { var security = new DirectorySecurity(); var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); var accessRule = new FileSystemAccessRule(identity, rights, AccessControlType.Allow); security.AddAccessRule(accessRule); return security; } private FileSecurity GetFileSecurity(FileSystemRights rights) { var security = new FileSecurity(); var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); var accessRule = new FileSystemAccessRule(identity, rights, AccessControlType.Allow); security.AddAccessRule(accessRule); return security; } private void VerifyAccessSecurity(CommonObjectSecurity expectedSecurity, CommonObjectSecurity actualSecurity) { Assert.Equal(typeof(FileSystemRights), expectedSecurity.AccessRightType); Assert.Equal(typeof(FileSystemRights), actualSecurity.AccessRightType); List<FileSystemAccessRule> expectedAccessRules = expectedSecurity.GetAccessRules(includeExplicit: true, includeInherited: false, typeof(SecurityIdentifier)) .Cast<FileSystemAccessRule>().ToList(); List<FileSystemAccessRule> actualAccessRules = actualSecurity.GetAccessRules(includeExplicit: true, includeInherited: false, typeof(SecurityIdentifier)) .Cast<FileSystemAccessRule>().ToList(); Assert.Equal(expectedAccessRules.Count, actualAccessRules.Count); if (expectedAccessRules.Count > 0) { Assert.All(expectedAccessRules, actualAccessRule => { int count = expectedAccessRules.Count(expectedAccessRule => AreAccessRulesEqual(expectedAccessRule, actualAccessRule)); Assert.True(count > 0); }); } } private bool AreAccessRulesEqual(FileSystemAccessRule expectedRule, FileSystemAccessRule actualRule) { return expectedRule.AccessControlType == actualRule.AccessControlType && expectedRule.FileSystemRights == actualRule.FileSystemRights && expectedRule.InheritanceFlags == actualRule.InheritanceFlags && expectedRule.PropagationFlags == actualRule.PropagationFlags; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using System.Security.AccessControl; using System.Security.Principal; using Xunit; namespace System.IO { public class FileSystemAclExtensionsTests { private const int DefaultBufferSize = 4096; #region Test methods #region GetAccessControl [Fact] public void GetAccessControl_DirectoryInfo_InvalidArguments() { Assert.Throws<ArgumentNullException>(() => FileSystemAclExtensions.GetAccessControl((DirectoryInfo)null)); } [Fact] public void GetAccessControl_DirectoryInfo_ReturnsValidObject() { using var directory = new TempAclDirectory(); var directoryInfo = new DirectoryInfo(directory.Path); DirectorySecurity directorySecurity = directoryInfo.GetAccessControl(); Assert.NotNull(directorySecurity); Assert.Equal(typeof(FileSystemRights), directorySecurity.AccessRightType); } [Fact] public void GetAccessControl_DirectoryInfo_AccessControlSections_InvalidArguments() { Assert.Throws<ArgumentNullException>(() => FileSystemAclExtensions.GetAccessControl((DirectoryInfo)null, new AccessControlSections())); } [Fact] public void GetAccessControl_DirectoryInfo_AccessControlSections_ReturnsValidObject() { using var directory = new TempAclDirectory(); var directoryInfo = new DirectoryInfo(directory.Path); var accessControlSections = new AccessControlSections(); DirectorySecurity directorySecurity = directoryInfo.GetAccessControl(accessControlSections); Assert.NotNull(directorySecurity); Assert.Equal(typeof(FileSystemRights), directorySecurity.AccessRightType); } [Fact] public void GetAccessControl_FileInfo_InvalidArguments() { Assert.Throws<ArgumentNullException>(() => FileSystemAclExtensions.GetAccessControl((FileInfo)null)); } [Fact] public void GetAccessControl_FileInfo_ReturnsValidObject() { using var directory = new TempAclDirectory(); using var file = new TempFile(Path.Combine(directory.Path, "file.txt")); var fileInfo = new FileInfo(file.Path); FileSecurity fileSecurity = fileInfo.GetAccessControl(); Assert.NotNull(fileSecurity); Assert.Equal(typeof(FileSystemRights), fileSecurity.AccessRightType); } [Fact] public void GetAccessControl_FileInfo_AccessControlSections_InvalidArguments() { Assert.Throws<ArgumentNullException>(() => FileSystemAclExtensions.GetAccessControl((FileInfo)null, new AccessControlSections())); } [Fact] public void GetAccessControl_FileInfo_AccessControlSections_ReturnsValidObject() { using var directory = new TempAclDirectory(); using var file = new TempFile(Path.Combine(directory.Path, "file.txt")); var fileInfo = new FileInfo(file.Path); var accessControlSections = new AccessControlSections(); FileSecurity fileSecurity = fileInfo.GetAccessControl(accessControlSections); Assert.NotNull(fileSecurity); Assert.Equal(typeof(FileSystemRights), fileSecurity.AccessRightType); } [Fact] public void GetAccessControl_Filestream_InvalidArguments() { Assert.Throws<ArgumentNullException>("fileStream", () => FileSystemAclExtensions.GetAccessControl((FileStream)null)); } [Fact] public void GetAccessControl_Filestream_ReturnValidObject() { using var directory = new TempAclDirectory(); using var file = new TempFile(Path.Combine(directory.Path, "file.txt")); using FileStream fileStream = File.Open(file.Path, FileMode.Append, FileAccess.Write, FileShare.None); FileSecurity fileSecurity = FileSystemAclExtensions.GetAccessControl(fileStream); Assert.NotNull(fileSecurity); Assert.Equal(typeof(FileSystemRights), fileSecurity.AccessRightType); } #endregion #region SetAccessControl [Fact] public void SetAccessControl_DirectoryInfo_DirectorySecurity_InvalidArguments() { using var directory = new TempAclDirectory(); var directoryInfo = new DirectoryInfo(directory.Path); AssertExtensions.Throws<ArgumentNullException>("directorySecurity", () => directoryInfo.SetAccessControl(directorySecurity: null)); } [Fact] public void SetAccessControl_DirectoryInfo_DirectorySecurity_Success() { using var directory = new TempAclDirectory(); var directoryInfo = new DirectoryInfo(directory.Path); var directorySecurity = new DirectorySecurity(); directoryInfo.SetAccessControl(directorySecurity); } [Fact] public void SetAccessControl_FileInfo_FileSecurity_InvalidArguments() { using var directory = new TempAclDirectory(); using var file = new TempFile(Path.Combine(directory.Path, "file.txt")); var fileInfo = new FileInfo(file.Path); AssertExtensions.Throws<ArgumentNullException>("fileSecurity", () => fileInfo.SetAccessControl(fileSecurity: null)); } [Fact] public void SetAccessControl_FileInfo_FileSecurity_Success() { using var directory = new TempAclDirectory(); using var file = new TempFile(Path.Combine(directory.Path, "file.txt")); var fileInfo = new FileInfo(file.Path); var fileSecurity = new FileSecurity(); fileInfo.SetAccessControl(fileSecurity); } [Fact] public void SetAccessControl_FileStream_FileSecurity_InvalidArguments() { Assert.Throws<ArgumentNullException>("fileStream", () => FileSystemAclExtensions.SetAccessControl((FileStream)null, fileSecurity: null)); } [Fact] public void SetAccessControl_FileStream_FileSecurity_InvalidFileSecurityObject() { using var directory = new TempAclDirectory(); using var file = new TempFile(Path.Combine(directory.Path, "file.txt")); using FileStream fileStream = File.Open(file.Path, FileMode.Append, FileAccess.Write, FileShare.None); AssertExtensions.Throws<ArgumentNullException>("fileSecurity", () => FileSystemAclExtensions.SetAccessControl(fileStream, fileSecurity: null)); } [Fact] public void SetAccessControl_FileStream_FileSecurity_Success() { using var directory = new TempAclDirectory(); using var file = new TempFile(Path.Combine(directory.Path, "file.txt")); using FileStream fileStream = File.Open(file.Path, FileMode.Append, FileAccess.Write, FileShare.None); var fileSecurity = new FileSecurity(); FileSystemAclExtensions.SetAccessControl(fileStream, fileSecurity); } #endregion #region DirectoryInfo Create [Fact] public void DirectoryInfo_Create_NullDirectoryInfo() { DirectoryInfo info = null; var security = new DirectorySecurity(); Assert.Throws<ArgumentNullException>("directoryInfo", () => CreateDirectoryWithSecurity(info, security)); } [Fact] public void DirectoryInfo_Create_NullDirectorySecurity() { var info = new DirectoryInfo("path"); Assert.Throws<ArgumentNullException>("directorySecurity", () => CreateDirectoryWithSecurity(info, null)); } [Fact] public void DirectoryInfo_Create_NotFound() { using var tempRootDir = new TempAclDirectory(); string dirPath = Path.Combine(tempRootDir.GenerateSubItemPath(), "ParentDoesNotExist"); var dirInfo = new DirectoryInfo(dirPath); var security = new DirectorySecurity(); // Fails because the DirectorySecurity lacks any rights to create parent folder Assert.Throws<UnauthorizedAccessException>(() => CreateDirectoryWithSecurity(dirInfo, security)); } [Fact] public void DirectoryInfo_Create_NotFound_FullControl() { using var tempRootDir = new TempAclDirectory(); string dirPath = Path.Combine(tempRootDir.GenerateSubItemPath(), "ParentDoesNotExist"); var dirInfo = new DirectoryInfo(dirPath); var security = GetDirectorySecurity(FileSystemRights.FullControl); // Succeeds because it creates the missing parent folder CreateDirectoryWithSecurity(dirInfo, security); } private void CreateDirectoryWithSecurity(DirectoryInfo info, DirectorySecurity security) { if (PlatformDetection.IsNetFramework) { FileSystemAclExtensions.Create(info, security); } else { info.Create(security); } } [Fact] public void DirectoryInfo_Create_DefaultDirectorySecurity() { var security = new DirectorySecurity(); Verify_DirectorySecurity_CreateDirectory(security); } [Theory] // Must have at least one ReadData, otherwise the TempAclDirectory will fail to delete that item on dispose [MemberData(nameof(RightsToAllow))] public void DirectoryInfo_Create_AllowSpecific_AccessRules(FileSystemRights rights) { using var tempRootDir = new TempAclDirectory(); string path = Path.Combine(tempRootDir.Path, "directory"); var dirInfo = new DirectoryInfo(path); DirectorySecurity expectedSecurity = GetDirectorySecurity(rights); dirInfo.Create(expectedSecurity); Assert.True(dirInfo.Exists); tempRootDir.CreatedSubdirectories.Add(dirInfo); var actualInfo = new DirectoryInfo(dirInfo.FullName); DirectorySecurity actualSecurity = actualInfo.GetAccessControl(AccessControlSections.Access); VerifyAccessSecurity(expectedSecurity, actualSecurity); } [Theory] [MemberData(nameof(RightsToDeny))] public void DirectoryInfo_Create_DenySpecific_AddAccessRules(FileSystemRights rightsToDeny) { var expectedSecurity = new DirectorySecurity(); var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); var allowAccessRule = new FileSystemAccessRule(identity, FileSystemRights.Read, AccessControlType.Allow); expectedSecurity.AddAccessRule(allowAccessRule); var denyAccessRule = new FileSystemAccessRule(identity, rightsToDeny, AccessControlType.Deny); expectedSecurity.AddAccessRule(denyAccessRule); using var tempRootDir = new TempAclDirectory(); string path = Path.Combine(tempRootDir.Path, "directory"); var dirInfo = new DirectoryInfo(path); dirInfo.Create(expectedSecurity); Assert.True(dirInfo.Exists); tempRootDir.CreatedSubdirectories.Add(dirInfo); var actualInfo = new DirectoryInfo(dirInfo.FullName); DirectorySecurity actualSecurity = actualInfo.GetAccessControl(AccessControlSections.Access); VerifyAccessSecurity(expectedSecurity, actualSecurity); } #endregion #region FileInfo Create [Fact] public void FileInfo_Create_NullFileInfo() { FileInfo info = null; var security = new FileSecurity(); Assert.Throws<ArgumentNullException>("fileInfo", () => info.Create(FileMode.CreateNew, FileSystemRights.FullControl, FileShare.None, DefaultBufferSize, FileOptions.None, security)); } [Fact] public void FileInfo_Create_DirectoryNotFound() { using var tempRootDir = new TempAclDirectory(); string path = Path.Combine(tempRootDir.GenerateSubItemPath(), "file.txt"); var info = new FileInfo(path); var security = new FileSecurity(); Assert.Throws<DirectoryNotFoundException>(() => info.Create(FileMode.CreateNew, FileSystemRights.FullControl, FileShare.None, DefaultBufferSize, FileOptions.None, security)); } [Theory] [InlineData((FileMode)int.MinValue)] [InlineData((FileMode)0)] [InlineData((FileMode)int.MaxValue)] public void FileInfo_Create_FileSecurity_OutOfRange_FileMode(FileMode invalidMode) => FileInfo_Create_FileSecurity_ArgumentOutOfRangeException("mode", mode: invalidMode); [Theory] [InlineData((FileShare)(-1))] [InlineData((FileShare)int.MaxValue)] public void FileInfo_Create_FileSecurity_OutOfRange_FileShare(FileShare invalidFileShare) => FileInfo_Create_FileSecurity_ArgumentOutOfRangeException("share", share: invalidFileShare); [Theory] [InlineData(int.MinValue)] [InlineData(0)] public void FileInfo_Create_FileSecurity_OutOfRange_BufferSize(int invalidBufferSize) => FileInfo_Create_FileSecurity_ArgumentOutOfRangeException("bufferSize", bufferSize: invalidBufferSize); public static IEnumerable<object[]> WriteModes_ReadRights_ForbiddenCombo_Data() => from mode in s_writableModes from rights in s_readableRights where // These combinations are allowed, exclude them !(rights == FileSystemRights.CreateFiles && (mode == FileMode.Append || mode == FileMode.Create || mode == FileMode.CreateNew)) select new object[] { mode, rights }; // Do not combine writing modes with exclusively read rights [Theory] [MemberData(nameof(WriteModes_ReadRights_ForbiddenCombo_Data))] public void FileInfo_Create_FileSecurity_WriteModes_ReadRights_ForbiddenCombo(FileMode mode, FileSystemRights rights) => FileInfo_Create_FileSecurity_ArgumentException(mode, rights); public static IEnumerable<object[]> OpenOrCreateMode_ReadRights_AllowedCombo_Data() => from rights in s_readableRights select new object[] { rights }; // OpenOrCreate allows using exclusively read rights [Theory] [MemberData(nameof(OpenOrCreateMode_ReadRights_AllowedCombo_Data))] public void FileInfo_Create_FileSecurity_OpenOrCreateMode_ReadRights_AllowedCombo(FileSystemRights rights) => FileInfo_Create_FileSecurity_Successful(FileMode.OpenOrCreate, rights); // Append, Create and CreateNew allow using CreateFiles rights // These combinations were excluded from WriteModes_ReadRights_ForbiddenCombo_Data [Theory] [InlineData(FileMode.Append)] [InlineData(FileMode.Create)] [InlineData(FileMode.CreateNew)] public void FileInfo_Create_FileSecurity_WriteModes_CreateFilesRights_AllowedCombo(FileMode mode) => FileInfo_Create_FileSecurity_Successful(mode, FileSystemRights.CreateFiles); public static IEnumerable<object[]> AppendMode_UnexpectedReadRights_Data() => from writeRights in s_writableRights from readRights in new[] { FileSystemRights.ExecuteFile, FileSystemRights.ReadAttributes, FileSystemRights.ReadData, FileSystemRights.ReadExtendedAttributes, FileSystemRights.ReadPermissions, FileSystemRights.Read, // Contains ReadAttributes, ReadData, ReadExtendedAttributes, ReadPermissions FileSystemRights.ReadAndExecute, // Contains Read and ExecuteFile } select new object[] { writeRights | readRights }; // Append is allowed if at least one write permission is provided // But append is disallowed if any read rights are provided [Theory] [MemberData(nameof(AppendMode_UnexpectedReadRights_Data))] public void FileInfo_Create_FileSecurity_AppendMode_UnexpectedReadRights(FileSystemRights rights) => FileInfo_Create_FileSecurity_ArgumentException(FileMode.Append, rights); public static IEnumerable<object[]> AppendMode_OnlyWriteRights_Data() => from writeRights in s_writableRights select new object[] { writeRights }; // Append succeeds if only write permissions were provided (no read permissions) [Theory] [MemberData(nameof(AppendMode_OnlyWriteRights_Data))] public void FileInfo_Create_FileSecurity_AppendMode_OnlyWriteRights(FileSystemRights rights) => FileInfo_Create_FileSecurity_Successful(FileMode.Append, rights); public static IEnumerable<object[]> WritableRights_Data() => from rights in s_writableRights select new object[] { rights }; // Cannot truncate unless all write rights are provided [Theory] [MemberData(nameof(WritableRights_Data))] public void FileInfo_Create_FileSecurity_TruncateMode_IncompleteWriteRights(FileSystemRights rights) => FileInfo_Create_FileSecurity_ArgumentException(FileMode.Truncate, rights); [Fact] public void FileInfo_Create_FileSecurity_TruncateMode_AllWriteRights_Throws() { // Truncate, with all write rights, throws with different messages in each framework: // - In .NET Framework, throws "Could not find file" // - In .NET, throws IOException: "The parameter is incorrect" var security = new FileSecurity(); var info = new FileInfo(PathGenerator.GenerateTestFileName()); Assert.Throws<IOException>(() => info.Create(FileMode.Truncate, FileSystemRights.Write | FileSystemRights.ReadData, FileShare.None, DefaultBufferSize, FileOptions.None, security)); } public static IEnumerable<object[]> WriteRights_AllArguments_Data() => from mode in s_writableModes from rights in s_writableRights from share in Enum.GetValues<FileShare>() from options in Enum.GetValues<FileOptions>() where !(rights == FileSystemRights.CreateFiles && (mode == FileMode.Append || mode == FileMode.Create || mode == FileMode.CreateNew)) && !(mode == FileMode.Truncate && rights != FileSystemRights.Write) && (options != FileOptions.Encrypted && // Using FileOptions.Encrypted throws UnauthorizedAccessException when attempting to read the created file !(options == FileOptions.Asynchronous && !PlatformDetection.IsAsyncFileIOSupported))// Async IO not supported on Windows using Mono runtime https://github.com/dotnet/runtime/issues/34582 select new object[] { mode, rights, share, options }; [Theory] [MemberData(nameof(WriteRights_AllArguments_Data))] public void FileInfo_WriteRights_WithSecurity_Null(FileMode mode, FileSystemRights rights, FileShare share, FileOptions options) => Verify_FileSecurity_CreateFile(mode, rights, share, DefaultBufferSize, options, expectedSecurity: null); // Null security [Theory] [MemberData(nameof(WriteRights_AllArguments_Data))] public void FileInfo_WriteRights_WithSecurity_Default(FileMode mode, FileSystemRights rights, FileShare share, FileOptions options) => Verify_FileSecurity_CreateFile(mode, rights, share, DefaultBufferSize, options, new FileSecurity()); // Default security [Theory] [MemberData(nameof(WriteRights_AllArguments_Data))] public void FileInfo_WriteRights_WithSecurity_Custom(FileMode mode, FileSystemRights rights, FileShare share, FileOptions options) => Verify_FileSecurity_CreateFile(mode, rights, share, DefaultBufferSize, options, GetFileSecurity(rights)); // Custom security (AccessRule Allow) public static IEnumerable<object[]> ReadRights_AllArguments_Data() => from mode in new[] { FileMode.Create, FileMode.CreateNew, FileMode.OpenOrCreate } from rights in s_readableRights from share in Enum.GetValues<FileShare>() from options in Enum.GetValues<FileOptions>() where options != FileOptions.Encrypted && // Using FileOptions.Encrypted throws UnauthorizedAccessException when attempting to read the created file !(options == FileOptions.Asynchronous && !PlatformDetection.IsAsyncFileIOSupported) // Async IO not supported on Windows using Mono runtime https://github.com/dotnet/runtime/issues/34582 select new object[] { mode, rights, share, options }; [Theory] [MemberData(nameof(ReadRights_AllArguments_Data))] public void FileInfo_ReadRights_WithSecurity_Null(FileMode mode, FileSystemRights rights, FileShare share, FileOptions options) => // Writable FileModes require at least one write right Verify_FileSecurity_CreateFile(mode, rights | FileSystemRights.WriteData, share, DefaultBufferSize, options, expectedSecurity: null); // Null security [Theory] [MemberData(nameof(ReadRights_AllArguments_Data))] public void FileInfo_ReadRights_WithSecurity_Default(FileMode mode, FileSystemRights rights, FileShare share, FileOptions options) => // Writable FileModes require at least one write right Verify_FileSecurity_CreateFile(mode, rights | FileSystemRights.WriteData, share, DefaultBufferSize, options, new FileSecurity()); // Default security [Theory] [MemberData(nameof(ReadRights_AllArguments_Data))] public void FileInfo_ReadRights_WithSecurity_Custom(FileMode mode, FileSystemRights rights, FileShare share, FileOptions options) => // Writable FileModes require at least one write right Verify_FileSecurity_CreateFile(mode, rights | FileSystemRights.WriteData, share, DefaultBufferSize, options, GetFileSecurity(rights)); // Custom security (AccessRule Allow) [Theory] [MemberData(nameof(RightsToDeny))] public void FileInfo_Create_FileSecurity_DenyAccessRule(FileSystemRights rightsToDeny) { var expectedSecurity = new FileSecurity(); var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); // Add write deny rule var denyAccessRule = new FileSystemAccessRule(identity, rightsToDeny, AccessControlType.Deny); expectedSecurity.AddAccessRule(denyAccessRule); using var tempRootDir = new TempAclDirectory(); string path = tempRootDir.GenerateSubItemPath(); var fileInfo = new FileInfo(path); using FileStream stream = fileInfo.Create( FileMode.CreateNew, FileSystemRights.Write, // Create expects at least one write right FileShare.None, DefaultBufferSize, FileOptions.None, expectedSecurity); Assert.True(fileInfo.Exists); tempRootDir.CreatedSubfiles.Add(fileInfo); var actualInfo = new FileInfo(fileInfo.FullName); FileSecurity actualSecurity = actualInfo.GetAccessControl(AccessControlSections.Access); VerifyAccessSecurity(expectedSecurity, actualSecurity); } #endregion #region DirectorySecurity CreateDirectory [Fact] public void DirectorySecurity_CreateDirectory_NullSecurity() { DirectorySecurity security = null; string path = "whatever"; Assert.Throws<ArgumentNullException>("directorySecurity", () => security.CreateDirectory(path)); Assert.Throws<ArgumentNullException>("directorySecurity", () => FileSystemAclExtensions.CreateDirectory(security, path)); } [Fact] public void DirectorySecurity_CreateDirectory_InvalidPath() { var security = new DirectorySecurity(); Assert.Throws<ArgumentNullException>("path", () => security.CreateDirectory(null)); Assert.Throws<ArgumentException>(() => security.CreateDirectory("")); } [Fact] public void DirectorySecurity_CreateDirectory_DirectoryAlreadyExists() { using var tempRootDir = new TempAclDirectory(); string path = tempRootDir.GenerateSubItemPath(); DirectorySecurity expectedSecurity = GetDirectorySecurity(FileSystemRights.FullControl); DirectoryInfo dirInfo = expectedSecurity.CreateDirectory(path); Assert.True(dirInfo.Exists); tempRootDir.CreatedSubdirectories.Add(dirInfo); var basicSecurity = new DirectorySecurity(); // Already exists, existingDirInfo should have the original security, not the new basic security DirectoryInfo existingDirInfo = basicSecurity.CreateDirectory(path); DirectorySecurity actualSecurity = existingDirInfo.GetAccessControl(AccessControlSections.Access); VerifyAccessSecurity(expectedSecurity, actualSecurity); } #endregion #endregion #region Helper methods public static IEnumerable<object[]> RightsToDeny() => from rights in new[] { FileSystemRights.AppendData, // Same as CreateDirectories FileSystemRights.ChangePermissions, FileSystemRights.Delete, FileSystemRights.DeleteSubdirectoriesAndFiles, FileSystemRights.ExecuteFile, // Same as Traverse FileSystemRights.ReadAttributes, FileSystemRights.ReadExtendedAttributes, FileSystemRights.ReadPermissions, FileSystemRights.TakeOwnership, FileSystemRights.Write, // Contains AppendData, WriteData, WriteAttributes, WriteExtendedAttributes FileSystemRights.WriteAttributes, FileSystemRights.WriteData, // Same as CreateFiles FileSystemRights.WriteExtendedAttributes, // Rights that should not be denied: // - Synchronize: CreateFile always requires Synchronize access // - ReadData: Minimum right required to delete a file or directory // - ListDirectory: Equivalent to ReadData // - Modify: Contains ReadData // - Read: Contains ReadData // - ReadAndExecute: Contains ReadData // - FullControl: Contains ReadData and Synchronize } select new object[] { rights }; public static IEnumerable<object[]> RightsToAllow() => from rights in new[] { FileSystemRights.AppendData, // Same as CreateDirectories FileSystemRights.ChangePermissions, FileSystemRights.Delete, FileSystemRights.DeleteSubdirectoriesAndFiles, FileSystemRights.ExecuteFile, // Same as Traverse FileSystemRights.Modify, // Contains Read, Write and ReadAndExecute FileSystemRights.Read, // Contains ReadData, ReadPermissions, ReadAttributes, ReadExtendedAttributes FileSystemRights.ReadAndExecute, // Contains Read and ExecuteFile FileSystemRights.ReadAttributes, FileSystemRights.ReadData, // Minimum right required to delete a file or directory. Equivalent to ListDirectory FileSystemRights.ReadExtendedAttributes, FileSystemRights.ReadPermissions, FileSystemRights.Synchronize, // CreateFile always requires Synchronize access FileSystemRights.TakeOwnership, FileSystemRights.Write, // Contains AppendData, WriteData, WriteAttributes, WriteExtendedAttributes FileSystemRights.WriteAttributes, FileSystemRights.WriteData, // Same as CreateFiles FileSystemRights.WriteExtendedAttributes, FileSystemRights.FullControl, // Contains Modify, DeleteSubdirectoriesAndFiles, Delete, ChangePermissions, TakeOwnership, Synchronize } select new object[] { rights }; private static readonly FileMode[] s_writableModes = new[] { FileMode.Append, FileMode.Create, FileMode.CreateNew, FileMode.Truncate // Excludes OpenOrCreate because it has a different behavior compared to Create/CreateNew }; private static readonly FileSystemRights[] s_readableRights = new[] { // Excludes combined rights FileSystemRights.ExecuteFile, FileSystemRights.ReadAttributes, FileSystemRights.ReadData, FileSystemRights.ReadExtendedAttributes, FileSystemRights.ReadPermissions }; private static readonly FileSystemRights[] s_writableRights = new[] { // Excludes combined rights FileSystemRights.AppendData, // Same as CreateDirectories FileSystemRights.WriteAttributes, FileSystemRights.WriteData, FileSystemRights.WriteExtendedAttributes }; private void FileInfo_Create_FileSecurity_ArgumentOutOfRangeException(string paramName, FileMode mode = FileMode.CreateNew, FileShare share = FileShare.None, int bufferSize = DefaultBufferSize) { var security = new FileSecurity(); var info = new FileInfo(PathGenerator.GenerateTestFileName()); Assert.Throws<ArgumentOutOfRangeException>(paramName, () => info.Create(mode, FileSystemRights.FullControl, share, bufferSize, FileOptions.None, security)); } private void FileInfo_Create_FileSecurity_ArgumentException(FileMode mode, FileSystemRights rights) { var security = new FileSecurity(); var info = new FileInfo(PathGenerator.GenerateTestFileName()); Assert.Throws<ArgumentException>(() => info.Create(mode, rights, FileShare.None, DefaultBufferSize, FileOptions.None, security)); } private void FileInfo_Create_FileSecurity_Successful(FileMode mode, FileSystemRights rights) { var security = new FileSecurity(); var info = new FileInfo(PathGenerator.GenerateTestFileName()); info.Create(mode, rights, FileShare.None, DefaultBufferSize, FileOptions.DeleteOnClose, security).Dispose(); } private void Verify_FileSecurity_CreateFile(FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity expectedSecurity) { using var tempRootDir = new TempAclDirectory(); string path = tempRootDir.GenerateSubItemPath(); var fileInfo = new FileInfo(path); using (FileStream fs = fileInfo.Create(mode, rights, share, bufferSize, options, expectedSecurity)) { Assert.True(fileInfo.Exists); tempRootDir.CreatedSubfiles.Add(fileInfo); var actualFileInfo = new FileInfo(path); FileSecurity actualSecurity = actualFileInfo.GetAccessControl(); if (expectedSecurity != null) { VerifyAccessSecurity(expectedSecurity, actualSecurity); } else { int count = actualSecurity.GetAccessRules(includeExplicit: true, includeInherited: false, typeof(SecurityIdentifier)).Count; Assert.Equal(0, count); } } } private void Verify_DirectorySecurity_CreateDirectory(DirectorySecurity expectedSecurity) { using var tempRootDir = new TempAclDirectory(); string path = tempRootDir.GenerateSubItemPath(); DirectoryInfo dirInfo = expectedSecurity.CreateDirectory(path); Assert.True(dirInfo.Exists); tempRootDir.CreatedSubdirectories.Add(dirInfo); var actualDirInfo = new DirectoryInfo(path); DirectorySecurity actualSecurity = actualDirInfo.GetAccessControl(AccessControlSections.Access); VerifyAccessSecurity(expectedSecurity, actualSecurity); } private DirectorySecurity GetDirectorySecurity(FileSystemRights rights) { var security = new DirectorySecurity(); var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); var accessRule = new FileSystemAccessRule(identity, rights, AccessControlType.Allow); security.AddAccessRule(accessRule); return security; } private FileSecurity GetFileSecurity(FileSystemRights rights) { var security = new FileSecurity(); var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); var accessRule = new FileSystemAccessRule(identity, rights, AccessControlType.Allow); security.AddAccessRule(accessRule); return security; } private void VerifyAccessSecurity(CommonObjectSecurity expectedSecurity, CommonObjectSecurity actualSecurity) { Assert.Equal(typeof(FileSystemRights), expectedSecurity.AccessRightType); Assert.Equal(typeof(FileSystemRights), actualSecurity.AccessRightType); List<FileSystemAccessRule> expectedAccessRules = expectedSecurity.GetAccessRules(includeExplicit: true, includeInherited: false, typeof(SecurityIdentifier)) .Cast<FileSystemAccessRule>().ToList(); List<FileSystemAccessRule> actualAccessRules = actualSecurity.GetAccessRules(includeExplicit: true, includeInherited: false, typeof(SecurityIdentifier)) .Cast<FileSystemAccessRule>().ToList(); Assert.Equal(expectedAccessRules.Count, actualAccessRules.Count); if (expectedAccessRules.Count > 0) { Assert.All(expectedAccessRules, actualAccessRule => { int count = expectedAccessRules.Count(expectedAccessRule => AreAccessRulesEqual(expectedAccessRule, actualAccessRule)); Assert.True(count > 0); }); } } private bool AreAccessRulesEqual(FileSystemAccessRule expectedRule, FileSystemAccessRule actualRule) { return expectedRule.AccessControlType == actualRule.AccessControlType && expectedRule.FileSystemRights == actualRule.FileSystemRights && expectedRule.InheritanceFlags == actualRule.InheritanceFlags && expectedRule.PropagationFlags == actualRule.PropagationFlags; } #endregion } }
1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/System.IO.FileSystem.AccessControl/tests/TempAclDirectory.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.Security.AccessControl; using System.Security.Principal; namespace System.IO { /// <summary> /// Represents a temporary directory. /// Disposing will recurse all files and directories inside it, ensure the /// appropriate access control is set, then delete all of them. /// </summary> public sealed class TempAclDirectory : TempDirectory { internal readonly List<DirectoryInfo> CreatedSubdirectories = new(); internal readonly List<FileInfo> CreatedSubfiles = new(); protected override void DeleteDirectory() { try { foreach (DirectoryInfo subdir in CreatedSubdirectories) { ResetFullControlToDirectory(subdir); } foreach (FileInfo subfile in CreatedSubfiles) { ResetFullControlToFile(subfile); } var rootDirInfo = new DirectoryInfo(Path); ResetFullControlToDirectory(rootDirInfo); rootDirInfo.Delete(recursive: true); } catch { /* Do not throw because we call this on finalize */ } } private void ResetFullControlToDirectory(DirectoryInfo dirInfo) { try { var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); var accessRule = new FileSystemAccessRule(identity, FileSystemRights.FullControl, AccessControlType.Allow); var security = new DirectorySecurity(dirInfo.FullName, AccessControlSections.Access); security.AddAccessRule(accessRule); dirInfo.SetAccessControl(security); } catch { /* Skip silently if dir does not exist */ } } private void ResetFullControlToFile(FileInfo fileInfo) { try { var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); var accessRule = new FileSystemAccessRule(identity, FileSystemRights.FullControl, AccessControlType.Allow); var security = new FileSecurity(fileInfo.FullName, AccessControlSections.Access); security.AddAccessRule(accessRule); fileInfo.SetAccessControl(security); } catch { /* Skip silently if file does not exist */ } } } }
// 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.Runtime.CompilerServices; using System.Security.AccessControl; using System.Security.Principal; namespace System.IO { /// <summary> /// Represents a temporary directory. /// Disposing will recurse all files and directories inside it, ensure the /// appropriate access control is set, then delete all of them. /// </summary> public sealed class TempAclDirectory : TempDirectory { internal readonly List<DirectoryInfo> CreatedSubdirectories = new(); internal readonly List<FileInfo> CreatedSubfiles = new(); public TempAclDirectory([CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0) : base(IO.Path.Combine(IO.Path.GetTempPath(), PathGenerator.GenerateTestFileName(null, memberName, lineNumber))) { } /// <summary> /// the returned path can be used both as directory and as file name /// </summary> public string GenerateSubItemPath([CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0) => IO.Path.Combine(Path, PathGenerator.GenerateTestFileName(null, memberName, lineNumber)); protected override void DeleteDirectory() { try { foreach (DirectoryInfo subdir in CreatedSubdirectories) { ResetFullControlToDirectory(subdir); } foreach (FileInfo subfile in CreatedSubfiles) { ResetFullControlToFile(subfile); } var rootDirInfo = new DirectoryInfo(Path); ResetFullControlToDirectory(rootDirInfo); rootDirInfo.Delete(recursive: true); } catch { /* Do not throw because we call this on finalize */ } } private void ResetFullControlToDirectory(DirectoryInfo dirInfo) { try { var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); var accessRule = new FileSystemAccessRule(identity, FileSystemRights.FullControl, AccessControlType.Allow); var security = new DirectorySecurity(dirInfo.FullName, AccessControlSections.Access); security.AddAccessRule(accessRule); dirInfo.SetAccessControl(security); } catch { /* Skip silently if dir does not exist */ } } private void ResetFullControlToFile(FileInfo fileInfo) { try { var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); var accessRule = new FileSystemAccessRule(identity, FileSystemRights.FullControl, AccessControlType.Allow); var security = new FileSecurity(fileInfo.FullName, AccessControlSections.Access); security.AddAccessRule(accessRule); fileInfo.SetAccessControl(security); } catch { /* Skip silently if file does not exist */ } } } }
1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/System.Private.Xml/tests/Writers/XmlWriterApi/TCWriterSettingsMisc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using OLEDB.Test.ModuleCore; using System.Text; using Xunit; namespace System.Xml.Tests { public class TCWriterSettingsMisc { [Fact] public void Reset_1() { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.Encoding = Encoding.UTF8; wSettings.OmitXmlDeclaration = true; wSettings.NewLineHandling = NewLineHandling.None; wSettings.NewLineChars = "\n"; wSettings.IndentChars = "\t\t"; wSettings.NewLineOnAttributes = true; wSettings.CloseOutput = true; wSettings.CheckCharacters = false; wSettings.ConformanceLevel = ConformanceLevel.Document; wSettings.WriteEndDocumentOnClose = false; wSettings.Reset(); CError.Equals(wSettings.Encoding, Encoding.UTF8, "Encoding"); CError.Equals(wSettings.OmitXmlDeclaration, false, "OmitXmlDeclaration"); CError.Equals(wSettings.NewLineHandling, NewLineHandling.Replace, "NewLineHandling"); CError.Equals(wSettings.NewLineChars, Environment.NewLine, "NewLineChars"); CError.Equals(wSettings.Indent, false, "Indent"); CError.Equals(wSettings.IndentChars, " ", "IndentChars"); CError.Equals(wSettings.NewLineOnAttributes, false, "NewLineOnAttributes"); CError.Equals(wSettings.CloseOutput, false, "CloseOutput"); CError.Equals(wSettings.CheckCharacters, true, "CheckCharacters"); CError.Equals(wSettings.ConformanceLevel, ConformanceLevel.Document, "ConformanceLevel"); CError.Equals(wSettings.WriteEndDocumentOnClose, true, "WriteEndDocumentOnClose"); } [Fact] public void Clone_1() { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.Encoding = Encoding.UTF8; wSettings.OmitXmlDeclaration = true; wSettings.NewLineHandling = NewLineHandling.Entitize; wSettings.NewLineChars = "\n"; wSettings.IndentChars = " "; wSettings.NewLineOnAttributes = true; wSettings.CloseOutput = true; wSettings.CheckCharacters = false; wSettings.ConformanceLevel = ConformanceLevel.Document; wSettings.WriteEndDocumentOnClose = false; XmlWriterSettings newSettings = wSettings.Clone(); CError.Equals(wSettings.Encoding, newSettings.Encoding, "Encoding"); CError.Equals(wSettings.OmitXmlDeclaration, newSettings.OmitXmlDeclaration, "OmitXmlDeclaration"); CError.Equals(wSettings.NewLineHandling, newSettings.NewLineHandling, "NewLineHandling"); CError.Equals(wSettings.NewLineChars, newSettings.NewLineChars, "NewLineChars"); CError.Equals(wSettings.Indent, newSettings.Indent, "Indent"); CError.Equals(wSettings.IndentChars, newSettings.IndentChars, "IndentChars"); CError.Equals(wSettings.NewLineOnAttributes, newSettings.NewLineOnAttributes, "NewLineOnAttributes"); CError.Equals(wSettings.CloseOutput, newSettings.CloseOutput, "CloseOutput"); CError.Equals(wSettings.CheckCharacters, newSettings.CheckCharacters, "CheckCharacters"); CError.Equals(wSettings.ConformanceLevel, newSettings.ConformanceLevel, "ConformanceLevel"); CError.Equals(wSettings.WriteEndDocumentOnClose, newSettings.WriteEndDocumentOnClose, "WriteEndDocumentOnClose"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using OLEDB.Test.ModuleCore; using System.Text; using Xunit; namespace System.Xml.Tests { public class TCWriterSettingsMisc { [Fact] public void Reset_1() { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.Encoding = Encoding.UTF8; wSettings.OmitXmlDeclaration = true; wSettings.NewLineHandling = NewLineHandling.None; wSettings.NewLineChars = "\n"; wSettings.IndentChars = "\t\t"; wSettings.NewLineOnAttributes = true; wSettings.CloseOutput = true; wSettings.CheckCharacters = false; wSettings.ConformanceLevel = ConformanceLevel.Document; wSettings.WriteEndDocumentOnClose = false; wSettings.Reset(); CError.Equals(wSettings.Encoding, Encoding.UTF8, "Encoding"); CError.Equals(wSettings.OmitXmlDeclaration, false, "OmitXmlDeclaration"); CError.Equals(wSettings.NewLineHandling, NewLineHandling.Replace, "NewLineHandling"); CError.Equals(wSettings.NewLineChars, Environment.NewLine, "NewLineChars"); CError.Equals(wSettings.Indent, false, "Indent"); CError.Equals(wSettings.IndentChars, " ", "IndentChars"); CError.Equals(wSettings.NewLineOnAttributes, false, "NewLineOnAttributes"); CError.Equals(wSettings.CloseOutput, false, "CloseOutput"); CError.Equals(wSettings.CheckCharacters, true, "CheckCharacters"); CError.Equals(wSettings.ConformanceLevel, ConformanceLevel.Document, "ConformanceLevel"); CError.Equals(wSettings.WriteEndDocumentOnClose, true, "WriteEndDocumentOnClose"); } [Fact] public void Clone_1() { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.Encoding = Encoding.UTF8; wSettings.OmitXmlDeclaration = true; wSettings.NewLineHandling = NewLineHandling.Entitize; wSettings.NewLineChars = "\n"; wSettings.IndentChars = " "; wSettings.NewLineOnAttributes = true; wSettings.CloseOutput = true; wSettings.CheckCharacters = false; wSettings.ConformanceLevel = ConformanceLevel.Document; wSettings.WriteEndDocumentOnClose = false; XmlWriterSettings newSettings = wSettings.Clone(); CError.Equals(wSettings.Encoding, newSettings.Encoding, "Encoding"); CError.Equals(wSettings.OmitXmlDeclaration, newSettings.OmitXmlDeclaration, "OmitXmlDeclaration"); CError.Equals(wSettings.NewLineHandling, newSettings.NewLineHandling, "NewLineHandling"); CError.Equals(wSettings.NewLineChars, newSettings.NewLineChars, "NewLineChars"); CError.Equals(wSettings.Indent, newSettings.Indent, "Indent"); CError.Equals(wSettings.IndentChars, newSettings.IndentChars, "IndentChars"); CError.Equals(wSettings.NewLineOnAttributes, newSettings.NewLineOnAttributes, "NewLineOnAttributes"); CError.Equals(wSettings.CloseOutput, newSettings.CloseOutput, "CloseOutput"); CError.Equals(wSettings.CheckCharacters, newSettings.CheckCharacters, "CheckCharacters"); CError.Equals(wSettings.ConformanceLevel, newSettings.ConformanceLevel, "ConformanceLevel"); CError.Equals(wSettings.WriteEndDocumentOnClose, newSettings.WriteEndDocumentOnClose, "WriteEndDocumentOnClose"); } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/JIT/Methodical/Arrays/misc/arrres.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace GCTest { internal class Test { private int _indx; public bool m_die = false; private static Test[] s_arr = new Test[50]; public Test(int indx) { _indx = indx; } public virtual void CheckValid() { if (s_arr[_indx] != this) throw new Exception(); } ~Test() { if (!m_die) { if (s_arr[_indx] != null) { throw new Exception("arr[" + _indx.ToString() + "] != null"); } s_arr[_indx] = this; GC.ReRegisterForFinalize(this); } } private static int Main() { Test1(); Test2(); Test3(); Test4(); Test5(); Test6(); Console.WriteLine("Test passed."); return 100; } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void CollectAndFinalize() { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void Test1() { for (int i = 0; i < 50; i++) s_arr[i] = new Test(i); CollectAndFinalize(); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void Test2() { for (int i = 0; i < 50; i++) { if (s_arr[i] == null) throw new Exception(); s_arr[i].CheckValid(); s_arr[i] = null; } } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void Test3() { CollectAndFinalize(); for (int i = 0; i < 50; i++) { if (s_arr[i] == null) throw new Exception(); s_arr[i].CheckValid(); s_arr[i] = null; } } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void Test4() { CollectAndFinalize(); for (int i = 0; i < 50; i++) { if (s_arr[i] == null) throw new Exception(); s_arr[i].CheckValid(); s_arr[i] = null; } } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void Test5() { CollectAndFinalize(); for (int i = 0; i < 50; i++) { if (s_arr[i] == null) throw new Exception(); s_arr[i].CheckValid(); s_arr[i] = null; } } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void Test6() { CollectAndFinalize(); for (int i = 0; i < 50; i++) { if (s_arr[i] == null) throw new Exception(); s_arr[i].CheckValid(); s_arr[i].m_die = true; s_arr[i] = null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace GCTest { internal class Test { private int _indx; public bool m_die = false; private static Test[] s_arr = new Test[50]; public Test(int indx) { _indx = indx; } public virtual void CheckValid() { if (s_arr[_indx] != this) throw new Exception(); } ~Test() { if (!m_die) { if (s_arr[_indx] != null) { throw new Exception("arr[" + _indx.ToString() + "] != null"); } s_arr[_indx] = this; GC.ReRegisterForFinalize(this); } } private static int Main() { Test1(); Test2(); Test3(); Test4(); Test5(); Test6(); Console.WriteLine("Test passed."); return 100; } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void CollectAndFinalize() { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void Test1() { for (int i = 0; i < 50; i++) s_arr[i] = new Test(i); CollectAndFinalize(); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void Test2() { for (int i = 0; i < 50; i++) { if (s_arr[i] == null) throw new Exception(); s_arr[i].CheckValid(); s_arr[i] = null; } } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void Test3() { CollectAndFinalize(); for (int i = 0; i < 50; i++) { if (s_arr[i] == null) throw new Exception(); s_arr[i].CheckValid(); s_arr[i] = null; } } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void Test4() { CollectAndFinalize(); for (int i = 0; i < 50; i++) { if (s_arr[i] == null) throw new Exception(); s_arr[i].CheckValid(); s_arr[i] = null; } } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void Test5() { CollectAndFinalize(); for (int i = 0; i < 50; i++) { if (s_arr[i] == null) throw new Exception(); s_arr[i].CheckValid(); s_arr[i] = null; } } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void Test6() { CollectAndFinalize(); for (int i = 0; i < 50; i++) { if (s_arr[i] == null) throw new Exception(); s_arr[i].CheckValid(); s_arr[i].m_die = true; s_arr[i] = null; } } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/Common/src/Interop/Windows/Advapi32/Interop.GetOldestEventLogRecord.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Advapi32 { [GeneratedDllImport(Libraries.Advapi32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static partial bool GetOldestEventLogRecord(SafeEventLogReadHandle hEventLog, out int OldestRecord); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Advapi32 { [GeneratedDllImport(Libraries.Advapi32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static partial bool GetOldestEventLogRecord(SafeEventLogReadHandle hEventLog, out int OldestRecord); } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.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.Net; using System.Net.Http; using System.Net.Security; using System.IO; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using JSObject = System.Runtime.InteropServices.JavaScript.JSObject; using JSException = System.Runtime.InteropServices.JavaScript.JSException; using HostObject = System.Runtime.InteropServices.JavaScript.HostObject; using Uint8Array = System.Runtime.InteropServices.JavaScript.Uint8Array; using Function = System.Runtime.InteropServices.JavaScript.Function; namespace System.Net.Http { // **Note** on `Task.ConfigureAwait(continueOnCapturedContext: true)` for the WebAssembly Browser. // The current implementation of WebAssembly for the Browser does not have a SynchronizationContext nor a Scheduler // thus forcing the callbacks to run on the main browser thread. When threading is eventually implemented using // emscripten's threading model of remote worker threads, via SharedArrayBuffer, any API calls will have to be // remoted back to the main thread. Most APIs only work on the main browser thread. // During discussions the concensus has been that it will not matter right now which value is used for ConfigureAwait // we should put this in place now. internal sealed class BrowserHttpHandler : HttpMessageHandler { // This partial implementation contains members common to Browser WebAssembly running on .NET Core. private static readonly JSObject? s_fetch = (JSObject)System.Runtime.InteropServices.JavaScript.Runtime.GetGlobalObject("fetch"); private static readonly JSObject? s_window = (JSObject)System.Runtime.InteropServices.JavaScript.Runtime.GetGlobalObject("window"); private static readonly HttpRequestOptionsKey<bool> EnableStreamingResponse = new HttpRequestOptionsKey<bool>("WebAssemblyEnableStreamingResponse"); private static readonly HttpRequestOptionsKey<IDictionary<string, object>> FetchOptions = new HttpRequestOptionsKey<IDictionary<string, object>>("WebAssemblyFetchOptions"); private bool _allowAutoRedirect = HttpHandlerDefaults.DefaultAutomaticRedirection; // flag to determine if the _allowAutoRedirect was explicitly set or not. private bool _isAllowAutoRedirectTouched; /// <summary> /// Gets whether the current Browser supports streaming responses /// </summary> private static bool StreamingSupported { get; } = GetIsStreamingSupported(); private static bool GetIsStreamingSupported() { using (var streamingSupported = new Function("return typeof Response !== 'undefined' && 'body' in Response.prototype && typeof ReadableStream === 'function'")) return (bool)streamingSupported.Call(); } public bool UseCookies { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public CookieContainer CookieContainer { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public DecompressionMethods AutomaticDecompression { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public bool UseProxy { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public IWebProxy? Proxy { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public ICredentials? DefaultProxyCredentials { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public bool PreAuthenticate { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public ICredentials? Credentials { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public bool AllowAutoRedirect { get => _allowAutoRedirect; set { _allowAutoRedirect = value; _isAllowAutoRedirectTouched = true; } } public int MaxAutomaticRedirections { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public int MaxConnectionsPerServer { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public int MaxResponseHeadersLength { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public SslClientAuthenticationOptions SslOptions { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public const bool SupportsAutomaticDecompression = false; public const bool SupportsProxy = false; public const bool SupportsRedirectConfiguration = true; private Dictionary<string, object?>? _properties; public IDictionary<string, object?> Properties => _properties ??= new Dictionary<string, object?>(); protected internal override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) { throw new PlatformNotSupportedException(); } protected internal override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request!!, CancellationToken cancellationToken) { CancellationTokenRegistration? abortRegistration = null; try { using var requestObject = new JSObject(); if (request.Options.TryGetValue(FetchOptions, out IDictionary<string, object>? fetchOptions)) { foreach (KeyValuePair<string, object> item in fetchOptions) { requestObject.SetObjectProperty(item.Key, item.Value); } } requestObject.SetObjectProperty("method", request.Method.Method); // Only set if property was specifically modified and is not default value if (_isAllowAutoRedirectTouched) { // Allowing or Disallowing redirects. // Here we will set redirect to `manual` instead of error if AllowAutoRedirect is // false so there is no exception thrown // // https://developer.mozilla.org/en-US/docs/Web/API/Response/type // // other issues from whatwg/fetch: // // https://github.com/whatwg/fetch/issues/763 // https://github.com/whatwg/fetch/issues/601 requestObject.SetObjectProperty("redirect", AllowAutoRedirect ? "follow" : "manual"); } // We need to check for body content if (request.Content != null) { if (request.Content is StringContent) { requestObject.SetObjectProperty("body", await request.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: true)); } else { using (Uint8Array uint8Buffer = Uint8Array.From(await request.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: true))) { requestObject.SetObjectProperty("body", uint8Buffer); } } } // Process headers // Cors has its own restrictions on headers. // https://developer.mozilla.org/en-US/docs/Web/API/Headers using (HostObject jsHeaders = new HostObject("Headers")) { foreach (KeyValuePair<string, IEnumerable<string>> header in request.Headers) { foreach (string value in header.Value) { jsHeaders.Invoke("append", header.Key, value); } } if (request.Content != null) { foreach (KeyValuePair<string, IEnumerable<string>> header in request.Content.Headers) { foreach (string value in header.Value) { jsHeaders.Invoke("append", header.Key, value); } } } requestObject.SetObjectProperty("headers", jsHeaders); } JSObject abortController = new HostObject("AbortController"); using JSObject signal = (JSObject)abortController.GetObjectProperty("signal"); requestObject.SetObjectProperty("signal", signal); abortRegistration = cancellationToken.Register(() => { if (!abortController.IsDisposed) { abortController.Invoke("abort"); abortController?.Dispose(); } }); using var args = new System.Runtime.InteropServices.JavaScript.Array(); if (request.RequestUri != null) { args.Push(request.RequestUri.ToString()); args.Push(requestObject); } var responseTask = s_fetch?.Invoke("apply", s_window, args) as Task<object>; if (responseTask == null) throw new Exception(SR.net_http_marshalling_response_promise_from_fetch); cancellationToken.ThrowIfCancellationRequested(); var fetchResponseJs = (JSObject)await responseTask.ConfigureAwait(continueOnCapturedContext: true); var fetchResponse = new WasmFetchResponse(fetchResponseJs, abortController, abortRegistration.Value); abortRegistration = null; var responseMessage = new HttpResponseMessage((HttpStatusCode)fetchResponse.Status); responseMessage.RequestMessage = request; // Here we will set the ReasonPhrase so that it can be evaluated later. // We do not have a status code but this will signal some type of what happened // after interrogating the status code for success or not i.e. IsSuccessStatusCode // // https://developer.mozilla.org/en-US/docs/Web/API/Response/type // opaqueredirect: The fetch request was made with redirect: "manual". // The Response's status is 0, headers are empty, body is null and trailer is empty. if (fetchResponse.ResponseType == "opaqueredirect") { responseMessage.SetReasonPhraseWithoutValidation(fetchResponse.ResponseType); } bool streamingEnabled = false; if (StreamingSupported) { request.Options.TryGetValue(EnableStreamingResponse, out streamingEnabled); } responseMessage.Content = streamingEnabled ? new StreamContent(new WasmHttpReadStream(fetchResponse)) : new BrowserHttpContent(fetchResponse); // Fill the response headers // CORS will only allow access to certain headers. // If a request is made for a resource on another origin which returns the CORs headers, then the type is cors. // cors and basic responses are almost identical except that a cors response restricts the headers you can view to // `Cache-Control`, `Content-Language`, `Content-Type`, `Expires`, `Last-Modified`, and `Pragma`. // View more information https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types // // Note: Some of the headers may not even be valid header types in .NET thus we use TryAddWithoutValidation using (JSObject respHeaders = fetchResponse.Headers) { if (respHeaders != null) { using (var entriesIterator = (JSObject)respHeaders.Invoke("entries")) { JSObject? nextResult = null; try { nextResult = (JSObject)entriesIterator.Invoke("next"); while (!(bool)nextResult.GetObjectProperty("done")) { using (var resultValue = (System.Runtime.InteropServices.JavaScript.Array)nextResult.GetObjectProperty("value")) { var name = (string)resultValue[0]; var value = (string)resultValue[1]; if (!responseMessage.Headers.TryAddWithoutValidation(name, value)) responseMessage.Content.Headers.TryAddWithoutValidation(name, value); } nextResult?.Dispose(); nextResult = (JSObject)entriesIterator.Invoke("next"); } } finally { nextResult?.Dispose(); } } } } return responseMessage; } catch (OperationCanceledException oce) when (cancellationToken.IsCancellationRequested) { throw CancellationHelper.CreateOperationCanceledException(oce, cancellationToken); } catch (JSException jse) { throw TranslateJSException(jse, cancellationToken); } finally { abortRegistration?.Dispose(); } } private static Exception TranslateJSException(JSException jse, CancellationToken cancellationToken) { if (jse.Message.StartsWith("AbortError", StringComparison.Ordinal)) { return CancellationHelper.CreateOperationCanceledException(jse, CancellationToken.None); } if (cancellationToken.IsCancellationRequested) { return CancellationHelper.CreateOperationCanceledException(jse, cancellationToken); } return new HttpRequestException(jse.Message, jse); } private sealed class WasmFetchResponse : IDisposable { private readonly JSObject _fetchResponse; private readonly JSObject _abortController; private readonly CancellationTokenRegistration _abortRegistration; private bool _isDisposed; public WasmFetchResponse(JSObject fetchResponse!!, JSObject abortController!!, CancellationTokenRegistration abortRegistration) { _fetchResponse = fetchResponse; _abortController = abortController; _abortRegistration = abortRegistration; } public bool IsOK => (bool)_fetchResponse.GetObjectProperty("ok"); public bool IsRedirected => (bool)_fetchResponse.GetObjectProperty("redirected"); public int Status => (int)_fetchResponse.GetObjectProperty("status"); public string StatusText => (string)_fetchResponse.GetObjectProperty("statusText"); public string ResponseType => (string)_fetchResponse.GetObjectProperty("type"); public string Url => (string)_fetchResponse.GetObjectProperty("url"); public bool IsBodyUsed => (bool)_fetchResponse.GetObjectProperty("bodyUsed"); public JSObject Headers => (JSObject)_fetchResponse.GetObjectProperty("headers"); public JSObject Body => (JSObject)_fetchResponse.GetObjectProperty("body"); public Task<object> ArrayBuffer() => (Task<object>)_fetchResponse.Invoke("arrayBuffer"); public Task<object> Text() => (Task<object>)_fetchResponse.Invoke("text"); public Task<object> JSON() => (Task<object>)_fetchResponse.Invoke("json"); public void Dispose() { if (_isDisposed) return; _isDisposed = true; _abortRegistration.Dispose(); _fetchResponse?.Dispose(); if (_abortController != null && !_abortController.IsDisposed) { _abortController.Invoke("abort"); } _abortController?.Dispose(); } } private sealed class BrowserHttpContent : HttpContent { private byte[]? _data; private readonly WasmFetchResponse _status; public BrowserHttpContent(WasmFetchResponse status!!) { _status = status; } private async Task<byte[]> GetResponseData(CancellationToken cancellationToken) { if (_data != null) { return _data; } try { using (System.Runtime.InteropServices.JavaScript.ArrayBuffer dataBuffer = (System.Runtime.InteropServices.JavaScript.ArrayBuffer)await _status.ArrayBuffer().ConfigureAwait(continueOnCapturedContext: true)) { using (Uint8Array dataBinView = new Uint8Array(dataBuffer)) { _data = dataBinView.ToArray(); _status.Dispose(); } } } catch (JSException jse) { throw TranslateJSException(jse, cancellationToken); } return _data; } protected override async Task<Stream> CreateContentReadStreamAsync() { byte[] data = await GetResponseData(CancellationToken.None).ConfigureAwait(continueOnCapturedContext: true); return new MemoryStream(data, writable: false); } protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) => SerializeToStreamAsync(stream, context, CancellationToken.None); protected override async Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken cancellationToken) { byte[] data = await GetResponseData(cancellationToken).ConfigureAwait(continueOnCapturedContext: true); await stream.WriteAsync(data, cancellationToken).ConfigureAwait(continueOnCapturedContext: true); } protected internal override bool TryComputeLength(out long length) { if (_data != null) { length = _data.Length; return true; } length = 0; return false; } protected override void Dispose(bool disposing) { _status?.Dispose(); base.Dispose(disposing); } } private sealed class WasmHttpReadStream : Stream { private WasmFetchResponse? _fetchResponse; private JSObject? _reader; private byte[]? _bufferedBytes; private int _position; public WasmHttpReadStream(WasmFetchResponse fetchResponse) { _fetchResponse = fetchResponse; } public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => false; public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { ValidateBufferArguments(buffer, offset, count); return ReadAsync(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask(); } public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken) { CancellationHelper.ThrowIfCancellationRequested(cancellationToken); if (_reader == null) { // If we've read everything, then _reader and _status will be null if (_fetchResponse == null) { return 0; } try { using (JSObject body = _fetchResponse.Body) { _reader = (JSObject)body.Invoke("getReader"); } } catch (OperationCanceledException oce) when (cancellationToken.IsCancellationRequested) { throw CancellationHelper.CreateOperationCanceledException(oce, cancellationToken); } catch (JSException jse) { throw TranslateJSException(jse, cancellationToken); } } using var abortRegistration = cancellationToken.Register(() => { _reader.Invoke("cancel"); }); if (_bufferedBytes != null && _position < _bufferedBytes.Length) { return ReadBuffered(); } try { var t = (Task<object>)_reader.Invoke("read"); using (var read = (JSObject)await t.ConfigureAwait(continueOnCapturedContext: true)) { if (cancellationToken.IsCancellationRequested) { _reader.Invoke("cancel"); throw CancellationHelper.CreateOperationCanceledException(null, cancellationToken); } if ((bool)read.GetObjectProperty("done")) { _reader.Dispose(); _reader = null; _fetchResponse?.Dispose(); _fetchResponse = null; return 0; } _position = 0; // value for fetch streams is a Uint8Array using (Uint8Array binValue = (Uint8Array)read.GetObjectProperty("value")) _bufferedBytes = binValue.ToArray(); } } catch (OperationCanceledException oce) when (cancellationToken.IsCancellationRequested) { throw CancellationHelper.CreateOperationCanceledException(oce, cancellationToken); } catch (JSException jse) { throw TranslateJSException(jse, cancellationToken); } return ReadBuffered(); int ReadBuffered() { int n = Math.Min(_bufferedBytes.Length - _position, buffer.Length); if (n <= 0) { return 0; } _bufferedBytes.AsSpan(_position, n).CopyTo(buffer.Span); _position += n; return n; } } protected override void Dispose(bool disposing) { _reader?.Dispose(); _fetchResponse?.Dispose(); } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(SR.net_http_synchronous_reads_not_supported); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } } } }
// 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.Net; using System.Net.Http; using System.Net.Security; using System.IO; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using JSObject = System.Runtime.InteropServices.JavaScript.JSObject; using JSException = System.Runtime.InteropServices.JavaScript.JSException; using HostObject = System.Runtime.InteropServices.JavaScript.HostObject; using Uint8Array = System.Runtime.InteropServices.JavaScript.Uint8Array; using Function = System.Runtime.InteropServices.JavaScript.Function; namespace System.Net.Http { // **Note** on `Task.ConfigureAwait(continueOnCapturedContext: true)` for the WebAssembly Browser. // The current implementation of WebAssembly for the Browser does not have a SynchronizationContext nor a Scheduler // thus forcing the callbacks to run on the main browser thread. When threading is eventually implemented using // emscripten's threading model of remote worker threads, via SharedArrayBuffer, any API calls will have to be // remoted back to the main thread. Most APIs only work on the main browser thread. // During discussions the concensus has been that it will not matter right now which value is used for ConfigureAwait // we should put this in place now. internal sealed class BrowserHttpHandler : HttpMessageHandler { // This partial implementation contains members common to Browser WebAssembly running on .NET Core. private static readonly JSObject? s_fetch = (JSObject)System.Runtime.InteropServices.JavaScript.Runtime.GetGlobalObject("fetch"); private static readonly JSObject? s_window = (JSObject)System.Runtime.InteropServices.JavaScript.Runtime.GetGlobalObject("window"); private static readonly HttpRequestOptionsKey<bool> EnableStreamingResponse = new HttpRequestOptionsKey<bool>("WebAssemblyEnableStreamingResponse"); private static readonly HttpRequestOptionsKey<IDictionary<string, object>> FetchOptions = new HttpRequestOptionsKey<IDictionary<string, object>>("WebAssemblyFetchOptions"); private bool _allowAutoRedirect = HttpHandlerDefaults.DefaultAutomaticRedirection; // flag to determine if the _allowAutoRedirect was explicitly set or not. private bool _isAllowAutoRedirectTouched; /// <summary> /// Gets whether the current Browser supports streaming responses /// </summary> private static bool StreamingSupported { get; } = GetIsStreamingSupported(); private static bool GetIsStreamingSupported() { using (var streamingSupported = new Function("return typeof Response !== 'undefined' && 'body' in Response.prototype && typeof ReadableStream === 'function'")) return (bool)streamingSupported.Call(); } public bool UseCookies { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public CookieContainer CookieContainer { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public DecompressionMethods AutomaticDecompression { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public bool UseProxy { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public IWebProxy? Proxy { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public ICredentials? DefaultProxyCredentials { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public bool PreAuthenticate { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public ICredentials? Credentials { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public bool AllowAutoRedirect { get => _allowAutoRedirect; set { _allowAutoRedirect = value; _isAllowAutoRedirectTouched = true; } } public int MaxAutomaticRedirections { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public int MaxConnectionsPerServer { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public int MaxResponseHeadersLength { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public SslClientAuthenticationOptions SslOptions { get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } public const bool SupportsAutomaticDecompression = false; public const bool SupportsProxy = false; public const bool SupportsRedirectConfiguration = true; private Dictionary<string, object?>? _properties; public IDictionary<string, object?> Properties => _properties ??= new Dictionary<string, object?>(); protected internal override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) { throw new PlatformNotSupportedException(); } protected internal override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request!!, CancellationToken cancellationToken) { CancellationTokenRegistration? abortRegistration = null; try { using var requestObject = new JSObject(); if (request.Options.TryGetValue(FetchOptions, out IDictionary<string, object>? fetchOptions)) { foreach (KeyValuePair<string, object> item in fetchOptions) { requestObject.SetObjectProperty(item.Key, item.Value); } } requestObject.SetObjectProperty("method", request.Method.Method); // Only set if property was specifically modified and is not default value if (_isAllowAutoRedirectTouched) { // Allowing or Disallowing redirects. // Here we will set redirect to `manual` instead of error if AllowAutoRedirect is // false so there is no exception thrown // // https://developer.mozilla.org/en-US/docs/Web/API/Response/type // // other issues from whatwg/fetch: // // https://github.com/whatwg/fetch/issues/763 // https://github.com/whatwg/fetch/issues/601 requestObject.SetObjectProperty("redirect", AllowAutoRedirect ? "follow" : "manual"); } // We need to check for body content if (request.Content != null) { if (request.Content is StringContent) { requestObject.SetObjectProperty("body", await request.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: true)); } else { using (Uint8Array uint8Buffer = Uint8Array.From(await request.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: true))) { requestObject.SetObjectProperty("body", uint8Buffer); } } } // Process headers // Cors has its own restrictions on headers. // https://developer.mozilla.org/en-US/docs/Web/API/Headers using (HostObject jsHeaders = new HostObject("Headers")) { foreach (KeyValuePair<string, IEnumerable<string>> header in request.Headers) { foreach (string value in header.Value) { jsHeaders.Invoke("append", header.Key, value); } } if (request.Content != null) { foreach (KeyValuePair<string, IEnumerable<string>> header in request.Content.Headers) { foreach (string value in header.Value) { jsHeaders.Invoke("append", header.Key, value); } } } requestObject.SetObjectProperty("headers", jsHeaders); } JSObject abortController = new HostObject("AbortController"); using JSObject signal = (JSObject)abortController.GetObjectProperty("signal"); requestObject.SetObjectProperty("signal", signal); abortRegistration = cancellationToken.Register(() => { if (!abortController.IsDisposed) { abortController.Invoke("abort"); abortController?.Dispose(); } }); using var args = new System.Runtime.InteropServices.JavaScript.Array(); if (request.RequestUri != null) { args.Push(request.RequestUri.ToString()); args.Push(requestObject); } var responseTask = s_fetch?.Invoke("apply", s_window, args) as Task<object>; if (responseTask == null) throw new Exception(SR.net_http_marshalling_response_promise_from_fetch); cancellationToken.ThrowIfCancellationRequested(); var fetchResponseJs = (JSObject)await responseTask.ConfigureAwait(continueOnCapturedContext: true); var fetchResponse = new WasmFetchResponse(fetchResponseJs, abortController, abortRegistration.Value); abortRegistration = null; var responseMessage = new HttpResponseMessage((HttpStatusCode)fetchResponse.Status); responseMessage.RequestMessage = request; // Here we will set the ReasonPhrase so that it can be evaluated later. // We do not have a status code but this will signal some type of what happened // after interrogating the status code for success or not i.e. IsSuccessStatusCode // // https://developer.mozilla.org/en-US/docs/Web/API/Response/type // opaqueredirect: The fetch request was made with redirect: "manual". // The Response's status is 0, headers are empty, body is null and trailer is empty. if (fetchResponse.ResponseType == "opaqueredirect") { responseMessage.SetReasonPhraseWithoutValidation(fetchResponse.ResponseType); } bool streamingEnabled = false; if (StreamingSupported) { request.Options.TryGetValue(EnableStreamingResponse, out streamingEnabled); } responseMessage.Content = streamingEnabled ? new StreamContent(new WasmHttpReadStream(fetchResponse)) : new BrowserHttpContent(fetchResponse); // Fill the response headers // CORS will only allow access to certain headers. // If a request is made for a resource on another origin which returns the CORs headers, then the type is cors. // cors and basic responses are almost identical except that a cors response restricts the headers you can view to // `Cache-Control`, `Content-Language`, `Content-Type`, `Expires`, `Last-Modified`, and `Pragma`. // View more information https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types // // Note: Some of the headers may not even be valid header types in .NET thus we use TryAddWithoutValidation using (JSObject respHeaders = fetchResponse.Headers) { if (respHeaders != null) { using (var entriesIterator = (JSObject)respHeaders.Invoke("entries")) { JSObject? nextResult = null; try { nextResult = (JSObject)entriesIterator.Invoke("next"); while (!(bool)nextResult.GetObjectProperty("done")) { using (var resultValue = (System.Runtime.InteropServices.JavaScript.Array)nextResult.GetObjectProperty("value")) { var name = (string)resultValue[0]; var value = (string)resultValue[1]; if (!responseMessage.Headers.TryAddWithoutValidation(name, value)) responseMessage.Content.Headers.TryAddWithoutValidation(name, value); } nextResult?.Dispose(); nextResult = (JSObject)entriesIterator.Invoke("next"); } } finally { nextResult?.Dispose(); } } } } return responseMessage; } catch (OperationCanceledException oce) when (cancellationToken.IsCancellationRequested) { throw CancellationHelper.CreateOperationCanceledException(oce, cancellationToken); } catch (JSException jse) { throw TranslateJSException(jse, cancellationToken); } finally { abortRegistration?.Dispose(); } } private static Exception TranslateJSException(JSException jse, CancellationToken cancellationToken) { if (jse.Message.StartsWith("AbortError", StringComparison.Ordinal)) { return CancellationHelper.CreateOperationCanceledException(jse, CancellationToken.None); } if (cancellationToken.IsCancellationRequested) { return CancellationHelper.CreateOperationCanceledException(jse, cancellationToken); } return new HttpRequestException(jse.Message, jse); } private sealed class WasmFetchResponse : IDisposable { private readonly JSObject _fetchResponse; private readonly JSObject _abortController; private readonly CancellationTokenRegistration _abortRegistration; private bool _isDisposed; public WasmFetchResponse(JSObject fetchResponse!!, JSObject abortController!!, CancellationTokenRegistration abortRegistration) { _fetchResponse = fetchResponse; _abortController = abortController; _abortRegistration = abortRegistration; } public bool IsOK => (bool)_fetchResponse.GetObjectProperty("ok"); public bool IsRedirected => (bool)_fetchResponse.GetObjectProperty("redirected"); public int Status => (int)_fetchResponse.GetObjectProperty("status"); public string StatusText => (string)_fetchResponse.GetObjectProperty("statusText"); public string ResponseType => (string)_fetchResponse.GetObjectProperty("type"); public string Url => (string)_fetchResponse.GetObjectProperty("url"); public bool IsBodyUsed => (bool)_fetchResponse.GetObjectProperty("bodyUsed"); public JSObject Headers => (JSObject)_fetchResponse.GetObjectProperty("headers"); public JSObject Body => (JSObject)_fetchResponse.GetObjectProperty("body"); public Task<object> ArrayBuffer() => (Task<object>)_fetchResponse.Invoke("arrayBuffer"); public Task<object> Text() => (Task<object>)_fetchResponse.Invoke("text"); public Task<object> JSON() => (Task<object>)_fetchResponse.Invoke("json"); public void Dispose() { if (_isDisposed) return; _isDisposed = true; _abortRegistration.Dispose(); _fetchResponse?.Dispose(); if (_abortController != null && !_abortController.IsDisposed) { _abortController.Invoke("abort"); } _abortController?.Dispose(); } } private sealed class BrowserHttpContent : HttpContent { private byte[]? _data; private readonly WasmFetchResponse _status; public BrowserHttpContent(WasmFetchResponse status!!) { _status = status; } private async Task<byte[]> GetResponseData(CancellationToken cancellationToken) { if (_data != null) { return _data; } try { using (System.Runtime.InteropServices.JavaScript.ArrayBuffer dataBuffer = (System.Runtime.InteropServices.JavaScript.ArrayBuffer)await _status.ArrayBuffer().ConfigureAwait(continueOnCapturedContext: true)) { using (Uint8Array dataBinView = new Uint8Array(dataBuffer)) { _data = dataBinView.ToArray(); _status.Dispose(); } } } catch (JSException jse) { throw TranslateJSException(jse, cancellationToken); } return _data; } protected override async Task<Stream> CreateContentReadStreamAsync() { byte[] data = await GetResponseData(CancellationToken.None).ConfigureAwait(continueOnCapturedContext: true); return new MemoryStream(data, writable: false); } protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) => SerializeToStreamAsync(stream, context, CancellationToken.None); protected override async Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken cancellationToken) { byte[] data = await GetResponseData(cancellationToken).ConfigureAwait(continueOnCapturedContext: true); await stream.WriteAsync(data, cancellationToken).ConfigureAwait(continueOnCapturedContext: true); } protected internal override bool TryComputeLength(out long length) { if (_data != null) { length = _data.Length; return true; } length = 0; return false; } protected override void Dispose(bool disposing) { _status?.Dispose(); base.Dispose(disposing); } } private sealed class WasmHttpReadStream : Stream { private WasmFetchResponse? _fetchResponse; private JSObject? _reader; private byte[]? _bufferedBytes; private int _position; public WasmHttpReadStream(WasmFetchResponse fetchResponse) { _fetchResponse = fetchResponse; } public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => false; public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { ValidateBufferArguments(buffer, offset, count); return ReadAsync(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask(); } public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken) { CancellationHelper.ThrowIfCancellationRequested(cancellationToken); if (_reader == null) { // If we've read everything, then _reader and _status will be null if (_fetchResponse == null) { return 0; } try { using (JSObject body = _fetchResponse.Body) { _reader = (JSObject)body.Invoke("getReader"); } } catch (OperationCanceledException oce) when (cancellationToken.IsCancellationRequested) { throw CancellationHelper.CreateOperationCanceledException(oce, cancellationToken); } catch (JSException jse) { throw TranslateJSException(jse, cancellationToken); } } using var abortRegistration = cancellationToken.Register(() => { _reader.Invoke("cancel"); }); if (_bufferedBytes != null && _position < _bufferedBytes.Length) { return ReadBuffered(); } try { var t = (Task<object>)_reader.Invoke("read"); using (var read = (JSObject)await t.ConfigureAwait(continueOnCapturedContext: true)) { if (cancellationToken.IsCancellationRequested) { _reader.Invoke("cancel"); throw CancellationHelper.CreateOperationCanceledException(null, cancellationToken); } if ((bool)read.GetObjectProperty("done")) { _reader.Dispose(); _reader = null; _fetchResponse?.Dispose(); _fetchResponse = null; return 0; } _position = 0; // value for fetch streams is a Uint8Array using (Uint8Array binValue = (Uint8Array)read.GetObjectProperty("value")) _bufferedBytes = binValue.ToArray(); } } catch (OperationCanceledException oce) when (cancellationToken.IsCancellationRequested) { throw CancellationHelper.CreateOperationCanceledException(oce, cancellationToken); } catch (JSException jse) { throw TranslateJSException(jse, cancellationToken); } return ReadBuffered(); int ReadBuffered() { int n = Math.Min(_bufferedBytes.Length - _position, buffer.Length); if (n <= 0) { return 0; } _bufferedBytes.AsSpan(_position, n).CopyTo(buffer.Span); _position += n; return n; } } protected override void Dispose(bool disposing) { _reader?.Dispose(); _fetchResponse?.Dispose(); } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(SR.net_http_synchronous_reads_not_supported); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/Microsoft.Extensions.Primitives/src/CompositeChangeToken.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; namespace Microsoft.Extensions.Primitives { /// <summary> /// An <see cref="IChangeToken"/> which represents one or more <see cref="IChangeToken"/> instances. /// </summary> public class CompositeChangeToken : IChangeToken { private static readonly Action<object?> _onChangeDelegate = OnChange; private readonly object _callbackLock = new(); private CancellationTokenSource? _cancellationTokenSource; private List<IDisposable>? _disposables; [MemberNotNullWhen(true, nameof(_cancellationTokenSource))] [MemberNotNullWhen(true, nameof(_disposables))] private bool RegisteredCallbackProxy { get; set; } /// <summary> /// Creates a new instance of <see cref="CompositeChangeToken"/>. /// </summary> /// <param name="changeTokens">The list of <see cref="IChangeToken"/> to compose.</param> public CompositeChangeToken(IReadOnlyList<IChangeToken> changeTokens!!) { ChangeTokens = changeTokens; for (int i = 0; i < ChangeTokens.Count; i++) { if (ChangeTokens[i].ActiveChangeCallbacks) { ActiveChangeCallbacks = true; break; } } } /// <summary> /// Returns the list of <see cref="IChangeToken"/> which compose the current <see cref="CompositeChangeToken"/>. /// </summary> public IReadOnlyList<IChangeToken> ChangeTokens { get; } /// <inheritdoc /> public IDisposable RegisterChangeCallback(Action<object?> callback, object? state) { EnsureCallbacksInitialized(); return _cancellationTokenSource.Token.Register(callback, state); } /// <inheritdoc /> public bool HasChanged { get { if (_cancellationTokenSource != null && _cancellationTokenSource.Token.IsCancellationRequested) { return true; } for (int i = 0; i < ChangeTokens.Count; i++) { if (ChangeTokens[i].HasChanged) { OnChange(this); return true; } } return false; } } /// <inheritdoc /> public bool ActiveChangeCallbacks { get; } [MemberNotNull(nameof(_cancellationTokenSource))] [MemberNotNull(nameof(_disposables))] private void EnsureCallbacksInitialized() { if (RegisteredCallbackProxy) { return; } lock (_callbackLock) { if (RegisteredCallbackProxy) { return; } _cancellationTokenSource = new CancellationTokenSource(); _disposables = new List<IDisposable>(); for (int i = 0; i < ChangeTokens.Count; i++) { if (ChangeTokens[i].ActiveChangeCallbacks) { IDisposable disposable = ChangeTokens[i].RegisterChangeCallback(_onChangeDelegate, this); _disposables.Add(disposable); } } RegisteredCallbackProxy = true; } } private static void OnChange(object? state) { Debug.Assert(state != null); var compositeChangeTokenState = (CompositeChangeToken)state; if (compositeChangeTokenState._cancellationTokenSource == null) { return; } lock (compositeChangeTokenState._callbackLock) { try { compositeChangeTokenState._cancellationTokenSource.Cancel(); } catch { } } List<IDisposable>? disposables = compositeChangeTokenState._disposables; Debug.Assert(disposables != null); for (int i = 0; i < disposables.Count; i++) { disposables[i].Dispose(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; namespace Microsoft.Extensions.Primitives { /// <summary> /// An <see cref="IChangeToken"/> which represents one or more <see cref="IChangeToken"/> instances. /// </summary> public class CompositeChangeToken : IChangeToken { private static readonly Action<object?> _onChangeDelegate = OnChange; private readonly object _callbackLock = new(); private CancellationTokenSource? _cancellationTokenSource; private List<IDisposable>? _disposables; [MemberNotNullWhen(true, nameof(_cancellationTokenSource))] [MemberNotNullWhen(true, nameof(_disposables))] private bool RegisteredCallbackProxy { get; set; } /// <summary> /// Creates a new instance of <see cref="CompositeChangeToken"/>. /// </summary> /// <param name="changeTokens">The list of <see cref="IChangeToken"/> to compose.</param> public CompositeChangeToken(IReadOnlyList<IChangeToken> changeTokens!!) { ChangeTokens = changeTokens; for (int i = 0; i < ChangeTokens.Count; i++) { if (ChangeTokens[i].ActiveChangeCallbacks) { ActiveChangeCallbacks = true; break; } } } /// <summary> /// Returns the list of <see cref="IChangeToken"/> which compose the current <see cref="CompositeChangeToken"/>. /// </summary> public IReadOnlyList<IChangeToken> ChangeTokens { get; } /// <inheritdoc /> public IDisposable RegisterChangeCallback(Action<object?> callback, object? state) { EnsureCallbacksInitialized(); return _cancellationTokenSource.Token.Register(callback, state); } /// <inheritdoc /> public bool HasChanged { get { if (_cancellationTokenSource != null && _cancellationTokenSource.Token.IsCancellationRequested) { return true; } for (int i = 0; i < ChangeTokens.Count; i++) { if (ChangeTokens[i].HasChanged) { OnChange(this); return true; } } return false; } } /// <inheritdoc /> public bool ActiveChangeCallbacks { get; } [MemberNotNull(nameof(_cancellationTokenSource))] [MemberNotNull(nameof(_disposables))] private void EnsureCallbacksInitialized() { if (RegisteredCallbackProxy) { return; } lock (_callbackLock) { if (RegisteredCallbackProxy) { return; } _cancellationTokenSource = new CancellationTokenSource(); _disposables = new List<IDisposable>(); for (int i = 0; i < ChangeTokens.Count; i++) { if (ChangeTokens[i].ActiveChangeCallbacks) { IDisposable disposable = ChangeTokens[i].RegisterChangeCallback(_onChangeDelegate, this); _disposables.Add(disposable); } } RegisteredCallbackProxy = true; } } private static void OnChange(object? state) { Debug.Assert(state != null); var compositeChangeTokenState = (CompositeChangeToken)state; if (compositeChangeTokenState._cancellationTokenSource == null) { return; } lock (compositeChangeTokenState._callbackLock) { try { compositeChangeTokenState._cancellationTokenSource.Cancel(); } catch { } } List<IDisposable>? disposables = compositeChangeTokenState._disposables; Debug.Assert(disposables != null); for (int i = 0; i < disposables.Count; i++) { disposables[i].Dispose(); } } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/JIT/Methodical/VT/etc/nested_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="nested.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="nested.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/License.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.ComponentModel { /// <summary> /// Provides the <see langword='abstract'/> base class for all licenses. A license is /// granted to a specific instance of a component. /// </summary> public abstract class License : IDisposable { /// <summary> /// When overridden in a derived class, gets the license key granted to this component. /// </summary> public abstract string LicenseKey { get; } /// <summary> /// When overridden in a derived class, releases the license. /// </summary> public abstract void Dispose(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.ComponentModel { /// <summary> /// Provides the <see langword='abstract'/> base class for all licenses. A license is /// granted to a specific instance of a component. /// </summary> public abstract class License : IDisposable { /// <summary> /// When overridden in a derived class, gets the license key granted to this component. /// </summary> public abstract string LicenseKey { get; } /// <summary> /// When overridden in a derived class, releases the license. /// </summary> public abstract void Dispose(); } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/System.Private.CoreLib/src/System/IO/Path.Unix.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.Text; namespace System.IO { public static partial class Path { public static char[] GetInvalidFileNameChars() => new char[] { '\0', '/' }; public static char[] GetInvalidPathChars() => new char[] { '\0' }; // Checks if the given path is available for use. private static bool ExistsCore(string fullPath, out bool isDirectory) { bool result = Interop.Sys.LStat(fullPath, out Interop.Sys.FileStatus fileInfo) == Interop.Errors.ERROR_SUCCESS; isDirectory = result && (fileInfo.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR; return result; } // Expands the given path to a fully qualified path. public static string GetFullPath(string path) { ArgumentException.ThrowIfNullOrEmpty(path); if (path.Contains('\0')) throw new ArgumentException(SR.Argument_InvalidPathChars, nameof(path)); return GetFullPathInternal(path); } public static string GetFullPath(string path!!, string basePath!!) { if (!IsPathFullyQualified(basePath)) throw new ArgumentException(SR.Arg_BasePathNotFullyQualified, nameof(basePath)); if (basePath.Contains('\0') || path.Contains('\0')) throw new ArgumentException(SR.Argument_InvalidPathChars); if (IsPathFullyQualified(path)) return GetFullPathInternal(path); return GetFullPathInternal(CombineInternal(basePath, path)); } // Gets the full path without argument validation private static string GetFullPathInternal(string path) { Debug.Assert(!string.IsNullOrEmpty(path)); Debug.Assert(!path.Contains('\0')); // Expand with current directory if necessary if (!IsPathRooted(path)) { path = Combine(Interop.Sys.GetCwd(), path); } // We would ideally use realpath to do this, but it resolves symlinks, requires that the file actually exist, // and turns it into a full path, which we only want if fullCheck is true. string collapsedString = PathInternal.RemoveRelativeSegments(path, PathInternal.GetRootLength(path)); Debug.Assert(collapsedString.Length < path.Length || collapsedString.ToString() == path, "Either we've removed characters, or the string should be unmodified from the input path."); string result = collapsedString.Length == 0 ? PathInternal.DirectorySeparatorCharAsString : collapsedString; return result; } private static string RemoveLongPathPrefix(string path) { return path; // nop. There's nothing special about "long" paths on Unix. } public static string GetTempPath() { const string TempEnvVar = "TMPDIR"; // Get the temp path from the TMPDIR environment variable. // If it's not set, just return the default path. // If it is, return it, ensuring it ends with a slash. string? path = Environment.GetEnvironmentVariable(TempEnvVar); return string.IsNullOrEmpty(path) ? DefaultTempPath : PathInternal.IsDirectorySeparator(path[path.Length - 1]) ? path : path + PathInternal.DirectorySeparatorChar; } public static string GetTempFileName() { const string Suffix = ".tmp"; const int SuffixByteLength = 4; // mkstemps takes a char* and overwrites the XXXXXX with six characters // that'll result in a unique file name. string template = GetTempPath() + "tmpXXXXXX" + Suffix + "\0"; byte[] name = Encoding.UTF8.GetBytes(template); // Create, open, and close the temp file. IntPtr fd = Interop.CheckIo(Interop.Sys.MksTemps(name, SuffixByteLength)); Interop.Sys.Close(fd); // ignore any errors from close; nothing to do if cleanup isn't possible // 'name' is now the name of the file Debug.Assert(name[name.Length - 1] == '\0'); return Encoding.UTF8.GetString(name, 0, name.Length - 1); // trim off the trailing '\0' } public static bool IsPathRooted([NotNullWhen(true)] string? path) { if (path == null) return false; return IsPathRooted(path.AsSpan()); } public static bool IsPathRooted(ReadOnlySpan<char> path) { return path.Length > 0 && path[0] == PathInternal.DirectorySeparatorChar; } /// <summary> /// Returns the path root or null if path is empty or null. /// </summary> public static string? GetPathRoot(string? path) { if (PathInternal.IsEffectivelyEmpty(path)) return null; return IsPathRooted(path) ? PathInternal.DirectorySeparatorCharAsString : string.Empty; } public static ReadOnlySpan<char> GetPathRoot(ReadOnlySpan<char> path) { return IsPathRooted(path) ? PathInternal.DirectorySeparatorCharAsString.AsSpan() : ReadOnlySpan<char>.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.Diagnostics.CodeAnalysis; using System.Text; namespace System.IO { public static partial class Path { public static char[] GetInvalidFileNameChars() => new char[] { '\0', '/' }; public static char[] GetInvalidPathChars() => new char[] { '\0' }; // Checks if the given path is available for use. private static bool ExistsCore(string fullPath, out bool isDirectory) { bool result = Interop.Sys.LStat(fullPath, out Interop.Sys.FileStatus fileInfo) == Interop.Errors.ERROR_SUCCESS; isDirectory = result && (fileInfo.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR; return result; } // Expands the given path to a fully qualified path. public static string GetFullPath(string path) { ArgumentException.ThrowIfNullOrEmpty(path); if (path.Contains('\0')) throw new ArgumentException(SR.Argument_InvalidPathChars, nameof(path)); return GetFullPathInternal(path); } public static string GetFullPath(string path!!, string basePath!!) { if (!IsPathFullyQualified(basePath)) throw new ArgumentException(SR.Arg_BasePathNotFullyQualified, nameof(basePath)); if (basePath.Contains('\0') || path.Contains('\0')) throw new ArgumentException(SR.Argument_InvalidPathChars); if (IsPathFullyQualified(path)) return GetFullPathInternal(path); return GetFullPathInternal(CombineInternal(basePath, path)); } // Gets the full path without argument validation private static string GetFullPathInternal(string path) { Debug.Assert(!string.IsNullOrEmpty(path)); Debug.Assert(!path.Contains('\0')); // Expand with current directory if necessary if (!IsPathRooted(path)) { path = Combine(Interop.Sys.GetCwd(), path); } // We would ideally use realpath to do this, but it resolves symlinks, requires that the file actually exist, // and turns it into a full path, which we only want if fullCheck is true. string collapsedString = PathInternal.RemoveRelativeSegments(path, PathInternal.GetRootLength(path)); Debug.Assert(collapsedString.Length < path.Length || collapsedString.ToString() == path, "Either we've removed characters, or the string should be unmodified from the input path."); string result = collapsedString.Length == 0 ? PathInternal.DirectorySeparatorCharAsString : collapsedString; return result; } private static string RemoveLongPathPrefix(string path) { return path; // nop. There's nothing special about "long" paths on Unix. } public static string GetTempPath() { const string TempEnvVar = "TMPDIR"; // Get the temp path from the TMPDIR environment variable. // If it's not set, just return the default path. // If it is, return it, ensuring it ends with a slash. string? path = Environment.GetEnvironmentVariable(TempEnvVar); return string.IsNullOrEmpty(path) ? DefaultTempPath : PathInternal.IsDirectorySeparator(path[path.Length - 1]) ? path : path + PathInternal.DirectorySeparatorChar; } public static string GetTempFileName() { const string Suffix = ".tmp"; const int SuffixByteLength = 4; // mkstemps takes a char* and overwrites the XXXXXX with six characters // that'll result in a unique file name. string template = GetTempPath() + "tmpXXXXXX" + Suffix + "\0"; byte[] name = Encoding.UTF8.GetBytes(template); // Create, open, and close the temp file. IntPtr fd = Interop.CheckIo(Interop.Sys.MksTemps(name, SuffixByteLength)); Interop.Sys.Close(fd); // ignore any errors from close; nothing to do if cleanup isn't possible // 'name' is now the name of the file Debug.Assert(name[name.Length - 1] == '\0'); return Encoding.UTF8.GetString(name, 0, name.Length - 1); // trim off the trailing '\0' } public static bool IsPathRooted([NotNullWhen(true)] string? path) { if (path == null) return false; return IsPathRooted(path.AsSpan()); } public static bool IsPathRooted(ReadOnlySpan<char> path) { return path.Length > 0 && path[0] == PathInternal.DirectorySeparatorChar; } /// <summary> /// Returns the path root or null if path is empty or null. /// </summary> public static string? GetPathRoot(string? path) { if (PathInternal.IsEffectivelyEmpty(path)) return null; return IsPathRooted(path) ? PathInternal.DirectorySeparatorCharAsString : string.Empty; } public static ReadOnlySpan<char> GetPathRoot(ReadOnlySpan<char> path) { return IsPathRooted(path) ? PathInternal.DirectorySeparatorCharAsString.AsSpan() : ReadOnlySpan<char>.Empty; } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/JIT/Methodical/Boxing/misc/tailjump_cs_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="tailjump.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="tailjump.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/JIT/HardwareIntrinsics/X86/Sse2/AndNot.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; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AndNotInt32() { var test = new SimpleBinaryOpTest__AndNotInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AndNotInt32 { 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, Int32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); 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<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* 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<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(SimpleBinaryOpTest__AndNotInt32 testClass) { var result = Sse2.AndNot(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndNotInt32 testClass) { fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((Int32*)(pFld1)), Sse2.LoadVector128((Int32*)(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<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = 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 SimpleBinaryOpTest__AndNotInt32() { 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 SimpleBinaryOpTest__AndNotInt32() { 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, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.AndNot( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.AndNot( Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.AndNot( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.AndNot( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) { var result = Sse2.AndNot( Sse2.LoadVector128((Int32*)(pClsVar1)), Sse2.LoadVector128((Int32*)(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<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AndNotInt32(); var result = Sse2.AndNot(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__AndNotInt32(); fixed (Vector128<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((Int32*)(pFld1)), Sse2.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.AndNot(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((Int32*)(pFld1)), Sse2.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.AndNot( Sse2.LoadVector128((Int32*)(&test._fld1)), Sse2.LoadVector128((Int32*)(&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<Int32> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; 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>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((int)(~left[0] & right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((int)(~left[i] & right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.AndNot)}<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: ({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 AndNotInt32() { var test = new SimpleBinaryOpTest__AndNotInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AndNotInt32 { 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, Int32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); 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<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* 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<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(SimpleBinaryOpTest__AndNotInt32 testClass) { var result = Sse2.AndNot(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndNotInt32 testClass) { fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((Int32*)(pFld1)), Sse2.LoadVector128((Int32*)(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<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = 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 SimpleBinaryOpTest__AndNotInt32() { 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 SimpleBinaryOpTest__AndNotInt32() { 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, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.AndNot( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.AndNot( Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.AndNot( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.AndNot( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) { var result = Sse2.AndNot( Sse2.LoadVector128((Int32*)(pClsVar1)), Sse2.LoadVector128((Int32*)(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<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse2.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AndNotInt32(); var result = Sse2.AndNot(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__AndNotInt32(); fixed (Vector128<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((Int32*)(pFld1)), Sse2.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.AndNot(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = Sse2.AndNot( Sse2.LoadVector128((Int32*)(pFld1)), Sse2.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.AndNot( Sse2.LoadVector128((Int32*)(&test._fld1)), Sse2.LoadVector128((Int32*)(&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<Int32> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; 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>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((int)(~left[0] & right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((int)(~left[i] & right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.AndNot)}<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: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/System.ComponentModel.TypeConverter/tests/DataObjectMethodAttributeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Xunit; namespace System.ComponentModel.Tests { public class DataObjectMethodAttributeTests { [Theory] [InlineData(DataObjectMethodType.Delete)] [InlineData(DataObjectMethodType.Fill - 1)] [InlineData(DataObjectMethodType.Delete + 1)] public void Ctor_MethodType(DataObjectMethodType methodType) { var attribute = new DataObjectMethodAttribute(methodType); Assert.Equal(methodType, attribute.MethodType); Assert.False(attribute.IsDefault); } [Theory] [InlineData(DataObjectMethodType.Delete, true)] [InlineData(DataObjectMethodType.Fill - 1, false)] [InlineData(DataObjectMethodType.Delete + 1, false)] public void Ctor_MethodType_IsDefault(DataObjectMethodType methodType, bool isDefault) { var attribute = new DataObjectMethodAttribute(methodType, isDefault); Assert.Equal(methodType, attribute.MethodType); Assert.Equal(isDefault, attribute.IsDefault); } public static IEnumerable<object[]> Equals_TestData() { var attribute = new DataObjectMethodAttribute(DataObjectMethodType.Fill, true); yield return new object[] { attribute, attribute, true }; yield return new object[] { attribute, new DataObjectMethodAttribute(DataObjectMethodType.Fill, true), true }; yield return new object[] { attribute, new DataObjectMethodAttribute(DataObjectMethodType.Delete, true), false }; yield return new object[] { attribute, new DataObjectMethodAttribute(DataObjectMethodType.Fill, false), false }; yield return new object[] { attribute, new object(), false }; yield return new object[] { attribute, null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals_Other_ReturnsExpected(DataObjectMethodAttribute attribute, object other, bool expected) { Assert.Equal(expected, attribute.Equals(other)); if (other is DataObjectMethodAttribute) { Assert.Equal(expected, attribute.GetHashCode().Equals(other.GetHashCode())); } } public static IEnumerable<object[]> Match_TestData() { var attribute = new DataObjectMethodAttribute(DataObjectMethodType.Fill, true); yield return new object[] { attribute, attribute, true }; yield return new object[] { attribute, new DataObjectMethodAttribute(DataObjectMethodType.Fill, true), true }; yield return new object[] { attribute, new DataObjectMethodAttribute(DataObjectMethodType.Delete, true), false }; yield return new object[] { attribute, new DataObjectMethodAttribute(DataObjectMethodType.Fill, false), true }; yield return new object[] { attribute, new object(), false }; yield return new object[] { attribute, null, false }; } [Theory] [MemberData(nameof(Match_TestData))] public void Match_Other_ReturnsExpected(DataObjectMethodAttribute attribute, object other, bool expected) { Assert.Equal(expected, attribute.Match(other)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Xunit; namespace System.ComponentModel.Tests { public class DataObjectMethodAttributeTests { [Theory] [InlineData(DataObjectMethodType.Delete)] [InlineData(DataObjectMethodType.Fill - 1)] [InlineData(DataObjectMethodType.Delete + 1)] public void Ctor_MethodType(DataObjectMethodType methodType) { var attribute = new DataObjectMethodAttribute(methodType); Assert.Equal(methodType, attribute.MethodType); Assert.False(attribute.IsDefault); } [Theory] [InlineData(DataObjectMethodType.Delete, true)] [InlineData(DataObjectMethodType.Fill - 1, false)] [InlineData(DataObjectMethodType.Delete + 1, false)] public void Ctor_MethodType_IsDefault(DataObjectMethodType methodType, bool isDefault) { var attribute = new DataObjectMethodAttribute(methodType, isDefault); Assert.Equal(methodType, attribute.MethodType); Assert.Equal(isDefault, attribute.IsDefault); } public static IEnumerable<object[]> Equals_TestData() { var attribute = new DataObjectMethodAttribute(DataObjectMethodType.Fill, true); yield return new object[] { attribute, attribute, true }; yield return new object[] { attribute, new DataObjectMethodAttribute(DataObjectMethodType.Fill, true), true }; yield return new object[] { attribute, new DataObjectMethodAttribute(DataObjectMethodType.Delete, true), false }; yield return new object[] { attribute, new DataObjectMethodAttribute(DataObjectMethodType.Fill, false), false }; yield return new object[] { attribute, new object(), false }; yield return new object[] { attribute, null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals_Other_ReturnsExpected(DataObjectMethodAttribute attribute, object other, bool expected) { Assert.Equal(expected, attribute.Equals(other)); if (other is DataObjectMethodAttribute) { Assert.Equal(expected, attribute.GetHashCode().Equals(other.GetHashCode())); } } public static IEnumerable<object[]> Match_TestData() { var attribute = new DataObjectMethodAttribute(DataObjectMethodType.Fill, true); yield return new object[] { attribute, attribute, true }; yield return new object[] { attribute, new DataObjectMethodAttribute(DataObjectMethodType.Fill, true), true }; yield return new object[] { attribute, new DataObjectMethodAttribute(DataObjectMethodType.Delete, true), false }; yield return new object[] { attribute, new DataObjectMethodAttribute(DataObjectMethodType.Fill, false), true }; yield return new object[] { attribute, new object(), false }; yield return new object[] { attribute, null, false }; } [Theory] [MemberData(nameof(Match_TestData))] public void Match_Other_ReturnsExpected(DataObjectMethodAttribute attribute, object other, bool expected) { Assert.Equal(expected, attribute.Match(other)); } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/JIT/opt/Tailcall/ImplicitByrefTailCalls.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; // Tail calls with implicit byref parameters as arguments. // // Generally, we can tail call provided we don't copy the // argument to the local frame. public class ImplicitByrefTailCalls { public static void Z() { } public static bool Z(bool b) => b; [MethodImpl(MethodImplOptions.NoOptimization)] public static int ZZ(Span<int> x) { int result = 0; for (int i = 0; i < x.Length; i++) { result += x[i] * x[i] + i; } return result; } [MethodImpl(MethodImplOptions.NoOptimization)] public static int ZZZ(Span<int> x, int a, int b, int c, int d, int e, int f) { int result = 0; for (int i = 0; i < x.Length; i++) { result += x[i] * x[i] + i; } return result; } // Various methods that should fast tail call public static int A(Span<int> x) { Z(); Z(); return ZZ(x); } public static int B(Span<int> x) { Z(); Z(); return A(x); } public static int C(Span<int> x, bool p) { Z(); Z(); if (Z(p)) { return A(x); } else { return B(x); } } public static int D(Span<int> x, bool p) { Z(); Z(); return Z(p) ? A(x) : B(x); } public static int E(Span<int> x, Span<int> y, bool p) { Z(); Z(); Z(); Z(); if (Z(p)) { return A(x); } else { return B(y); } } public static int F(Span<int> x, Span<int> y, bool p) { Z(); Z(); Z(); Z(); return Z(p) ? ZZ(x) : ZZ(y); } // Methods with tail call sites and other uses public static int G(Span<int> x, bool p) { Z(); Z(); if (Z(p)) { return ZZ(x); } else { return x.Length; } } // Here there are enough actual uses to // justify promotion, hence we can't tail // call, as "undoing" promotion at the end // entails making a local copy. // // We could handle this by writing the updated // struct values back to the original byref // before tail calling.... public static int H(Span<int> x, int y) { Z(); Z(); if (y < x.Length) { int result = 0; for (int i = 0; i < y; i++) { result += x[i]; } return result; } return ZZ(x); } // Here the call to ZZZ would need to be a slow tail call, // so we won't tail call at all. But the only // reference to x is at the call, and it's not in // a loop, so we can still can avoid making a copy. public static int S(Span<int> x) { Z(); Z(); return ZZZ(x, 1, 2, 3, 4, 5, 6); } // Must copy at the normal call site // but can avoid at tail call site. However // we're currently blocked because we reuse // the temp used to pass the argument and // it is exposed in the first call. public static int T(Span<int> x, ref int q) { Z(); Z(); q = ZZ(x); return ZZ(x); } // Here ZZZ is called in a loop, so despite // the call argument x being the only reference to // x in the method, we must copy x. // We can't consider it as last use. public static int L(Span<int> x) { Z(); Z(); int result = 0; int limit = 10; for (int i = 0; i < limit; i++) { result += ZZZ(x, 1, 2, 3, 4, 5, 6); } return result / limit; } static void MustThrow(Span<int> x) { x[0]++; throw new Exception(); } // Because MustThrow must throw // and the argument is the only // mention of x, we do not need to copy x. public static int M(Span<int> x) { Z(); Z(); Z(); Z(); if (p) { MustThrow(x); } return 10000; } // Although MustThrow must throw, // the argument x is the not only // mention of x, so we must copy x. public static int N(Span<int> x) { Z(); Z(); Z(); Z(); try { if (p) { MustThrow(x); } } catch (Exception) { } return 10000 + x[0]; } static bool p; public static int Main() { int[] a = new int[100]; a[45] = 55; a[55] = 45; p = false; Span<int> s = new Span<int>(a); int q = 0; int ra = A(s); int rb = B(s); int rc = C(s, p); int rd = D(s, p); int re = E(s, s, p); int rf = F(s, s, p); int rg = G(s, p); int rh = H(s, 46); int rs = S(s); int rt = T(s, ref q); int rl = L(s); int rm = M(s); int rn = N(s); Console.WriteLine($"{ra},{rb},{rc},{rd},{re},{rf},{rg},{rh},{rs},{rt},{rl},{rm},{rn}"); return ra + rb + rc + rd + re + rf + rg + rh + rs + rt + rl + rm + rn - 110055; } }
// 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; // Tail calls with implicit byref parameters as arguments. // // Generally, we can tail call provided we don't copy the // argument to the local frame. public class ImplicitByrefTailCalls { public static void Z() { } public static bool Z(bool b) => b; [MethodImpl(MethodImplOptions.NoOptimization)] public static int ZZ(Span<int> x) { int result = 0; for (int i = 0; i < x.Length; i++) { result += x[i] * x[i] + i; } return result; } [MethodImpl(MethodImplOptions.NoOptimization)] public static int ZZZ(Span<int> x, int a, int b, int c, int d, int e, int f) { int result = 0; for (int i = 0; i < x.Length; i++) { result += x[i] * x[i] + i; } return result; } // Various methods that should fast tail call public static int A(Span<int> x) { Z(); Z(); return ZZ(x); } public static int B(Span<int> x) { Z(); Z(); return A(x); } public static int C(Span<int> x, bool p) { Z(); Z(); if (Z(p)) { return A(x); } else { return B(x); } } public static int D(Span<int> x, bool p) { Z(); Z(); return Z(p) ? A(x) : B(x); } public static int E(Span<int> x, Span<int> y, bool p) { Z(); Z(); Z(); Z(); if (Z(p)) { return A(x); } else { return B(y); } } public static int F(Span<int> x, Span<int> y, bool p) { Z(); Z(); Z(); Z(); return Z(p) ? ZZ(x) : ZZ(y); } // Methods with tail call sites and other uses public static int G(Span<int> x, bool p) { Z(); Z(); if (Z(p)) { return ZZ(x); } else { return x.Length; } } // Here there are enough actual uses to // justify promotion, hence we can't tail // call, as "undoing" promotion at the end // entails making a local copy. // // We could handle this by writing the updated // struct values back to the original byref // before tail calling.... public static int H(Span<int> x, int y) { Z(); Z(); if (y < x.Length) { int result = 0; for (int i = 0; i < y; i++) { result += x[i]; } return result; } return ZZ(x); } // Here the call to ZZZ would need to be a slow tail call, // so we won't tail call at all. But the only // reference to x is at the call, and it's not in // a loop, so we can still can avoid making a copy. public static int S(Span<int> x) { Z(); Z(); return ZZZ(x, 1, 2, 3, 4, 5, 6); } // Must copy at the normal call site // but can avoid at tail call site. However // we're currently blocked because we reuse // the temp used to pass the argument and // it is exposed in the first call. public static int T(Span<int> x, ref int q) { Z(); Z(); q = ZZ(x); return ZZ(x); } // Here ZZZ is called in a loop, so despite // the call argument x being the only reference to // x in the method, we must copy x. // We can't consider it as last use. public static int L(Span<int> x) { Z(); Z(); int result = 0; int limit = 10; for (int i = 0; i < limit; i++) { result += ZZZ(x, 1, 2, 3, 4, 5, 6); } return result / limit; } static void MustThrow(Span<int> x) { x[0]++; throw new Exception(); } // Because MustThrow must throw // and the argument is the only // mention of x, we do not need to copy x. public static int M(Span<int> x) { Z(); Z(); Z(); Z(); if (p) { MustThrow(x); } return 10000; } // Although MustThrow must throw, // the argument x is the not only // mention of x, so we must copy x. public static int N(Span<int> x) { Z(); Z(); Z(); Z(); try { if (p) { MustThrow(x); } } catch (Exception) { } return 10000 + x[0]; } static bool p; public static int Main() { int[] a = new int[100]; a[45] = 55; a[55] = 45; p = false; Span<int> s = new Span<int>(a); int q = 0; int ra = A(s); int rb = B(s); int rc = C(s, p); int rd = D(s, p); int re = E(s, s, p); int rf = F(s, s, p); int rg = G(s, p); int rh = H(s, 46); int rs = S(s); int rt = T(s, ref q); int rl = L(s); int rm = M(s); int rn = N(s); Console.WriteLine($"{ra},{rb},{rc},{rd},{re},{rf},{rg},{rh},{rs},{rt},{rl},{rm},{rn}"); return ra + rb + rc + rd + re + rf + rg + rh + rs + rt + rl + rm + rn - 110055; } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/JIT/jit64/valuetypes/nullable/box-unbox/generics/box-unbox-generics010.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="box-unbox-generics010.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="box-unbox-generics010.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ASN1.Nid.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.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography; internal static partial class Interop { internal static partial class Crypto { private static readonly ConcurrentDictionary<string, int> s_nidLookup = new ConcurrentDictionary<string, int>(); internal const int NID_undef = 0; [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ObjTxt2Nid", StringMarshalling = StringMarshalling.Utf8)] private static partial int ObjTxt2Nid(string oid); internal static int ResolveRequiredNid(string oid) { return s_nidLookup.GetOrAdd(oid, s => LookupNid(s)); } private static int LookupNid(string oid) { int nid = ObjTxt2Nid(oid); if (nid == NID_undef) { Debug.Fail($"NID Lookup for {oid} failed, only well-known types should be queried."); throw new CryptographicException(); } return nid; } } }
// 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.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography; internal static partial class Interop { internal static partial class Crypto { private static readonly ConcurrentDictionary<string, int> s_nidLookup = new ConcurrentDictionary<string, int>(); internal const int NID_undef = 0; [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ObjTxt2Nid", StringMarshalling = StringMarshalling.Utf8)] private static partial int ObjTxt2Nid(string oid); internal static int ResolveRequiredNid(string oid) { return s_nidLookup.GetOrAdd(oid, s => LookupNid(s)); } private static int LookupNid(string oid) { int nid = ObjTxt2Nid(oid); if (nid == NID_undef) { Debug.Fail($"NID Lookup for {oid} failed, only well-known types should be queried."); throw new CryptographicException(); } return nid; } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/System.ComponentModel.Composition.Registration/tests/System/ComponentModel/Composition/Registration/RegistrationBuilderTests.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.ComponentModel.Composition.Hosting; using System.Linq; using System.Reflection; using Xunit; namespace System.ComponentModel.Composition.Registration.Tests { public class RegistrationBuilderTests { private interface IFoo { } private class FooImpl : IFoo { public string P1 { get; set; } public string P2 { get; set; } public IEnumerable<IFoo> P3 { get; set; } } private class FooImplWithConstructors : IFoo { public FooImplWithConstructors() { } public FooImplWithConstructors(IEnumerable<IFoo> ids) { } public FooImplWithConstructors(int id, string name) { } } private class FooImplWithConstructors2 : IFoo { public FooImplWithConstructors2() { } public FooImplWithConstructors2(IEnumerable<IFoo> ids) { } public FooImplWithConstructors2(int id, string name) { } } private class RealPart { } private class DiscoveredCatalog : AssemblyCatalog { public DiscoveredCatalog() : base("") { } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))] public void ShouldSucceed() { var rb = new RegistrationBuilder(); rb.ForType<RealPart>().Export(); var cat = new AssemblyCatalog(typeof(RegistrationBuilderTests).Assembly, rb); var container = new CompositionContainer(cat); // Throws: // Can not determine which constructor to use for the type 'System.ComponentModel.Composition.Hosting.AssemblyCatalog, System.ComponentModel.Composition, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. RealPart rp = container.GetExport<RealPart>().Value; } [Fact] public void MapType_ShouldReturnProjectedAttributesForType() { var builder = new RegistrationBuilder(); builder.ForTypesDerivedFrom<IFoo>() .Export<IFoo>(); TypeInfo projectedType1 = builder.MapType(typeof(FooImpl).GetTypeInfo()); TypeInfo projectedType2 = builder.MapType(typeof(FooImplWithConstructors).GetTypeInfo()); var exports = new List<object>(); exports.AddRange(projectedType1.GetCustomAttributes(typeof(ExportAttribute), false)); exports.AddRange(projectedType2.GetCustomAttributes(typeof(ExportAttribute), false)); Assert.Equal(2, exports.Count); foreach (var exportAttribute in exports) { Assert.Equal(typeof(IFoo), ((ExportAttribute)exportAttribute).ContractType); Assert.Null(((ExportAttribute)exportAttribute).ContractName); } } [Fact] public void MapType_ConventionSelectedConstructor() { var builder = new RegistrationBuilder(); builder.ForTypesDerivedFrom<IFoo>() .Export<IFoo>(); TypeInfo projectedType1 = builder.MapType(typeof(FooImpl).GetTypeInfo()); TypeInfo projectedType2 = builder.MapType(typeof(FooImplWithConstructors).GetTypeInfo()); // necessary as BuildConventionConstructorAttributes is only called for type level query for attributes var typeLevelAttrs = projectedType2.GetCustomAttributes(false); ConstructorInfo constructor1 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 0).Single(); ConstructorInfo constructor2 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 1).Single(); ConstructorInfo constructor3 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 2).Single(); Assert.Equal(0, constructor1.GetCustomAttributes(false).Length); Assert.Equal(0, constructor2.GetCustomAttributes(false).Length); ConstructorInfo ci = constructor3; var attrs = ci.GetCustomAttributes(false); Assert.Equal(1, attrs.Length); Assert.Equal(typeof(ImportingConstructorAttribute), attrs[0].GetType()); } [Fact] public void MapType_OverridingSelectionOfConventionSelectedConstructor() { var builder = new RegistrationBuilder(); builder.ForTypesDerivedFrom<IFoo>() .Export<IFoo>(); builder.ForType<FooImplWithConstructors>() .SelectConstructor(cis => cis[1]); TypeInfo projectedType1 = builder.MapType(typeof(FooImpl).GetTypeInfo().GetTypeInfo()); TypeInfo projectedType2 = builder.MapType(typeof(FooImplWithConstructors).GetTypeInfo().GetTypeInfo()); ConstructorInfo constructor1 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 0).Single(); ConstructorInfo constructor2 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 1).Single(); ConstructorInfo constructor3 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 2).Single(); // necessary as BuildConventionConstructorAttributes is only called for type level query for attributes var typeLevelAttrs = projectedType2.GetCustomAttributes(false); Assert.Equal(0, constructor1.GetCustomAttributes(false).Length); Assert.Equal(0, constructor3.GetCustomAttributes(false).Length); ConstructorInfo ci = constructor2; var attrs = ci.GetCustomAttributes(false); Assert.Equal(1, attrs.Length); Assert.IsType<ImportingConstructorAttribute>(attrs[0]); } [Fact] public void MapType_OverridingSelectionOfConventionSelectedConstructor_WithPartBuilderOfT() { var builder = new RegistrationBuilder(); builder.ForTypesDerivedFrom<IFoo>() .Export<IFoo>(); builder.ForType<FooImplWithConstructors2>(). SelectConstructor(param => new FooImplWithConstructors2(param.Import<IEnumerable<IFoo>>())); TypeInfo projectedType1 = builder.MapType(typeof(FooImpl).GetTypeInfo().GetTypeInfo()); TypeInfo projectedType2 = builder.MapType(typeof(FooImplWithConstructors2).GetTypeInfo().GetTypeInfo()); ConstructorInfo constructor1 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 0).Single(); ConstructorInfo constructor2 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 1).Single(); ConstructorInfo constructor3 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 2).Single(); // necessary as BuildConventionConstructorAttributes is only called for type level query for attributes var typeLevelAttrs = projectedType2.GetCustomAttributes(false); Assert.Equal(0, constructor1.GetCustomAttributes(false).Length); Assert.Equal(0, constructor3.GetCustomAttributes(false).Length); ConstructorInfo ci = constructor2; var attrs = ci.GetCustomAttributes(false); Assert.Equal(1, attrs.Length); Assert.IsType<ImportingConstructorAttribute>(attrs[0]); } private interface IGenericInterface<T> { } [Export(typeof(IGenericInterface<>))] private class ClassExportingInterface<T> : IGenericInterface<T> { } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))] public void GenericInterfaceExportInRegistrationBuilder() { CompositionContainer container = CreateRegistrationBuilderContainer(typeof(ClassExportingInterface<>)); IGenericInterface<string> v = container.GetExportedValue<IGenericInterface<string>>(); Assert.IsAssignableFrom<IGenericInterface<string>>(v); } private class GenericBaseClass<T> { } [Export(typeof(GenericBaseClass<>))] private class ClassExportingBaseClass<T> : GenericBaseClass<T> { } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))] public void GenericBaseClassExportInRegistrationBuilder() { CompositionContainer container = CreateRegistrationBuilderContainer(typeof(ClassExportingBaseClass<>)); GenericBaseClass<string> v = container.GetExportedValue<GenericBaseClass<string>>(); Assert.IsAssignableFrom<GenericBaseClass<string>>(v); } [Export] private class GenericClass<T> { } [Fact] public void GenericExportInRegistrationBuilder() { CompositionContainer container = CreateRegistrationBuilderContainer(typeof(GenericClass<>)); GenericClass<string> v = container.GetExportedValue<GenericClass<string>>(); Assert.IsType<GenericClass<string>>(v); } [Export(typeof(ExplicitGenericClass<>))] private class ExplicitGenericClass<T> { } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))] public void ExplicitGenericExportInRegistrationBuilder() { CompositionContainer container = CreateRegistrationBuilderContainer(typeof(ExplicitGenericClass<>)); ExplicitGenericClass<string> v = container.GetExportedValue<ExplicitGenericClass<string>>(); Assert.IsType<ExplicitGenericClass<string>>(v); } [Export(typeof(ExplicitGenericClass<,>))] private class ExplicitGenericClass<T, U> { } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))] public void ExplicitGenericArity2ExportInRegistrationBuilder() { CompositionContainer container = CreateRegistrationBuilderContainer(typeof(ExplicitGenericClass<,>)); ExplicitGenericClass<int, string> v = container.GetExportedValue<ExplicitGenericClass<int, string>>(); Assert.IsType<ExplicitGenericClass<int, string>>(v); } private CompositionContainer CreateRegistrationBuilderContainer(params Type[] types) { var reg = new RegistrationBuilder(); var container = new CompositionContainer(new TypeCatalog(types, reg)); return container; } } }
// 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.ComponentModel.Composition.Hosting; using System.Linq; using System.Reflection; using Xunit; namespace System.ComponentModel.Composition.Registration.Tests { public class RegistrationBuilderTests { private interface IFoo { } private class FooImpl : IFoo { public string P1 { get; set; } public string P2 { get; set; } public IEnumerable<IFoo> P3 { get; set; } } private class FooImplWithConstructors : IFoo { public FooImplWithConstructors() { } public FooImplWithConstructors(IEnumerable<IFoo> ids) { } public FooImplWithConstructors(int id, string name) { } } private class FooImplWithConstructors2 : IFoo { public FooImplWithConstructors2() { } public FooImplWithConstructors2(IEnumerable<IFoo> ids) { } public FooImplWithConstructors2(int id, string name) { } } private class RealPart { } private class DiscoveredCatalog : AssemblyCatalog { public DiscoveredCatalog() : base("") { } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))] public void ShouldSucceed() { var rb = new RegistrationBuilder(); rb.ForType<RealPart>().Export(); var cat = new AssemblyCatalog(typeof(RegistrationBuilderTests).Assembly, rb); var container = new CompositionContainer(cat); // Throws: // Can not determine which constructor to use for the type 'System.ComponentModel.Composition.Hosting.AssemblyCatalog, System.ComponentModel.Composition, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. RealPart rp = container.GetExport<RealPart>().Value; } [Fact] public void MapType_ShouldReturnProjectedAttributesForType() { var builder = new RegistrationBuilder(); builder.ForTypesDerivedFrom<IFoo>() .Export<IFoo>(); TypeInfo projectedType1 = builder.MapType(typeof(FooImpl).GetTypeInfo()); TypeInfo projectedType2 = builder.MapType(typeof(FooImplWithConstructors).GetTypeInfo()); var exports = new List<object>(); exports.AddRange(projectedType1.GetCustomAttributes(typeof(ExportAttribute), false)); exports.AddRange(projectedType2.GetCustomAttributes(typeof(ExportAttribute), false)); Assert.Equal(2, exports.Count); foreach (var exportAttribute in exports) { Assert.Equal(typeof(IFoo), ((ExportAttribute)exportAttribute).ContractType); Assert.Null(((ExportAttribute)exportAttribute).ContractName); } } [Fact] public void MapType_ConventionSelectedConstructor() { var builder = new RegistrationBuilder(); builder.ForTypesDerivedFrom<IFoo>() .Export<IFoo>(); TypeInfo projectedType1 = builder.MapType(typeof(FooImpl).GetTypeInfo()); TypeInfo projectedType2 = builder.MapType(typeof(FooImplWithConstructors).GetTypeInfo()); // necessary as BuildConventionConstructorAttributes is only called for type level query for attributes var typeLevelAttrs = projectedType2.GetCustomAttributes(false); ConstructorInfo constructor1 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 0).Single(); ConstructorInfo constructor2 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 1).Single(); ConstructorInfo constructor3 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 2).Single(); Assert.Equal(0, constructor1.GetCustomAttributes(false).Length); Assert.Equal(0, constructor2.GetCustomAttributes(false).Length); ConstructorInfo ci = constructor3; var attrs = ci.GetCustomAttributes(false); Assert.Equal(1, attrs.Length); Assert.Equal(typeof(ImportingConstructorAttribute), attrs[0].GetType()); } [Fact] public void MapType_OverridingSelectionOfConventionSelectedConstructor() { var builder = new RegistrationBuilder(); builder.ForTypesDerivedFrom<IFoo>() .Export<IFoo>(); builder.ForType<FooImplWithConstructors>() .SelectConstructor(cis => cis[1]); TypeInfo projectedType1 = builder.MapType(typeof(FooImpl).GetTypeInfo().GetTypeInfo()); TypeInfo projectedType2 = builder.MapType(typeof(FooImplWithConstructors).GetTypeInfo().GetTypeInfo()); ConstructorInfo constructor1 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 0).Single(); ConstructorInfo constructor2 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 1).Single(); ConstructorInfo constructor3 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 2).Single(); // necessary as BuildConventionConstructorAttributes is only called for type level query for attributes var typeLevelAttrs = projectedType2.GetCustomAttributes(false); Assert.Equal(0, constructor1.GetCustomAttributes(false).Length); Assert.Equal(0, constructor3.GetCustomAttributes(false).Length); ConstructorInfo ci = constructor2; var attrs = ci.GetCustomAttributes(false); Assert.Equal(1, attrs.Length); Assert.IsType<ImportingConstructorAttribute>(attrs[0]); } [Fact] public void MapType_OverridingSelectionOfConventionSelectedConstructor_WithPartBuilderOfT() { var builder = new RegistrationBuilder(); builder.ForTypesDerivedFrom<IFoo>() .Export<IFoo>(); builder.ForType<FooImplWithConstructors2>(). SelectConstructor(param => new FooImplWithConstructors2(param.Import<IEnumerable<IFoo>>())); TypeInfo projectedType1 = builder.MapType(typeof(FooImpl).GetTypeInfo().GetTypeInfo()); TypeInfo projectedType2 = builder.MapType(typeof(FooImplWithConstructors2).GetTypeInfo().GetTypeInfo()); ConstructorInfo constructor1 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 0).Single(); ConstructorInfo constructor2 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 1).Single(); ConstructorInfo constructor3 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 2).Single(); // necessary as BuildConventionConstructorAttributes is only called for type level query for attributes var typeLevelAttrs = projectedType2.GetCustomAttributes(false); Assert.Equal(0, constructor1.GetCustomAttributes(false).Length); Assert.Equal(0, constructor3.GetCustomAttributes(false).Length); ConstructorInfo ci = constructor2; var attrs = ci.GetCustomAttributes(false); Assert.Equal(1, attrs.Length); Assert.IsType<ImportingConstructorAttribute>(attrs[0]); } private interface IGenericInterface<T> { } [Export(typeof(IGenericInterface<>))] private class ClassExportingInterface<T> : IGenericInterface<T> { } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))] public void GenericInterfaceExportInRegistrationBuilder() { CompositionContainer container = CreateRegistrationBuilderContainer(typeof(ClassExportingInterface<>)); IGenericInterface<string> v = container.GetExportedValue<IGenericInterface<string>>(); Assert.IsAssignableFrom<IGenericInterface<string>>(v); } private class GenericBaseClass<T> { } [Export(typeof(GenericBaseClass<>))] private class ClassExportingBaseClass<T> : GenericBaseClass<T> { } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))] public void GenericBaseClassExportInRegistrationBuilder() { CompositionContainer container = CreateRegistrationBuilderContainer(typeof(ClassExportingBaseClass<>)); GenericBaseClass<string> v = container.GetExportedValue<GenericBaseClass<string>>(); Assert.IsAssignableFrom<GenericBaseClass<string>>(v); } [Export] private class GenericClass<T> { } [Fact] public void GenericExportInRegistrationBuilder() { CompositionContainer container = CreateRegistrationBuilderContainer(typeof(GenericClass<>)); GenericClass<string> v = container.GetExportedValue<GenericClass<string>>(); Assert.IsType<GenericClass<string>>(v); } [Export(typeof(ExplicitGenericClass<>))] private class ExplicitGenericClass<T> { } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))] public void ExplicitGenericExportInRegistrationBuilder() { CompositionContainer container = CreateRegistrationBuilderContainer(typeof(ExplicitGenericClass<>)); ExplicitGenericClass<string> v = container.GetExportedValue<ExplicitGenericClass<string>>(); Assert.IsType<ExplicitGenericClass<string>>(v); } [Export(typeof(ExplicitGenericClass<,>))] private class ExplicitGenericClass<T, U> { } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))] public void ExplicitGenericArity2ExportInRegistrationBuilder() { CompositionContainer container = CreateRegistrationBuilderContainer(typeof(ExplicitGenericClass<,>)); ExplicitGenericClass<int, string> v = container.GetExportedValue<ExplicitGenericClass<int, string>>(); Assert.IsType<ExplicitGenericClass<int, string>>(v); } private CompositionContainer CreateRegistrationBuilderContainer(params Type[] types) { var reg = new RegistrationBuilder(); var container = new CompositionContainer(new TypeCatalog(types, reg)); return container; } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/JIT/CodeGenBringUpTests/FPVar.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 BringUpTest_FPVar { const int Pass = 100; const int Fail = -1; [MethodImplAttribute(MethodImplOptions.NoInlining)] public static float FPVar(float x, float y) { float z = x+y; return z; } public static int Main() { float y = FPVar(1f, 1f); Console.WriteLine(y); if (System.Math.Abs(y-2f) <= Single.Epsilon) return Pass; else return Fail; } }
// 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 BringUpTest_FPVar { const int Pass = 100; const int Fail = -1; [MethodImplAttribute(MethodImplOptions.NoInlining)] public static float FPVar(float x, float y) { float z = x+y; return z; } public static int Main() { float y = FPVar(1f, 1f); Console.WriteLine(y); if (System.Math.Abs(y-2f) <= Single.Epsilon) return Pass; else return Fail; } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/JIT/HardwareIntrinsics/General/Vector64/LessThanOrEqualAll.UInt16.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void LessThanOrEqualAllUInt16() { var test = new VectorBooleanBinaryOpTest__LessThanOrEqualAllUInt16(); // 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__LessThanOrEqualAllUInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); 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<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void 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<UInt16> _fld1; public Vector64<UInt16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__LessThanOrEqualAllUInt16 testClass) { var result = Vector64.LessThanOrEqualAll(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector64<UInt16> _clsVar1; private static Vector64<UInt16> _clsVar2; private Vector64<UInt16> _fld1; private Vector64<UInt16> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__LessThanOrEqualAllUInt16() { 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>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); } public VectorBooleanBinaryOpTest__LessThanOrEqualAllUInt16() { 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 < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector64.LessThanOrEqualAll( Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector64).GetMethod(nameof(Vector64.LessThanOrEqualAll), new Type[] { typeof(Vector64<UInt16>), typeof(Vector64<UInt16>) }); if (method is null) { method = typeof(Vector64).GetMethod(nameof(Vector64.LessThanOrEqualAll), 1, new Type[] { typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector64.LessThanOrEqualAll( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr); var result = Vector64.LessThanOrEqualAll(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__LessThanOrEqualAllUInt16(); var result = Vector64.LessThanOrEqualAll(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector64.LessThanOrEqualAll(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector64.LessThanOrEqualAll(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<UInt16> op1, Vector64<UInt16> op2, bool result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; 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 inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(UInt16[] left, UInt16[] 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)}.{nameof(Vector64.LessThanOrEqualAll)}<UInt16>(Vector64<UInt16>, Vector64<UInt16>): {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 LessThanOrEqualAllUInt16() { var test = new VectorBooleanBinaryOpTest__LessThanOrEqualAllUInt16(); // 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__LessThanOrEqualAllUInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); 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<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void 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<UInt16> _fld1; public Vector64<UInt16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__LessThanOrEqualAllUInt16 testClass) { var result = Vector64.LessThanOrEqualAll(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector64<UInt16> _clsVar1; private static Vector64<UInt16> _clsVar2; private Vector64<UInt16> _fld1; private Vector64<UInt16> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__LessThanOrEqualAllUInt16() { 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>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); } public VectorBooleanBinaryOpTest__LessThanOrEqualAllUInt16() { 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 < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector64.LessThanOrEqualAll( Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector64).GetMethod(nameof(Vector64.LessThanOrEqualAll), new Type[] { typeof(Vector64<UInt16>), typeof(Vector64<UInt16>) }); if (method is null) { method = typeof(Vector64).GetMethod(nameof(Vector64.LessThanOrEqualAll), 1, new Type[] { typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector64.LessThanOrEqualAll( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr); var result = Vector64.LessThanOrEqualAll(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__LessThanOrEqualAllUInt16(); var result = Vector64.LessThanOrEqualAll(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector64.LessThanOrEqualAll(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector64.LessThanOrEqualAll(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<UInt16> op1, Vector64<UInt16> op2, bool result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; 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 inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(UInt16[] left, UInt16[] 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)}.{nameof(Vector64.LessThanOrEqualAll)}<UInt16>(Vector64<UInt16>, Vector64<UInt16>): {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,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/coreclr/tools/Common/TypeSystem/Common/LinqPoison.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 { // // The type system needs to be low level enough to be usable as // an actual runtime type system. // // LINQ is not low level enough to be allowable in the type system. // // It also has performance characteristics that make it a poor choice // in high performance components such as the type system. // // If you get an error pointing to here, the fix is to remove // "using System.Linq" from your file. Do not modify this file or // remove it from the project. // internal class Linq { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System { // // The type system needs to be low level enough to be usable as // an actual runtime type system. // // LINQ is not low level enough to be allowable in the type system. // // It also has performance characteristics that make it a poor choice // in high performance components such as the type system. // // If you get an error pointing to here, the fix is to remove // "using System.Linq" from your file. Do not modify this file or // remove it from the project. // internal class Linq { } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/System.Dynamic.Runtime/tests/Dynamic.Context/Conformance.dynamic.context.method.genmethod.regclass.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclassgenmeth.regclassgenmeth; using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclassgenmeth.regclassgenmeth { using System.Collections.Generic; public class C { } public interface I { } public class MemberClass { #region Instance methods public T Method_ReturnsT<T>() { return default(T); } public T Method_ReturnsT<T>(T t) { return t; } public T Method_ReturnsT<T, U>(out T t) { t = default(T); return t; } public T Method_ReturnsT<T>(ref T t) { t = default(T); return t; } public T Method_ReturnsT<T>(params T[] t) { return default(T); } public int M<T>(T t) where T : IEnumerable<T> { return 3; } public T Method_ReturnsT<T, U>(params U[] d) { return default(T); } public T Method_ReturnsT<T, U>(float x, T t, U u) { return default(T); } public T Method_ReturnsT<T, U>(U u) { return default(T); } public T Method_ReturnsT<T, U, V>(out U u, ref V v) { u = default(U); return default(T); } public int Method_ReturnsInt<T>(T t) { return 1; } public string Method_ReturnsString<T, U>(T t, U u) { return "foo"; } public float Method_ReturnsFloat<T, U, V>(T t, dynamic d, U u) { return 3.4f; } public float Method_ReturnsFloat<T, U, V>(T t, dynamic d, U u, ref decimal dec) { dec = 3m; return 3.4f; } public dynamic Method_ReturnsDynamic<T>(T t) { return t; } public dynamic Method_ReturnsDynamic<T, U>(T t, U u, dynamic d) { return u; } public dynamic Method_ReturnsDynamic<T, U, V>(T t, U u, V v, dynamic d) { return v; } #region Constraints on methods that have a new type parameter public U Method_ReturnsUConstraint<U>(U u) where U : class { return null; } public U Method_ReturnsUConstraint<T, U>(T t) where U : new() { return new U(); } public U Method_ReturnsUConstraint<T, U, V>(T t, V v) where U : new() where V : U, new() { return new V(); } public dynamic Method_ReturnsDynamicConstraint<T, U>(T t, U u, dynamic d) where U : new() { return new U(); } public dynamic Method_ReturnsDynamicConstraint<T, U, V>(T t, U u, V v, dynamic d) where V : class { return u; } public float Method_ReturnsFloatConstraint<T, U, V>(T t, dynamic d, U u, ref decimal dec) where V : U { dec = 3m; return 3.4f; } public string Method_ReturnsStringConstraint<T, U, V>(T t, dynamic d, U u) where U : class where V : U { return ""; } //These are negative methods... you should not be able to call them with the dynamic type because the dynamic type would not satisfy the constraints //you cannot call this like: Method_ReturnsUConstraint<dynamic>(d); because object does not derive from C public U Method_ReturnsUNegConstraint<U>(U u) where U : C { return null; } public T Method_ReturnsTNegConstraint<T, U>(U u) where U : struct { return default(T); } public float Method_ReturnsFloatNegConstraint<T, U, V>(T t, dynamic d, U u, ref decimal dec) where V : U where U : I { dec = 3m; return 3.4f; } #endregion #region Nested class public class NestedMemberClass<U> { public U Method_ReturnsU(U t) { return default(U); } public U Method_ReturnsT(params U[] d) { return default(U); } public U Method_ReturnsT<V>(out U u, ref V v) { u = default(U); return default(U); } public dynamic Method_ReturnsDynamic(U t, U u, dynamic d) { return u; } public dynamic Method_ReturnsDynamic<V>(U t, U u, V v, dynamic d) { return v; } public decimal Method_ReturnsDecimal<V>(U t, dynamic d, U u) { return 3.4m; } public byte Method_ReturnsByte<V>(U t, dynamic d, U u, ref double dec) { dec = 3; return 4; } } #endregion #endregion } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass001.regclass001 { // <Title> Tests regular class generic method used in regular method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (t.TestMethod()) return 1; return 0; } public bool TestMethod() { dynamic mc = new MemberClass(); return (bool)mc.Method_ReturnsT<bool>(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass002.regclass002 { // <Title> Tests regular class generic method used in variable initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private static dynamic s_mc = new MemberClass(); private int _loc = (int)s_mc.Method_ReturnsT<int, string>(string.Empty, null, "abc"); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (t._loc != 0) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass003.regclass003 { // <Title> Tests regular class generic method used in indexer body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class Test { private Dictionary<int, string> _dic = new Dictionary<int, string>(); private MemberClass _mc = new MemberClass(); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { if (TestSet() == 0 && TestGet() == 0) return 0; else return 1; } private static int TestSet() { Test t = new Test(); t[0] = "Test0"; t[1] = null; t[2] = "Test2"; if (t._dic[0] == "Test0" && t._dic[1] == null && t._dic[2] == "Test2") return 0; else return 1; } private static int TestGet() { Test t = new Test(); t._dic[2] = "Test0"; t._dic[1] = null; t._dic[0] = "Test2"; if (t[2] == "Test0" && t[1] == null && t[0] == "Test2") return 0; else return 1; } public string this[int i] { set { dynamic dy = _mc; _dic.Add((int)dy.Method_ReturnsT(i), value); } get { dynamic dy = _mc; return _dic[(int)dy.Method_ReturnsT(i)]; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass004.regclass004 { // <Title> Tests regular class generic method used in static constructor.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private static int s_field = 10; private static int s_result = -1; public Test() { dynamic dy = new MemberClass(); string s = "Foo"; Test.s_result = dy.Method_ReturnsT<int, int, string>(out s_field, ref s); } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (Test.s_field == 0 && Test.s_result == 0) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass005.regclass005 { // <Title> Tests regular class generic method used in variable named dynamic.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int i = 1; dynamic dynamic = new MemberClass(); int result = dynamic.Method_ReturnsT<int>(ref i); if (i == 0 && result == 0) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass006.regclass006 { public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t1 = new Test(); return t1.TestMethod<long>(1L) == 0 ? 0 : 1; } public T TestMethod<T>(T t) { dynamic dy = new MemberClass(); return (T)dy.Method_ReturnsT<T>(t, t, t); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass008.regclass008 { // <Title> Tests regular class generic method used in method body of method with conditional attribute.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private static int s_result = 0; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t1 = new Test(); t1.TestMethod(); return s_result; } [System.Diagnostics.Conditional("c1")] public void TestMethod() { dynamic dy = new MemberClass(); s_result = (int)dy.Method_ReturnsT<int, string>(null) + 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass009.regclass009 { // <Title> Tests regular class generic method used in arguments to method invocation.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections; using System.Collections.Generic; public class Test { public class InnerTest : IEnumerable<InnerTest> { public int Field; #region IEnumerable<InnerTest> Members public IEnumerator<InnerTest> GetEnumerator() { return new InnerTestEnumerator(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return new InnerTestEnumerator(); } #endregion } public class InnerTestEnumerator : IEnumerator<InnerTest>, IEnumerator { private InnerTest[] _list = new InnerTest[] { new InnerTest() { Field = 0 } , new InnerTest() { Field = 1 } , null } ; private int _index = -1; #region IEnumerator<InnerTest> Members public InnerTest Current { get { return _list[_index]; } } #endregion #region IDisposable Members public void Dispose() { // Empty. } #endregion #region IEnumerator Members object IEnumerator.Current { get { return _list[_index]; } } public bool MoveNext() { _index++; return _index >= _list.Length ? false : true; } public void Reset() { _index = -1; } #endregion } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); dynamic mc = new MemberClass(); int result = t.Method((int)mc.M<InnerTest>(new InnerTest())); return result == 3 ? 0 : 1; } public int Method(int value) { return value; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass010.regclass010 { // <Title> Tests regular class generic method used in implicitly-typed variable initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic mc = new MemberClass(); string u = string.Empty; string v = string.Empty; var result = (int)mc.Method_ReturnsT<int, string, string>(out u, ref v); if (result == 0 && u == null && v == string.Empty) return 0; else return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass011.regclass011 { // <Title> Tests regular class generic method used in implicitly-typed variable initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic mc = new MemberClass(); var tc = new { A1 = (int)mc.Method_ReturnsInt<int>(0), A2 = (string)mc.Method_ReturnsString<int, int>(1, 2) } ; if (tc != null && tc.A1 == 1 && tc.A2 == "foo") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass012.regclass012 { // <Title> Tests regular class generic method used in property-set body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private float _field; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); t.TestProperty = 1.1f; if (t.TestProperty == 3.4f) return 0; return 1; } public float TestProperty { set { dynamic mc = new MemberClass(); dynamic mv = value; _field = (float)mc.Method_ReturnsFloat<float, string, string>(value, mv, null); } get { return _field; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass013.regclass013 { // <Title> Tests regular class generic method used in constructor.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private float _filed; private decimal _dec; public Test() { dynamic mc = new MemberClass(); _filed = mc.Method_ReturnsFloat<string, long, int>(null, mc, 1L, ref _dec); } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (t._filed == 3.4f && t._dec == 3M) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass014.regclass014 { // <Title> Tests regular class generic method used in operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic mc = new MemberClass(); int result = (int)mc.Method_ReturnsDynamic<int>(7) % (int)mc.Method_ReturnsDynamic<int>(5); if ((int)mc.Method_ReturnsDynamic<int>(99) != 99) return 1; if (result == 2) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass015.regclass015 { // <Title> Tests regular class generic method used in null coalescing operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic mc = new MemberClass(); string result = (string)mc.Method_ReturnsDynamic<int, string>(10, null, mc) ?? string.Empty; if (result == string.Empty) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass016.regclass016 { // <Title> Tests regular class generic method used in query expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Linq; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var list = new List<string>() { null, "b", null, "a" } ; dynamic mc = new MemberClass(); string a = "a"; dynamic da = a; var result = list.Where(p => p == (string)mc.Method_ReturnsDynamic<string, int, string>(null, 10, a, da)).ToList(); if (result.Count == 1 && result[0] == "a") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass017.regclass017 { // <Title> Tests regular class generic method used in short-circuit boolean expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass.NestedMemberClass<string>(); int loopCount = 0; while ((int)dy.Method_ReturnsDynamic<int>(null, null, loopCount, dy) < 10) { loopCount++; } return loopCount - 10; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass018.regclass018 { // <Title> Tests regular class generic method used in destructor.</Title> // <Description> // On IA64 the GC.WaitForPendingFinalizers() does not actually work... // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Runtime.CompilerServices; public class Test { private static string s_field; public static object locker = new object(); ~Test() { lock (locker) { dynamic mc = new MemberClass.NestedMemberClass<Test>(); s_field = mc.Method_ReturnsDynamic<string>(null, null, "Test", mc); } } private static int Verify() { lock (Test.locker) { if (Test.s_field != "Test") { return 1; } } return 0; } [MethodImpl(MethodImplOptions.NoInlining)] private static void RequireLifetimesEnded() { Test t = new Test(); Test.s_field = "Field"; GC.KeepAlive(t); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { RequireLifetimesEnded(); GC.Collect(); GC.WaitForPendingFinalizers(); // If move the code in Verify() to here, the finalizer will only be executed after exited Main return Verify(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass019.regclass019 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); var result = (object)dy.Method_ReturnsUConstraint<Test>(new Test()); return result == null ? 0 : 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass020.regclass020 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private int _field; public Test() { _field = 10; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); var result = (Test)dy.Method_ReturnsUConstraint<int, Test>(4); if (result != null && result._field == 10) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass021.regclass021 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private int _field; public Test() { _field = 10; } public class InnerTest : Test { public InnerTest() { _field = 11; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); var result = (Test)dy.Method_ReturnsUConstraint<string, Test, InnerTest>(null, new InnerTest() { _field = 0 } ); if (result.GetType() == typeof(InnerTest) && result._field == 11) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass022.regclass022 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private int _field; public Test() { _field = 10; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); dynamic result = dy.Method_ReturnsDynamicConstraint<int, Test>(1, new Test() { _field = 0 } , dy); if (((Test)result)._field == 10) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass023.regclass023 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(12,9\).*CS0414</Expects> public class Test { private int _field; public Test() { _field = 10; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); dynamic s = "Test"; dynamic result = dy.Method_ReturnsDynamicConstraint<string, string, string>((string)s, (string)s, (string)s, s); if (((string)result) == "Test") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass024.regclass024 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(12,9\).*CS0414</Expects> public class Test { private int _field; public Test() { _field = 10; } public class InnerTest : Test { public InnerTest() { _field = 11; } } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); Test t = new Test(); dynamic it = new InnerTest(); decimal dec = 0M; float result = (float)dy.Method_ReturnsFloatConstraint<Test, Test, InnerTest>(t, it, t, ref dec); if (result == 3.4f && dec == 3M) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass025.regclass025 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); dynamic t = new Test(); try { dynamic result = dy.Method_ReturnsUNegConstraint<Test>(t); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.GenericConstraintNotSatisfiedRefType, e.Message, "MemberClass.Method_ReturnsUNegConstraint<U>(U)", "C", "U", "Test")) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass027.regclass027 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); MyTest mt = new MyTest(); dynamic d = mt; decimal dec = 0M; try { float result = (float)dy.Method_ReturnsFloatNegConstraint<Test, dynamic, DerivedMyTest>(null, d, d, ref dec); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (!ErrorVerifier.Verify(ErrorMessageId.GenericConstraintNotSatisfiedRefType, e.Message, "MemberClass.Method_ReturnsFloatNegConstraint<T,U,V>(T, object, U, ref decimal)", "I", "U", "object")) return 1; } return 0; } } public class MyTest : I { } public class DerivedMyTest : MyTest { } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass028.regclass028 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass.NestedMemberClass<string>(); string result = (string)dy.Method_ReturnsU("0"); if (result == null) return 0; return 1; } } //</Code> }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclassgenmeth.regclassgenmeth; using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclassgenmeth.regclassgenmeth { using System.Collections.Generic; public class C { } public interface I { } public class MemberClass { #region Instance methods public T Method_ReturnsT<T>() { return default(T); } public T Method_ReturnsT<T>(T t) { return t; } public T Method_ReturnsT<T, U>(out T t) { t = default(T); return t; } public T Method_ReturnsT<T>(ref T t) { t = default(T); return t; } public T Method_ReturnsT<T>(params T[] t) { return default(T); } public int M<T>(T t) where T : IEnumerable<T> { return 3; } public T Method_ReturnsT<T, U>(params U[] d) { return default(T); } public T Method_ReturnsT<T, U>(float x, T t, U u) { return default(T); } public T Method_ReturnsT<T, U>(U u) { return default(T); } public T Method_ReturnsT<T, U, V>(out U u, ref V v) { u = default(U); return default(T); } public int Method_ReturnsInt<T>(T t) { return 1; } public string Method_ReturnsString<T, U>(T t, U u) { return "foo"; } public float Method_ReturnsFloat<T, U, V>(T t, dynamic d, U u) { return 3.4f; } public float Method_ReturnsFloat<T, U, V>(T t, dynamic d, U u, ref decimal dec) { dec = 3m; return 3.4f; } public dynamic Method_ReturnsDynamic<T>(T t) { return t; } public dynamic Method_ReturnsDynamic<T, U>(T t, U u, dynamic d) { return u; } public dynamic Method_ReturnsDynamic<T, U, V>(T t, U u, V v, dynamic d) { return v; } #region Constraints on methods that have a new type parameter public U Method_ReturnsUConstraint<U>(U u) where U : class { return null; } public U Method_ReturnsUConstraint<T, U>(T t) where U : new() { return new U(); } public U Method_ReturnsUConstraint<T, U, V>(T t, V v) where U : new() where V : U, new() { return new V(); } public dynamic Method_ReturnsDynamicConstraint<T, U>(T t, U u, dynamic d) where U : new() { return new U(); } public dynamic Method_ReturnsDynamicConstraint<T, U, V>(T t, U u, V v, dynamic d) where V : class { return u; } public float Method_ReturnsFloatConstraint<T, U, V>(T t, dynamic d, U u, ref decimal dec) where V : U { dec = 3m; return 3.4f; } public string Method_ReturnsStringConstraint<T, U, V>(T t, dynamic d, U u) where U : class where V : U { return ""; } //These are negative methods... you should not be able to call them with the dynamic type because the dynamic type would not satisfy the constraints //you cannot call this like: Method_ReturnsUConstraint<dynamic>(d); because object does not derive from C public U Method_ReturnsUNegConstraint<U>(U u) where U : C { return null; } public T Method_ReturnsTNegConstraint<T, U>(U u) where U : struct { return default(T); } public float Method_ReturnsFloatNegConstraint<T, U, V>(T t, dynamic d, U u, ref decimal dec) where V : U where U : I { dec = 3m; return 3.4f; } #endregion #region Nested class public class NestedMemberClass<U> { public U Method_ReturnsU(U t) { return default(U); } public U Method_ReturnsT(params U[] d) { return default(U); } public U Method_ReturnsT<V>(out U u, ref V v) { u = default(U); return default(U); } public dynamic Method_ReturnsDynamic(U t, U u, dynamic d) { return u; } public dynamic Method_ReturnsDynamic<V>(U t, U u, V v, dynamic d) { return v; } public decimal Method_ReturnsDecimal<V>(U t, dynamic d, U u) { return 3.4m; } public byte Method_ReturnsByte<V>(U t, dynamic d, U u, ref double dec) { dec = 3; return 4; } } #endregion #endregion } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass001.regclass001 { // <Title> Tests regular class generic method used in regular method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (t.TestMethod()) return 1; return 0; } public bool TestMethod() { dynamic mc = new MemberClass(); return (bool)mc.Method_ReturnsT<bool>(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass002.regclass002 { // <Title> Tests regular class generic method used in variable initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private static dynamic s_mc = new MemberClass(); private int _loc = (int)s_mc.Method_ReturnsT<int, string>(string.Empty, null, "abc"); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (t._loc != 0) return 1; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass003.regclass003 { // <Title> Tests regular class generic method used in indexer body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class Test { private Dictionary<int, string> _dic = new Dictionary<int, string>(); private MemberClass _mc = new MemberClass(); [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { if (TestSet() == 0 && TestGet() == 0) return 0; else return 1; } private static int TestSet() { Test t = new Test(); t[0] = "Test0"; t[1] = null; t[2] = "Test2"; if (t._dic[0] == "Test0" && t._dic[1] == null && t._dic[2] == "Test2") return 0; else return 1; } private static int TestGet() { Test t = new Test(); t._dic[2] = "Test0"; t._dic[1] = null; t._dic[0] = "Test2"; if (t[2] == "Test0" && t[1] == null && t[0] == "Test2") return 0; else return 1; } public string this[int i] { set { dynamic dy = _mc; _dic.Add((int)dy.Method_ReturnsT(i), value); } get { dynamic dy = _mc; return _dic[(int)dy.Method_ReturnsT(i)]; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass004.regclass004 { // <Title> Tests regular class generic method used in static constructor.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private static int s_field = 10; private static int s_result = -1; public Test() { dynamic dy = new MemberClass(); string s = "Foo"; Test.s_result = dy.Method_ReturnsT<int, int, string>(out s_field, ref s); } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (Test.s_field == 0 && Test.s_result == 0) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass005.regclass005 { // <Title> Tests regular class generic method used in variable named dynamic.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int i = 1; dynamic dynamic = new MemberClass(); int result = dynamic.Method_ReturnsT<int>(ref i); if (i == 0 && result == 0) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass006.regclass006 { public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t1 = new Test(); return t1.TestMethod<long>(1L) == 0 ? 0 : 1; } public T TestMethod<T>(T t) { dynamic dy = new MemberClass(); return (T)dy.Method_ReturnsT<T>(t, t, t); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass008.regclass008 { // <Title> Tests regular class generic method used in method body of method with conditional attribute.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private static int s_result = 0; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t1 = new Test(); t1.TestMethod(); return s_result; } [System.Diagnostics.Conditional("c1")] public void TestMethod() { dynamic dy = new MemberClass(); s_result = (int)dy.Method_ReturnsT<int, string>(null) + 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass009.regclass009 { // <Title> Tests regular class generic method used in arguments to method invocation.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections; using System.Collections.Generic; public class Test { public class InnerTest : IEnumerable<InnerTest> { public int Field; #region IEnumerable<InnerTest> Members public IEnumerator<InnerTest> GetEnumerator() { return new InnerTestEnumerator(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return new InnerTestEnumerator(); } #endregion } public class InnerTestEnumerator : IEnumerator<InnerTest>, IEnumerator { private InnerTest[] _list = new InnerTest[] { new InnerTest() { Field = 0 } , new InnerTest() { Field = 1 } , null } ; private int _index = -1; #region IEnumerator<InnerTest> Members public InnerTest Current { get { return _list[_index]; } } #endregion #region IDisposable Members public void Dispose() { // Empty. } #endregion #region IEnumerator Members object IEnumerator.Current { get { return _list[_index]; } } public bool MoveNext() { _index++; return _index >= _list.Length ? false : true; } public void Reset() { _index = -1; } #endregion } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); dynamic mc = new MemberClass(); int result = t.Method((int)mc.M<InnerTest>(new InnerTest())); return result == 3 ? 0 : 1; } public int Method(int value) { return value; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass010.regclass010 { // <Title> Tests regular class generic method used in implicitly-typed variable initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic mc = new MemberClass(); string u = string.Empty; string v = string.Empty; var result = (int)mc.Method_ReturnsT<int, string, string>(out u, ref v); if (result == 0 && u == null && v == string.Empty) return 0; else return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass011.regclass011 { // <Title> Tests regular class generic method used in implicitly-typed variable initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic mc = new MemberClass(); var tc = new { A1 = (int)mc.Method_ReturnsInt<int>(0), A2 = (string)mc.Method_ReturnsString<int, int>(1, 2) } ; if (tc != null && tc.A1 == 1 && tc.A2 == "foo") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass012.regclass012 { // <Title> Tests regular class generic method used in property-set body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private float _field; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); t.TestProperty = 1.1f; if (t.TestProperty == 3.4f) return 0; return 1; } public float TestProperty { set { dynamic mc = new MemberClass(); dynamic mv = value; _field = (float)mc.Method_ReturnsFloat<float, string, string>(value, mv, null); } get { return _field; } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass013.regclass013 { // <Title> Tests regular class generic method used in constructor.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private float _filed; private decimal _dec; public Test() { dynamic mc = new MemberClass(); _filed = mc.Method_ReturnsFloat<string, long, int>(null, mc, 1L, ref _dec); } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (t._filed == 3.4f && t._dec == 3M) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass014.regclass014 { // <Title> Tests regular class generic method used in operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic mc = new MemberClass(); int result = (int)mc.Method_ReturnsDynamic<int>(7) % (int)mc.Method_ReturnsDynamic<int>(5); if ((int)mc.Method_ReturnsDynamic<int>(99) != 99) return 1; if (result == 2) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass015.regclass015 { // <Title> Tests regular class generic method used in null coalescing operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic mc = new MemberClass(); string result = (string)mc.Method_ReturnsDynamic<int, string>(10, null, mc) ?? string.Empty; if (result == string.Empty) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass016.regclass016 { // <Title> Tests regular class generic method used in query expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Linq; using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var list = new List<string>() { null, "b", null, "a" } ; dynamic mc = new MemberClass(); string a = "a"; dynamic da = a; var result = list.Where(p => p == (string)mc.Method_ReturnsDynamic<string, int, string>(null, 10, a, da)).ToList(); if (result.Count == 1 && result[0] == "a") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass017.regclass017 { // <Title> Tests regular class generic method used in short-circuit boolean expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass.NestedMemberClass<string>(); int loopCount = 0; while ((int)dy.Method_ReturnsDynamic<int>(null, null, loopCount, dy) < 10) { loopCount++; } return loopCount - 10; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass018.regclass018 { // <Title> Tests regular class generic method used in destructor.</Title> // <Description> // On IA64 the GC.WaitForPendingFinalizers() does not actually work... // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Runtime.CompilerServices; public class Test { private static string s_field; public static object locker = new object(); ~Test() { lock (locker) { dynamic mc = new MemberClass.NestedMemberClass<Test>(); s_field = mc.Method_ReturnsDynamic<string>(null, null, "Test", mc); } } private static int Verify() { lock (Test.locker) { if (Test.s_field != "Test") { return 1; } } return 0; } [MethodImpl(MethodImplOptions.NoInlining)] private static void RequireLifetimesEnded() { Test t = new Test(); Test.s_field = "Field"; GC.KeepAlive(t); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { RequireLifetimesEnded(); GC.Collect(); GC.WaitForPendingFinalizers(); // If move the code in Verify() to here, the finalizer will only be executed after exited Main return Verify(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass019.regclass019 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); var result = (object)dy.Method_ReturnsUConstraint<Test>(new Test()); return result == null ? 0 : 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass020.regclass020 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private int _field; public Test() { _field = 10; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); var result = (Test)dy.Method_ReturnsUConstraint<int, Test>(4); if (result != null && result._field == 10) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass021.regclass021 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private int _field; public Test() { _field = 10; } public class InnerTest : Test { public InnerTest() { _field = 11; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); var result = (Test)dy.Method_ReturnsUConstraint<string, Test, InnerTest>(null, new InnerTest() { _field = 0 } ); if (result.GetType() == typeof(InnerTest) && result._field == 11) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass022.regclass022 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private int _field; public Test() { _field = 10; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); dynamic result = dy.Method_ReturnsDynamicConstraint<int, Test>(1, new Test() { _field = 0 } , dy); if (((Test)result)._field == 10) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass023.regclass023 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(12,9\).*CS0414</Expects> public class Test { private int _field; public Test() { _field = 10; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); dynamic s = "Test"; dynamic result = dy.Method_ReturnsDynamicConstraint<string, string, string>((string)s, (string)s, (string)s, s); if (((string)result) == "Test") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass024.regclass024 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(12,9\).*CS0414</Expects> public class Test { private int _field; public Test() { _field = 10; } public class InnerTest : Test { public InnerTest() { _field = 11; } } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); Test t = new Test(); dynamic it = new InnerTest(); decimal dec = 0M; float result = (float)dy.Method_ReturnsFloatConstraint<Test, Test, InnerTest>(t, it, t, ref dec); if (result == 3.4f && dec == 3M) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass025.regclass025 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); dynamic t = new Test(); try { dynamic result = dy.Method_ReturnsUNegConstraint<Test>(t); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.GenericConstraintNotSatisfiedRefType, e.Message, "MemberClass.Method_ReturnsUNegConstraint<U>(U)", "C", "U", "Test")) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass027.regclass027 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); MyTest mt = new MyTest(); dynamic d = mt; decimal dec = 0M; try { float result = (float)dy.Method_ReturnsFloatNegConstraint<Test, dynamic, DerivedMyTest>(null, d, d, ref dec); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (!ErrorVerifier.Verify(ErrorMessageId.GenericConstraintNotSatisfiedRefType, e.Message, "MemberClass.Method_ReturnsFloatNegConstraint<T,U,V>(T, object, U, ref decimal)", "I", "U", "object")) return 1; } return 0; } } public class MyTest : I { } public class DerivedMyTest : MyTest { } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.genmethod.regclass.regclass028.regclass028 { // <Title> Tests regular class generic method used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass.NestedMemberClass<string>(); string result = (string)dy.Method_ReturnsU("0"); if (result == null) return 0; return 1; } } //</Code> }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Map.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; namespace System.Runtime.InteropServices.JavaScript { /// <summary> /// The Map object holds key-value pairs and remembers the original insertion order of the keys. /// Any value (both objects and primitive values) may be used as either a key or a value. /// </summary> public class Map : CoreObject, IDictionary { /// <summary> /// Initializes a new instance of the Map class. /// </summary> public Map() : base(nameof(Map)) { } /// <summary> /// Initializes a new instance of the Map class. /// </summary> /// <param name="jsHandle">Js handle.</param> internal Map(IntPtr jsHandle) : base(jsHandle) { } /// <summary> /// Gets a value indicating whether the Map object has a fixed size. /// </summary> public bool IsFixedSize => false; /// <summary> /// Gets a value indicating whether the Map object is read-only. /// </summary> public bool IsReadOnly => false; /// <summary> /// Gets an System.Collections.ICollection object containing the keys of the Map object. /// </summary> public ICollection Keys => new MapItemCollection(this, "keys"); /// <summary> /// Gets an System.Collections.ICollection object containing the values of the Map object. /// </summary> public ICollection Values => new MapItemCollection(this, "values"); public int Count => (int)GetObjectProperty("size"); public bool IsSynchronized => false; public object SyncRoot => false; public void Add(object key, object? value) => Invoke("set", key, value); public void Clear() => Invoke("clear"); public bool Contains(object key) => (bool)Invoke("has", key); public IDictionaryEnumerator GetEnumerator() => new MapEnumerator(this); public void Remove(object key) => Invoke("delete", key); public void CopyTo(System.Array array, int index) => throw new NotImplementedException(); // Construct and return an enumerator. IEnumerator IEnumerable.GetEnumerator() => new MapEnumerator(this); /// <summary> /// Gets or sets the Map with the key specified by <paramref name="key" />. /// </summary> /// <param name="key">The key.</param> public object? this[object key] { get { return Invoke("get", key); } set { Invoke("set", key, value); } } private sealed class MapEnumerator : IDictionaryEnumerator, IDisposable { private JSObject? _mapIterator; private readonly Map _map; public MapEnumerator(Map map) { _map = map; } // Return the current item. public object Current => new DictionaryEntry(Key, Value); // Return the current dictionary entry. public DictionaryEntry Entry => (DictionaryEntry)Current; // Return the key of the current item. public object Key { get; private set; } = new object(); // Return the value of the current item. public object? Value { get; private set; } // Advance to the next item. public bool MoveNext() { if (_mapIterator == null) _mapIterator = (JSObject)_map.Invoke("entries"); using (var result = (JSObject)_mapIterator.Invoke("next")) { using (var resultValue = (Array)result.GetObjectProperty("value")) { if (resultValue != null) { Key = resultValue[0]; Value = resultValue[1]; } else { Value = null; } } return !(bool)result.GetObjectProperty("done"); } } // Reset the index to restart the enumeration. public void Reset() { _mapIterator?.Dispose(); _mapIterator = null; } #region IDisposable Support private bool _disposedValue; // To detect redundant calls private void Dispose(bool disposing) { if (!_disposedValue) { _mapIterator?.Dispose(); _mapIterator = null; _disposedValue = true; } } ~MapEnumerator() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } /// <summary> /// Class that implements an ICollection over the "keys" or "values" /// </summary> private sealed class MapItemCollection : ICollection { private readonly Map _map; private readonly string _iterator; // "keys" or "values" public MapItemCollection(Map map, string iterator) { _map = map; _iterator = iterator; } public int Count => _map.Count; public bool IsSynchronized => false; public object SyncRoot => this; public void CopyTo(System.Array array, int index) => throw new NotImplementedException(); // Construct and return an enumerator. public IEnumerator GetEnumerator() => new MapItemEnumerator(this); /// <summary> /// The custom enumerator used by MapItemCollection /// </summary> private sealed class MapItemEnumerator : IEnumerator { private readonly MapItemCollection _mapItemCollection; private JSObject? _mapItemIterator; public object? Current { get; private set; } public MapItemEnumerator(MapItemCollection mapCollection) { _mapItemCollection = mapCollection; } public bool MoveNext() { if (_mapItemIterator == null) _mapItemIterator = (JSObject)_mapItemCollection._map.Invoke(_mapItemCollection._iterator); using (var result = (JSObject)_mapItemIterator.Invoke("next")) { bool done = (bool)result.GetObjectProperty("done"); if (!done) Current = result.GetObjectProperty("value"); return !done; } } public void Reset() { _mapItemIterator?.Dispose(); _mapItemIterator = null; } #region IDisposable Support private bool _disposedValue; // To detect redundant calls private void Dispose(bool disposing) { if (!_disposedValue) { _mapItemIterator?.Dispose(); _mapItemIterator = null; _disposedValue = true; } } ~MapItemEnumerator() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(false); } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. GC.SuppressFinalize(this); } #endregion } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; namespace System.Runtime.InteropServices.JavaScript { /// <summary> /// The Map object holds key-value pairs and remembers the original insertion order of the keys. /// Any value (both objects and primitive values) may be used as either a key or a value. /// </summary> public class Map : CoreObject, IDictionary { /// <summary> /// Initializes a new instance of the Map class. /// </summary> public Map() : base(nameof(Map)) { } /// <summary> /// Initializes a new instance of the Map class. /// </summary> /// <param name="jsHandle">Js handle.</param> internal Map(IntPtr jsHandle) : base(jsHandle) { } /// <summary> /// Gets a value indicating whether the Map object has a fixed size. /// </summary> public bool IsFixedSize => false; /// <summary> /// Gets a value indicating whether the Map object is read-only. /// </summary> public bool IsReadOnly => false; /// <summary> /// Gets an System.Collections.ICollection object containing the keys of the Map object. /// </summary> public ICollection Keys => new MapItemCollection(this, "keys"); /// <summary> /// Gets an System.Collections.ICollection object containing the values of the Map object. /// </summary> public ICollection Values => new MapItemCollection(this, "values"); public int Count => (int)GetObjectProperty("size"); public bool IsSynchronized => false; public object SyncRoot => false; public void Add(object key, object? value) => Invoke("set", key, value); public void Clear() => Invoke("clear"); public bool Contains(object key) => (bool)Invoke("has", key); public IDictionaryEnumerator GetEnumerator() => new MapEnumerator(this); public void Remove(object key) => Invoke("delete", key); public void CopyTo(System.Array array, int index) => throw new NotImplementedException(); // Construct and return an enumerator. IEnumerator IEnumerable.GetEnumerator() => new MapEnumerator(this); /// <summary> /// Gets or sets the Map with the key specified by <paramref name="key" />. /// </summary> /// <param name="key">The key.</param> public object? this[object key] { get { return Invoke("get", key); } set { Invoke("set", key, value); } } private sealed class MapEnumerator : IDictionaryEnumerator, IDisposable { private JSObject? _mapIterator; private readonly Map _map; public MapEnumerator(Map map) { _map = map; } // Return the current item. public object Current => new DictionaryEntry(Key, Value); // Return the current dictionary entry. public DictionaryEntry Entry => (DictionaryEntry)Current; // Return the key of the current item. public object Key { get; private set; } = new object(); // Return the value of the current item. public object? Value { get; private set; } // Advance to the next item. public bool MoveNext() { if (_mapIterator == null) _mapIterator = (JSObject)_map.Invoke("entries"); using (var result = (JSObject)_mapIterator.Invoke("next")) { using (var resultValue = (Array)result.GetObjectProperty("value")) { if (resultValue != null) { Key = resultValue[0]; Value = resultValue[1]; } else { Value = null; } } return !(bool)result.GetObjectProperty("done"); } } // Reset the index to restart the enumeration. public void Reset() { _mapIterator?.Dispose(); _mapIterator = null; } #region IDisposable Support private bool _disposedValue; // To detect redundant calls private void Dispose(bool disposing) { if (!_disposedValue) { _mapIterator?.Dispose(); _mapIterator = null; _disposedValue = true; } } ~MapEnumerator() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } /// <summary> /// Class that implements an ICollection over the "keys" or "values" /// </summary> private sealed class MapItemCollection : ICollection { private readonly Map _map; private readonly string _iterator; // "keys" or "values" public MapItemCollection(Map map, string iterator) { _map = map; _iterator = iterator; } public int Count => _map.Count; public bool IsSynchronized => false; public object SyncRoot => this; public void CopyTo(System.Array array, int index) => throw new NotImplementedException(); // Construct and return an enumerator. public IEnumerator GetEnumerator() => new MapItemEnumerator(this); /// <summary> /// The custom enumerator used by MapItemCollection /// </summary> private sealed class MapItemEnumerator : IEnumerator { private readonly MapItemCollection _mapItemCollection; private JSObject? _mapItemIterator; public object? Current { get; private set; } public MapItemEnumerator(MapItemCollection mapCollection) { _mapItemCollection = mapCollection; } public bool MoveNext() { if (_mapItemIterator == null) _mapItemIterator = (JSObject)_mapItemCollection._map.Invoke(_mapItemCollection._iterator); using (var result = (JSObject)_mapItemIterator.Invoke("next")) { bool done = (bool)result.GetObjectProperty("done"); if (!done) Current = result.GetObjectProperty("value"); return !done; } } public void Reset() { _mapItemIterator?.Dispose(); _mapItemIterator = null; } #region IDisposable Support private bool _disposedValue; // To detect redundant calls private void Dispose(bool disposing) { if (!_disposedValue) { _mapItemIterator?.Dispose(); _mapItemIterator = null; _disposedValue = true; } } ~MapItemEnumerator() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(false); } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. GC.SuppressFinalize(this); } #endregion } } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/JIT/Methodical/int64/signed/s_ldc_div_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="s_ldc_div.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="s_ldc_div.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/Marshal/ReleaseComObjectTests.Windows.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices.Tests.Common; using Xunit; namespace System.Runtime.InteropServices.Tests { public partial class ReleaseComObjectTests { [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] public void ReleaseComObject_ValidComObject_Success() { var comObject = new ComImportObject(); Assert.Equal(0, Marshal.ReleaseComObject(comObject)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices.Tests.Common; using Xunit; namespace System.Runtime.InteropServices.Tests { public partial class ReleaseComObjectTests { [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] public void ReleaseComObject_ValidComObject_Success() { var comObject = new ComImportObject(); Assert.Equal(0, Marshal.ReleaseComObject(comObject)); } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/JIT/Methodical/doublearray/dblarray4_cs_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> <GCStressIncompatible>true</GCStressIncompatible> </PropertyGroup> <ItemGroup> <Compile Include="dblarray4.cs" /> </ItemGroup> <PropertyGroup> <CLRTestBatchPreCommands><![CDATA[ $(CLRTestBatchPreCommands) set COMPlus_DoubleArrayToLargeObjectHeap=0x64 ]]></CLRTestBatchPreCommands> <BashCLRTestPreCommands><![CDATA[ $(BashCLRTestPreCommands) export COMPlus_DoubleArrayToLargeObjectHeap=0x64 ]]></BashCLRTestPreCommands> </PropertyGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> <GCStressIncompatible>true</GCStressIncompatible> </PropertyGroup> <ItemGroup> <Compile Include="dblarray4.cs" /> </ItemGroup> <PropertyGroup> <CLRTestBatchPreCommands><![CDATA[ $(CLRTestBatchPreCommands) set COMPlus_DoubleArrayToLargeObjectHeap=0x64 ]]></CLRTestBatchPreCommands> <BashCLRTestPreCommands><![CDATA[ $(BashCLRTestPreCommands) export COMPlus_DoubleArrayToLargeObjectHeap=0x64 ]]></BashCLRTestPreCommands> </PropertyGroup> </Project>
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/ShiftRightArithmeticRoundedNarrowingSaturateScalar.Vector64.Int16.32.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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32() { var test = new ImmUnaryOpTest__ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32(); 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 ImmUnaryOpTest__ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray, Int16[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<Int32, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.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> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32 testClass) { var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar(_fld, 16); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32 testClass) { fixed (Vector64<Int32>* pFld = &_fld) { var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((Int32*)(pFld)), 16 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly byte Imm = 16; private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector64<Int32> _clsVar; private Vector64<Int32> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public ImmUnaryOpTest__ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data, 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.ShiftRightArithmeticRoundedNarrowingSaturateScalar( Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar), new Type[] { typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar), new Type[] { typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar( _clsVar, 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar = &_clsVar) { var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((Int32*)(pClsVar)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr); var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar(firstOp, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)); var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar(firstOp, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32(); var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar(test._fld, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32(); fixed (Vector64<Int32>* pFld = &test._fld) { var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((Int32*)(pFld)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar(_fld, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld = &_fld) { var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((Int32*)(pFld)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar(test._fld, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((Int32*)(&test._fld)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _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> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Helpers.ShiftRightArithmeticRoundedNarrowingSaturate(firstOp[0], Imm) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar)}<Int16>(Vector64<Int32>, 16): {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\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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32() { var test = new ImmUnaryOpTest__ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32(); 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 ImmUnaryOpTest__ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray, Int16[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<Int32, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.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> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32 testClass) { var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar(_fld, 16); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32 testClass) { fixed (Vector64<Int32>* pFld = &_fld) { var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((Int32*)(pFld)), 16 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly byte Imm = 16; private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector64<Int32> _clsVar; private Vector64<Int32> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public ImmUnaryOpTest__ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data, 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.ShiftRightArithmeticRoundedNarrowingSaturateScalar( Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar), new Type[] { typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar), new Type[] { typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar( _clsVar, 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar = &_clsVar) { var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((Int32*)(pClsVar)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr); var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar(firstOp, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)); var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar(firstOp, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32(); var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar(test._fld, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftRightArithmeticRoundedNarrowingSaturateScalar_Vector64_Int16_32(); fixed (Vector64<Int32>* pFld = &test._fld) { var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((Int32*)(pFld)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar(_fld, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld = &_fld) { var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((Int32*)(pFld)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar(test._fld, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((Int32*)(&test._fld)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _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> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Helpers.ShiftRightArithmeticRoundedNarrowingSaturate(firstOp[0], Imm) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ShiftRightArithmeticRoundedNarrowingSaturateScalar)}<Int16>(Vector64<Int32>, 16): {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,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/DSPropertyCollection.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.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.DirectoryServices; using System.Text; using System.Net; using System.Collections; namespace System.DirectoryServices.AccountManagement { internal sealed class dSPropertyCollection { private readonly PropertyCollection _pc; private readonly ResultPropertyCollection _rp; private dSPropertyCollection() { } internal dSPropertyCollection(PropertyCollection pc) { _pc = pc; } internal dSPropertyCollection(ResultPropertyCollection rp) { _rp = rp; } public dSPropertyValueCollection this[string propertyName] { get { if (propertyName == null) throw new ArgumentNullException(nameof(propertyName)); if (null != _pc) { return new dSPropertyValueCollection(_pc[propertyName]); } else { return new dSPropertyValueCollection(_rp[propertyName]); } } } } internal sealed class dSPropertyValueCollection { private readonly PropertyValueCollection _pc; private readonly ResultPropertyValueCollection _rc; private dSPropertyValueCollection() { } internal dSPropertyValueCollection(PropertyValueCollection pc) { _pc = pc; } internal dSPropertyValueCollection(ResultPropertyValueCollection rc) { _rc = rc; } public object this[int index] { get { if (_pc != null) { return _pc[index]; } else { return _rc[index]; } } } public int Count { get { return (_pc != null ? _pc.Count : _rc.Count); } } public IEnumerator GetEnumerator() { return (_pc != null ? _pc.GetEnumerator() : _rc.GetEnumerator()); } } }
// 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.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.DirectoryServices; using System.Text; using System.Net; using System.Collections; namespace System.DirectoryServices.AccountManagement { internal sealed class dSPropertyCollection { private readonly PropertyCollection _pc; private readonly ResultPropertyCollection _rp; private dSPropertyCollection() { } internal dSPropertyCollection(PropertyCollection pc) { _pc = pc; } internal dSPropertyCollection(ResultPropertyCollection rp) { _rp = rp; } public dSPropertyValueCollection this[string propertyName] { get { if (propertyName == null) throw new ArgumentNullException(nameof(propertyName)); if (null != _pc) { return new dSPropertyValueCollection(_pc[propertyName]); } else { return new dSPropertyValueCollection(_rp[propertyName]); } } } } internal sealed class dSPropertyValueCollection { private readonly PropertyValueCollection _pc; private readonly ResultPropertyValueCollection _rc; private dSPropertyValueCollection() { } internal dSPropertyValueCollection(PropertyValueCollection pc) { _pc = pc; } internal dSPropertyValueCollection(ResultPropertyValueCollection rc) { _rc = rc; } public object this[int index] { get { if (_pc != null) { return _pc[index]; } else { return _rc[index]; } } } public int Count { get { return (_pc != null ? _pc.Count : _rc.Count); } } public IEnumerator GetEnumerator() { return (_pc != null ? _pc.GetEnumerator() : _rc.GetEnumerator()); } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/coreclr/pal/tests/palsuite/c_runtime/errno/test1/test1.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================================ ** ** Source: test1.c ** ** Purpose: Test that errno begins as 0, and sets to ERANGE when that ** error is forced with wcstoul. ** ** **==========================================================================*/ #include <palsuite.h> PALTEST(c_runtime_errno_test1_paltest_errno_test1, "c_runtime/errno/test1/paltest_errno_test1") { WCHAR overstr[] = {'4','2','9','4','9','6','7','2','9','6',0}; WCHAR *end; if (PAL_Initialize(argc, argv)) { return FAIL; } /* The only value that must be supported is ERANGE, in the event that wcstoul() fails due to overflow. */ wcstoul(overstr, &end, 10); if (errno != ERANGE) { Fail("ERROR: wcstoul did not set errno to ERANGE. Instead " "the value of errno is %d\n", errno); } PAL_Terminate(); return PASS; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================================ ** ** Source: test1.c ** ** Purpose: Test that errno begins as 0, and sets to ERANGE when that ** error is forced with wcstoul. ** ** **==========================================================================*/ #include <palsuite.h> PALTEST(c_runtime_errno_test1_paltest_errno_test1, "c_runtime/errno/test1/paltest_errno_test1") { WCHAR overstr[] = {'4','2','9','4','9','6','7','2','9','6',0}; WCHAR *end; if (PAL_Initialize(argc, argv)) { return FAIL; } /* The only value that must be supported is ERANGE, in the event that wcstoul() fails due to overflow. */ wcstoul(overstr, &end, 10); if (errno != ERANGE) { Fail("ERROR: wcstoul did not set errno to ERANGE. Instead " "the value of errno is %d\n", errno); } PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/native/public/mono/metadata/details/environment-functions.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // This file does not have ifdef guards, it is meant to be included multiple times with different definitions of MONO_API_FUNCTION #ifndef MONO_API_FUNCTION #error "MONO_API_FUNCTION(ret,name,args) macro not defined before including function declaration header" #endif MONO_API_FUNCTION(int32_t, mono_environment_exitcode_get, (void)) MONO_API_FUNCTION(void, mono_environment_exitcode_set, (int32_t value))
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // This file does not have ifdef guards, it is meant to be included multiple times with different definitions of MONO_API_FUNCTION #ifndef MONO_API_FUNCTION #error "MONO_API_FUNCTION(ret,name,args) macro not defined before including function declaration header" #endif MONO_API_FUNCTION(int32_t, mono_environment_exitcode_get, (void)) MONO_API_FUNCTION(void, mono_environment_exitcode_set, (int32_t value))
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Threading.Tasks { // Task type used to implement: Task ContinueWith(Action<Task,...>) internal sealed class ContinuationTaskFromTask : Task { private Task? m_antecedent; public ContinuationTaskFromTask( Task antecedent, Delegate action, object? state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null) { Debug.Assert(action is Action<Task> || action is Action<Task, object?>, "Invalid delegate type in ContinuationTaskFromTask"); m_antecedent = antecedent; } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. Task? antecedent = m_antecedent; Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Debug.Assert(m_action != null); if (m_action is Action<Task> action) { action(antecedent); return; } if (m_action is Action<Task, object?> actionWithState) { actionWithState(antecedent, m_stateObject); return; } Debug.Fail("Invalid m_action in ContinuationTaskFromTask"); } } // Task type used to implement: Task<TResult> ContinueWith(Func<Task,...>) internal sealed class ContinuationResultTaskFromTask<TResult> : Task<TResult> { private Task? m_antecedent; public ContinuationResultTaskFromTask( Task antecedent, Delegate function, object? state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(function, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null) { Debug.Assert(function is Func<Task, TResult> || function is Func<Task, object?, TResult>, "Invalid delegate type in ContinuationResultTaskFromTask"); m_antecedent = antecedent; } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. Task? antecedent = m_antecedent; Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationResultTaskFromTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Debug.Assert(m_action != null); if (m_action is Func<Task, TResult> func) { m_result = func(antecedent); return; } if (m_action is Func<Task, object?, TResult> funcWithState) { m_result = funcWithState(antecedent, m_stateObject); return; } Debug.Fail("Invalid m_action in ContinuationResultTaskFromTask"); } } // Task type used to implement: Task ContinueWith(Action<Task<TAntecedentResult>,...>) internal sealed class ContinuationTaskFromResultTask<TAntecedentResult> : Task { private Task<TAntecedentResult>? m_antecedent; public ContinuationTaskFromResultTask( Task<TAntecedentResult> antecedent, Delegate action, object? state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null) { Debug.Assert(action is Action<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object?>, "Invalid delegate type in ContinuationTaskFromResultTask"); m_antecedent = antecedent; } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. Task<TAntecedentResult>? antecedent = m_antecedent; Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromResultTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Debug.Assert(m_action != null); if (m_action is Action<Task<TAntecedentResult>> action) { action(antecedent); return; } if (m_action is Action<Task<TAntecedentResult>, object?> actionWithState) { actionWithState(antecedent, m_stateObject); return; } Debug.Fail("Invalid m_action in ContinuationTaskFromResultTask"); } } // Task type used to implement: Task<TResult> ContinueWith(Func<Task<TAntecedentResult>,...>) internal sealed class ContinuationResultTaskFromResultTask<TAntecedentResult, TResult> : Task<TResult> { private Task<TAntecedentResult>? m_antecedent; public ContinuationResultTaskFromResultTask( Task<TAntecedentResult> antecedent, Delegate function, object? state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(function, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null) { Debug.Assert(function is Func<Task<TAntecedentResult>, TResult> || function is Func<Task<TAntecedentResult>, object?, TResult>, "Invalid delegate type in ContinuationResultTaskFromResultTask"); m_antecedent = antecedent; } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. Task<TAntecedentResult>? antecedent = m_antecedent; Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationResultTaskFromResultTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Debug.Assert(m_action != null); if (m_action is Func<Task<TAntecedentResult>, TResult> func) { m_result = func(antecedent); return; } if (m_action is Func<Task<TAntecedentResult>, object?, TResult> funcWithState) { m_result = funcWithState(antecedent, m_stateObject); return; } Debug.Fail("Invalid m_action in ContinuationResultTaskFromResultTask"); } } // For performance reasons, we don't just have a single way of representing // a continuation object. Rather, we have a hierarchy of types: // - TaskContinuation: abstract base that provides a virtual Run method // - StandardTaskContinuation: wraps a task,options,and scheduler, and overrides Run to process the task with that configuration // - AwaitTaskContinuation: base for continuations created through TaskAwaiter; targets default scheduler by default // - TaskSchedulerAwaitTaskContinuation: awaiting with a non-default TaskScheduler // - SynchronizationContextAwaitTaskContinuation: awaiting with a "current" sync ctx /// <summary>Represents a continuation.</summary> internal abstract class TaskContinuation { /// <summary>Inlines or schedules the continuation.</summary> /// <param name="completedTask">The antecedent task that has completed.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal abstract void Run(Task completedTask, bool canInlineContinuationTask); /// <summary>Tries to run the task on the current thread, if possible; otherwise, schedules it.</summary> /// <param name="task">The task to run</param> /// <param name="needsProtection"> /// true if we need to protect against multiple threads racing to start/cancel the task; otherwise, false. /// </param> protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection) { Debug.Assert(task != null); Debug.Assert(task.m_taskScheduler != null); // Set the TaskStateFlags.Started flag. This only needs to be done // if the task may be canceled or if someone else has a reference to it // that may try to execute it. if (needsProtection) { if (!task.MarkStarted()) return; // task has been previously started or canceled. Stop processing. } else { task.m_stateFlags |= (int)Task.TaskStateFlags.Started; } // Try to inline it but queue if we can't try { if (!task.m_taskScheduler.TryRunInline(task, taskWasPreviouslyQueued: false)) { task.m_taskScheduler.InternalQueueTask(task); } } catch (Exception e) { // Either TryRunInline() or QueueTask() threw an exception. Record the exception, marking the task as Faulted. // However if it was a ThreadAbortException coming from TryRunInline we need to skip here, // because it would already have been handled in Task.Execute() TaskSchedulerException tse = new TaskSchedulerException(e); task.AddException(tse); task.Finish(false); // Don't re-throw. } } // // This helper routine is targeted by the debugger. // internal abstract Delegate[]? GetDelegateContinuationsForDebugger(); } /// <summary>Provides the standard implementation of a task continuation.</summary> internal sealed class ContinueWithTaskContinuation : TaskContinuation { /// <summary>The unstarted continuation task.</summary> internal Task? m_task; /// <summary>The options to use with the continuation task.</summary> internal readonly TaskContinuationOptions m_options; /// <summary>The task scheduler with which to run the continuation task.</summary> private readonly TaskScheduler m_taskScheduler; /// <summary>Initializes a new continuation.</summary> /// <param name="task">The task to be activated.</param> /// <param name="options">The continuation options.</param> /// <param name="scheduler">The scheduler to use for the continuation.</param> internal ContinueWithTaskContinuation(Task task, TaskContinuationOptions options, TaskScheduler scheduler) { Debug.Assert(task != null, "TaskContinuation ctor: task is null"); Debug.Assert(scheduler != null, "TaskContinuation ctor: scheduler is null"); m_task = task; m_options = options; m_taskScheduler = scheduler; if (TplEventSource.Log.IsEnabled()) TplEventSource.Log.TraceOperationBegin(m_task.Id, "Task.ContinueWith: " + task.m_action!.Method.Name, 0); if (Task.s_asyncDebuggingEnabled) Task.AddToActiveTasks(m_task); } /// <summary>Invokes the continuation for the target completion task.</summary> /// <param name="completedTask">The completed task.</param> /// <param name="canInlineContinuationTask">Whether the continuation can be inlined.</param> internal override void Run(Task completedTask, bool canInlineContinuationTask) { Debug.Assert(completedTask != null); Debug.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed"); Task? continuationTask = m_task; Debug.Assert(continuationTask != null); m_task = null; // Check if the completion status of the task works with the desired // activation criteria of the TaskContinuationOptions. TaskContinuationOptions options = m_options; bool isRightKind = completedTask.IsCompletedSuccessfully ? (options & TaskContinuationOptions.NotOnRanToCompletion) == 0 : (completedTask.IsCanceled ? (options & TaskContinuationOptions.NotOnCanceled) == 0 : (options & TaskContinuationOptions.NotOnFaulted) == 0); // If the completion status is allowed, run the continuation. if (isRightKind) { // If the task was cancel before running (e.g a ContinueWhenAll with a cancelled caancelation token) // we will still flow it to ScheduleAndStart() were it will check the status before running // We check here to avoid faulty logs that contain a join event to an operation that was already set as completed. if (TplEventSource.Log.IsEnabled() && !continuationTask.IsCanceled) { // Log now that we are sure that this continuation is being ran TplEventSource.Log.TraceOperationRelation(continuationTask.Id, CausalityRelation.AssignDelegate); } continuationTask.m_taskScheduler = m_taskScheduler; // Either run directly or just queue it up for execution, depending // on whether synchronous or asynchronous execution is wanted. if (canInlineContinuationTask && // inlining is allowed by the caller (options & TaskContinuationOptions.ExecuteSynchronously) != 0) // synchronous execution was requested by the continuation's creator { InlineIfPossibleOrElseQueue(continuationTask, needsProtection: true); } else { try { continuationTask.ScheduleAndStart(needsProtection: true); } catch (TaskSchedulerException) { // No further action is necessary -- ScheduleAndStart() already transitioned the // task to faulted. But we want to make sure that no exception is thrown from here. } } } else { // Otherwise, the final state of this task does not match the desired continuation activation criteria; cancel it to denote this. Task.ContingentProperties? cp = continuationTask.m_contingentProperties; // no need to volatile read, as we only care about the token, which is only assignable at construction if (cp is null || cp.m_cancellationToken == default) { // With no cancellation token, use an optimized path that doesn't need to account for concurrent completion. // This is primarily valuable for continuations created with TaskContinuationOptions.NotOn* options, where // we'll cancel the continuation if it's not needed. continuationTask.InternalCancelContinueWithInitialState(); } else { // There's a non-default token. Follow the normal internal cancellation path. continuationTask.InternalCancel(); } } } internal override Delegate[]? GetDelegateContinuationsForDebugger() => m_task is null ? null : m_task.m_action is null ? m_task.GetDelegateContinuationsForDebugger() : new Delegate[] { m_task.m_action }; } /// <summary>Task continuation for awaiting with a current synchronization context.</summary> internal sealed class SynchronizationContextAwaitTaskContinuation : AwaitTaskContinuation { /// <summary>SendOrPostCallback delegate to invoke the action.</summary> private static readonly SendOrPostCallback s_postCallback = static state => { Debug.Assert(state is Action); ((Action)state)(); }; /// <summary>Cached delegate for PostAction</summary> private static ContextCallback? s_postActionCallback; /// <summary>The context with which to run the action.</summary> private readonly SynchronizationContext m_syncContext; /// <summary>Initializes the SynchronizationContextAwaitTaskContinuation.</summary> /// <param name="context">The synchronization context with which to invoke the action. Must not be null.</param> /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param> internal SynchronizationContextAwaitTaskContinuation( SynchronizationContext context, Action action, bool flowExecutionContext) : base(action, flowExecutionContext) { Debug.Assert(context != null); m_syncContext = context; } /// <summary>Inlines or schedules the continuation.</summary> /// <param name="task">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal sealed override void Run(Task task, bool canInlineContinuationTask) { // If we're allowed to inline, run the action on this thread. if (canInlineContinuationTask && m_syncContext == SynchronizationContext.Current) { RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask); } // Otherwise, Post the action back to the SynchronizationContext. else { TplEventSource log = TplEventSource.Log; if (log.IsEnabled()) { m_continuationId = Task.NewId(); log.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, m_continuationId); } RunCallback(GetPostActionCallback(), this, ref Task.t_currentTask); } // Any exceptions will be handled by RunCallback. } /// <summary>Calls InvokeOrPostAction(false) on the supplied SynchronizationContextAwaitTaskContinuation.</summary> /// <param name="state">The SynchronizationContextAwaitTaskContinuation.</param> private static void PostAction(object? state) { Debug.Assert(state is SynchronizationContextAwaitTaskContinuation); var c = (SynchronizationContextAwaitTaskContinuation)state; TplEventSource log = TplEventSource.Log; if (log.IsEnabled() && log.TasksSetActivityIds && c.m_continuationId != 0) { c.m_syncContext.Post(s_postCallback, GetActionLogDelegate(c.m_continuationId, c.m_action)); } else { c.m_syncContext.Post(s_postCallback, c.m_action); // s_postCallback is manually cached, as the compiler won't in a SecurityCritical method } } private static Action GetActionLogDelegate(int continuationId, Action action) { return () => { Guid activityId = TplEventSource.CreateGuidForTaskID(continuationId); System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(activityId, out Guid savedActivityId); try { action(); } finally { System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(savedActivityId); } }; } /// <summary>Gets a cached delegate for the PostAction method.</summary> /// <returns> /// A delegate for PostAction, which expects a SynchronizationContextAwaitTaskContinuation /// to be passed as state. /// </returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ContextCallback GetPostActionCallback() => s_postActionCallback ??= PostAction; } /// <summary>Task continuation for awaiting with a task scheduler.</summary> internal sealed class TaskSchedulerAwaitTaskContinuation : AwaitTaskContinuation { /// <summary>The scheduler on which to run the action.</summary> private readonly TaskScheduler m_scheduler; /// <summary>Initializes the TaskSchedulerAwaitTaskContinuation.</summary> /// <param name="scheduler">The task scheduler with which to invoke the action. Must not be null.</param> /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param> internal TaskSchedulerAwaitTaskContinuation( TaskScheduler scheduler, Action action, bool flowExecutionContext) : base(action, flowExecutionContext) { Debug.Assert(scheduler != null); m_scheduler = scheduler; } /// <summary>Inlines or schedules the continuation.</summary> /// <param name="ignored">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal sealed override void Run(Task ignored, bool canInlineContinuationTask) { // If we're targeting the default scheduler, we can use the faster path provided by the base class. if (m_scheduler == TaskScheduler.Default) { base.Run(ignored, canInlineContinuationTask); } else { // We permit inlining if the caller allows us to, and // either we're on a thread pool thread (in which case we're fine running arbitrary code) // or we're already on the target scheduler (in which case we'll just ask the scheduler // whether it's ok to run here). We include the IsThreadPoolThread check here, whereas // we don't in AwaitTaskContinuation.Run, since here it expands what's allowed as opposed // to in AwaitTaskContinuation.Run where it restricts what's allowed. bool inlineIfPossible = canInlineContinuationTask && (TaskScheduler.InternalCurrent == m_scheduler || Thread.CurrentThread.IsThreadPoolThread); // Create the continuation task task. If we're allowed to inline, try to do so. // The target scheduler may still deny us from executing on this thread, in which case this'll be queued. Task task = CreateTask(static state => { try { ((Action)state!)(); } catch (Exception exception) { Task.ThrowAsync(exception, targetContext: null); } }, m_action, m_scheduler); if (inlineIfPossible) { InlineIfPossibleOrElseQueue(task, needsProtection: false); } else { // We need to run asynchronously, so just schedule the task. try { task.ScheduleAndStart(needsProtection: false); } catch (TaskSchedulerException) { } // No further action is necessary, as ScheduleAndStart already transitioned task to faulted } } } } /// <summary>Base task continuation class used for await continuations.</summary> internal class AwaitTaskContinuation : TaskContinuation, IThreadPoolWorkItem { /// <summary>The ExecutionContext with which to run the continuation.</summary> private readonly ExecutionContext? m_capturedContext; /// <summary>The action to invoke.</summary> protected readonly Action m_action; protected int m_continuationId; /// <summary>Initializes the continuation.</summary> /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param> internal AwaitTaskContinuation(Action action, bool flowExecutionContext) { Debug.Assert(action != null); m_action = action; if (flowExecutionContext) { m_capturedContext = ExecutionContext.Capture(); } } /// <summary>Creates a task to run the action with the specified state on the specified scheduler.</summary> /// <param name="action">The action to run. Must not be null.</param> /// <param name="state">The state to pass to the action. Must not be null.</param> /// <param name="scheduler">The scheduler to target.</param> /// <returns>The created task.</returns> protected Task CreateTask(Action<object?> action, object? state, TaskScheduler scheduler) { Debug.Assert(action != null); Debug.Assert(scheduler != null); return new Task( action, state, null, default, TaskCreationOptions.None, InternalTaskOptions.QueuedByRuntime, scheduler) { CapturedContext = m_capturedContext }; } /// <summary>Inlines or schedules the continuation onto the default scheduler.</summary> /// <param name="task">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal override void Run(Task task, bool canInlineContinuationTask) { // For the base AwaitTaskContinuation, we allow inlining if our caller allows it // and if we're in a "valid location" for it. See the comments on // IsValidLocationForInlining for more about what's valid. For performance // reasons we would like to always inline, but we don't in some cases to avoid // running arbitrary amounts of work in suspected "bad locations", like UI threads. if (canInlineContinuationTask && IsValidLocationForInlining) { RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask); // any exceptions from m_action will be handled by s_callbackRunAction } else { TplEventSource log = TplEventSource.Log; if (log.IsEnabled()) { m_continuationId = Task.NewId(); log.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, m_continuationId); } // We couldn't inline, so now we need to schedule it ThreadPool.UnsafeQueueUserWorkItemInternal(this, preferLocal: true); } } /// <summary> /// Gets whether the current thread is an appropriate location to inline a continuation's execution. /// </summary> /// <remarks> /// Returns whether SynchronizationContext is null and we're in the default scheduler. /// If the await had a SynchronizationContext/TaskScheduler where it began and the /// default/ConfigureAwait(true) was used, then we won't be on this path. If, however, /// ConfigureAwait(false) was used, or the SynchronizationContext and TaskScheduler were /// naturally null/Default, then we might end up here. If we do, we need to make sure /// that we don't execute continuations in a place that isn't set up to handle them, e.g. /// running arbitrary amounts of code on the UI thread. It would be "correct", but very /// expensive, to always run the continuations asynchronously, incurring lots of context /// switches and allocations and locks and the like. As such, we employ the heuristic /// that if the current thread has a non-null SynchronizationContext or a non-default /// scheduler, then we better not run arbitrary continuations here. /// </remarks> internal static bool IsValidLocationForInlining { get { // If there's a SynchronizationContext, we'll be conservative and say // this is a bad location to inline. SynchronizationContext? ctx = SynchronizationContext.Current; if (ctx != null && ctx.GetType() != typeof(SynchronizationContext)) return false; // Similarly, if there's a non-default TaskScheduler, we'll be conservative // and say this is a bad location to inline. TaskScheduler? sched = TaskScheduler.InternalCurrent; return sched == null || sched == TaskScheduler.Default; } } void IThreadPoolWorkItem.Execute() { TplEventSource log = TplEventSource.Log; ExecutionContext? context = m_capturedContext; if (!log.IsEnabled() && context == null) { m_action(); return; } Guid savedActivityId = default; if (log.IsEnabled() && log.TasksSetActivityIds && m_continuationId != 0) { Guid activityId = TplEventSource.CreateGuidForTaskID(m_continuationId); System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(activityId, out savedActivityId); } try { // We're not inside of a task, so t_currentTask doesn't need to be specially maintained. // We're on a thread pool thread with no higher-level callers, so exceptions can just propagate. ExecutionContext.CheckThreadPoolAndContextsAreDefault(); // If there's no execution context or Default, just invoke the delegate as ThreadPool is on Default context. // We don't have to use ExecutionContext.Run for the Default context here as there is no extra processing after the delegate if (context == null || context.IsDefault) { m_action(); } // If there is an execution context, get the cached delegate and run the action under the context. else { ExecutionContext.RunForThreadPoolUnsafe(context, s_invokeAction, m_action); } // ThreadPoolWorkQueue.Dispatch handles notifications and reset context back to default } finally { if (log.IsEnabled() && log.TasksSetActivityIds && m_continuationId != 0) { System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(savedActivityId); } } } /// <summary>Cached delegate that invokes an Action passed as an object parameter.</summary> private static readonly ContextCallback s_invokeContextCallback = static (state) => { Debug.Assert(state is Action); ((Action)state)(); }; private static readonly Action<Action> s_invokeAction = (action) => action(); [MethodImpl(MethodImplOptions.AggressiveInlining)] protected static ContextCallback GetInvokeActionCallback() => s_invokeContextCallback; /// <summary>Runs the callback synchronously with the provided state.</summary> /// <param name="callback">The callback to run.</param> /// <param name="state">The state to pass to the callback.</param> /// <param name="currentTask">A reference to Task.t_currentTask.</param> protected void RunCallback(ContextCallback callback, object? state, ref Task? currentTask) { Debug.Assert(callback != null); Debug.Assert(currentTask == Task.t_currentTask); // Pretend there's no current task, so that no task is seen as a parent // and TaskScheduler.Current does not reflect false information Task? prevCurrentTask = currentTask; try { if (prevCurrentTask != null) currentTask = null; ExecutionContext? context = m_capturedContext; if (context == null) { // If there's no captured context, just run the callback directly. callback(state); } else { // Otherwise, use the captured context to do so. ExecutionContext.RunInternal(context, callback, state); } } catch (Exception exception) // we explicitly do not request handling of dangerous exceptions like AVs { Task.ThrowAsync(exception, targetContext: null); } finally { // Restore the current task information if (prevCurrentTask != null) currentTask = prevCurrentTask; } } /// <summary>Invokes or schedules the action to be executed.</summary> /// <param name="action">The action to invoke or queue.</param> /// <param name="allowInlining"> /// true to allow inlining, or false to force the action to run asynchronously. /// </param> /// <remarks> /// No ExecutionContext work is performed used. This method is only used in the /// case where a raw Action continuation delegate was stored into the Task, which /// only happens in Task.SetContinuationForAwait if execution context flow was disabled /// via using TaskAwaiter.UnsafeOnCompleted or a similar path. /// </remarks> internal static void RunOrScheduleAction(Action action, bool allowInlining) { ref Task? currentTask = ref Task.t_currentTask; Task? prevCurrentTask = currentTask; // If we're not allowed to run here, schedule the action if (!allowInlining || !IsValidLocationForInlining) { UnsafeScheduleAction(action, prevCurrentTask); return; } // Otherwise, run it, making sure that t_currentTask is null'd out appropriately during the execution try { if (prevCurrentTask != null) currentTask = null; action(); } catch (Exception exception) { Task.ThrowAsync(exception, targetContext: null); } finally { if (prevCurrentTask != null) currentTask = prevCurrentTask; } } /// <summary>Invokes or schedules the action to be executed.</summary> /// <param name="box">The <see cref="IAsyncStateMachineBox"/> that needs to be invoked or queued.</param> /// <param name="allowInlining"> /// true to allow inlining, or false to force the box's action to run asynchronously. /// </param> internal static void RunOrScheduleAction(IAsyncStateMachineBox box, bool allowInlining) { // Same logic as in the RunOrScheduleAction(Action, ...) overload, except invoking // box.Invoke instead of action(). ref Task? currentTask = ref Task.t_currentTask; Task? prevCurrentTask = currentTask; // If we're not allowed to run here, schedule the action if (!allowInlining || !IsValidLocationForInlining) { // If logging is disabled, we can simply queue the box itself as a custom work // item, and its work item execution will just invoke its MoveNext. However, if // logging is enabled, there is pre/post-work we need to do around logging to // match what's done for other continuations, and that requires flowing additional // information into the continuation, which we don't want to burden other cases of the // box with... so, in that case we just delegate to the AwaitTaskContinuation-based // path that already handles this, albeit at the expense of allocating the ATC // object, and potentially forcing the box's delegate into existence, when logging // is enabled. if (TplEventSource.Log.IsEnabled()) { UnsafeScheduleAction(box.MoveNextAction, prevCurrentTask); } else { ThreadPool.UnsafeQueueUserWorkItemInternal(box, preferLocal: true); } return; } // Otherwise, run it, making sure that t_currentTask is null'd out appropriately during the execution try { if (prevCurrentTask != null) currentTask = null; box.MoveNext(); } catch (Exception exception) { Task.ThrowAsync(exception, targetContext: null); } finally { if (prevCurrentTask != null) currentTask = prevCurrentTask; } } /// <summary>Schedules the action to be executed. No ExecutionContext work is performed used.</summary> /// <param name="action">The action to invoke or queue.</param> /// <param name="task">The task scheduling the action.</param> internal static void UnsafeScheduleAction(Action action, Task? task) { AwaitTaskContinuation atc = new AwaitTaskContinuation(action, flowExecutionContext: false); TplEventSource log = TplEventSource.Log; if (log.IsEnabled() && task != null) { atc.m_continuationId = Task.NewId(); log.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, atc.m_continuationId); } ThreadPool.UnsafeQueueUserWorkItemInternal(atc, preferLocal: true); } internal override Delegate[] GetDelegateContinuationsForDebugger() { Debug.Assert(m_action != null); return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Threading.Tasks { // Task type used to implement: Task ContinueWith(Action<Task,...>) internal sealed class ContinuationTaskFromTask : Task { private Task? m_antecedent; public ContinuationTaskFromTask( Task antecedent, Delegate action, object? state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null) { Debug.Assert(action is Action<Task> || action is Action<Task, object?>, "Invalid delegate type in ContinuationTaskFromTask"); m_antecedent = antecedent; } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. Task? antecedent = m_antecedent; Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Debug.Assert(m_action != null); if (m_action is Action<Task> action) { action(antecedent); return; } if (m_action is Action<Task, object?> actionWithState) { actionWithState(antecedent, m_stateObject); return; } Debug.Fail("Invalid m_action in ContinuationTaskFromTask"); } } // Task type used to implement: Task<TResult> ContinueWith(Func<Task,...>) internal sealed class ContinuationResultTaskFromTask<TResult> : Task<TResult> { private Task? m_antecedent; public ContinuationResultTaskFromTask( Task antecedent, Delegate function, object? state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(function, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null) { Debug.Assert(function is Func<Task, TResult> || function is Func<Task, object?, TResult>, "Invalid delegate type in ContinuationResultTaskFromTask"); m_antecedent = antecedent; } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. Task? antecedent = m_antecedent; Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationResultTaskFromTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Debug.Assert(m_action != null); if (m_action is Func<Task, TResult> func) { m_result = func(antecedent); return; } if (m_action is Func<Task, object?, TResult> funcWithState) { m_result = funcWithState(antecedent, m_stateObject); return; } Debug.Fail("Invalid m_action in ContinuationResultTaskFromTask"); } } // Task type used to implement: Task ContinueWith(Action<Task<TAntecedentResult>,...>) internal sealed class ContinuationTaskFromResultTask<TAntecedentResult> : Task { private Task<TAntecedentResult>? m_antecedent; public ContinuationTaskFromResultTask( Task<TAntecedentResult> antecedent, Delegate action, object? state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null) { Debug.Assert(action is Action<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object?>, "Invalid delegate type in ContinuationTaskFromResultTask"); m_antecedent = antecedent; } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. Task<TAntecedentResult>? antecedent = m_antecedent; Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromResultTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Debug.Assert(m_action != null); if (m_action is Action<Task<TAntecedentResult>> action) { action(antecedent); return; } if (m_action is Action<Task<TAntecedentResult>, object?> actionWithState) { actionWithState(antecedent, m_stateObject); return; } Debug.Fail("Invalid m_action in ContinuationTaskFromResultTask"); } } // Task type used to implement: Task<TResult> ContinueWith(Func<Task<TAntecedentResult>,...>) internal sealed class ContinuationResultTaskFromResultTask<TAntecedentResult, TResult> : Task<TResult> { private Task<TAntecedentResult>? m_antecedent; public ContinuationResultTaskFromResultTask( Task<TAntecedentResult> antecedent, Delegate function, object? state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(function, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null) { Debug.Assert(function is Func<Task<TAntecedentResult>, TResult> || function is Func<Task<TAntecedentResult>, object?, TResult>, "Invalid delegate type in ContinuationResultTaskFromResultTask"); m_antecedent = antecedent; } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. Task<TAntecedentResult>? antecedent = m_antecedent; Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationResultTaskFromResultTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Debug.Assert(m_action != null); if (m_action is Func<Task<TAntecedentResult>, TResult> func) { m_result = func(antecedent); return; } if (m_action is Func<Task<TAntecedentResult>, object?, TResult> funcWithState) { m_result = funcWithState(antecedent, m_stateObject); return; } Debug.Fail("Invalid m_action in ContinuationResultTaskFromResultTask"); } } // For performance reasons, we don't just have a single way of representing // a continuation object. Rather, we have a hierarchy of types: // - TaskContinuation: abstract base that provides a virtual Run method // - StandardTaskContinuation: wraps a task,options,and scheduler, and overrides Run to process the task with that configuration // - AwaitTaskContinuation: base for continuations created through TaskAwaiter; targets default scheduler by default // - TaskSchedulerAwaitTaskContinuation: awaiting with a non-default TaskScheduler // - SynchronizationContextAwaitTaskContinuation: awaiting with a "current" sync ctx /// <summary>Represents a continuation.</summary> internal abstract class TaskContinuation { /// <summary>Inlines or schedules the continuation.</summary> /// <param name="completedTask">The antecedent task that has completed.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal abstract void Run(Task completedTask, bool canInlineContinuationTask); /// <summary>Tries to run the task on the current thread, if possible; otherwise, schedules it.</summary> /// <param name="task">The task to run</param> /// <param name="needsProtection"> /// true if we need to protect against multiple threads racing to start/cancel the task; otherwise, false. /// </param> protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection) { Debug.Assert(task != null); Debug.Assert(task.m_taskScheduler != null); // Set the TaskStateFlags.Started flag. This only needs to be done // if the task may be canceled or if someone else has a reference to it // that may try to execute it. if (needsProtection) { if (!task.MarkStarted()) return; // task has been previously started or canceled. Stop processing. } else { task.m_stateFlags |= (int)Task.TaskStateFlags.Started; } // Try to inline it but queue if we can't try { if (!task.m_taskScheduler.TryRunInline(task, taskWasPreviouslyQueued: false)) { task.m_taskScheduler.InternalQueueTask(task); } } catch (Exception e) { // Either TryRunInline() or QueueTask() threw an exception. Record the exception, marking the task as Faulted. // However if it was a ThreadAbortException coming from TryRunInline we need to skip here, // because it would already have been handled in Task.Execute() TaskSchedulerException tse = new TaskSchedulerException(e); task.AddException(tse); task.Finish(false); // Don't re-throw. } } // // This helper routine is targeted by the debugger. // internal abstract Delegate[]? GetDelegateContinuationsForDebugger(); } /// <summary>Provides the standard implementation of a task continuation.</summary> internal sealed class ContinueWithTaskContinuation : TaskContinuation { /// <summary>The unstarted continuation task.</summary> internal Task? m_task; /// <summary>The options to use with the continuation task.</summary> internal readonly TaskContinuationOptions m_options; /// <summary>The task scheduler with which to run the continuation task.</summary> private readonly TaskScheduler m_taskScheduler; /// <summary>Initializes a new continuation.</summary> /// <param name="task">The task to be activated.</param> /// <param name="options">The continuation options.</param> /// <param name="scheduler">The scheduler to use for the continuation.</param> internal ContinueWithTaskContinuation(Task task, TaskContinuationOptions options, TaskScheduler scheduler) { Debug.Assert(task != null, "TaskContinuation ctor: task is null"); Debug.Assert(scheduler != null, "TaskContinuation ctor: scheduler is null"); m_task = task; m_options = options; m_taskScheduler = scheduler; if (TplEventSource.Log.IsEnabled()) TplEventSource.Log.TraceOperationBegin(m_task.Id, "Task.ContinueWith: " + task.m_action!.Method.Name, 0); if (Task.s_asyncDebuggingEnabled) Task.AddToActiveTasks(m_task); } /// <summary>Invokes the continuation for the target completion task.</summary> /// <param name="completedTask">The completed task.</param> /// <param name="canInlineContinuationTask">Whether the continuation can be inlined.</param> internal override void Run(Task completedTask, bool canInlineContinuationTask) { Debug.Assert(completedTask != null); Debug.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed"); Task? continuationTask = m_task; Debug.Assert(continuationTask != null); m_task = null; // Check if the completion status of the task works with the desired // activation criteria of the TaskContinuationOptions. TaskContinuationOptions options = m_options; bool isRightKind = completedTask.IsCompletedSuccessfully ? (options & TaskContinuationOptions.NotOnRanToCompletion) == 0 : (completedTask.IsCanceled ? (options & TaskContinuationOptions.NotOnCanceled) == 0 : (options & TaskContinuationOptions.NotOnFaulted) == 0); // If the completion status is allowed, run the continuation. if (isRightKind) { // If the task was cancel before running (e.g a ContinueWhenAll with a cancelled caancelation token) // we will still flow it to ScheduleAndStart() were it will check the status before running // We check here to avoid faulty logs that contain a join event to an operation that was already set as completed. if (TplEventSource.Log.IsEnabled() && !continuationTask.IsCanceled) { // Log now that we are sure that this continuation is being ran TplEventSource.Log.TraceOperationRelation(continuationTask.Id, CausalityRelation.AssignDelegate); } continuationTask.m_taskScheduler = m_taskScheduler; // Either run directly or just queue it up for execution, depending // on whether synchronous or asynchronous execution is wanted. if (canInlineContinuationTask && // inlining is allowed by the caller (options & TaskContinuationOptions.ExecuteSynchronously) != 0) // synchronous execution was requested by the continuation's creator { InlineIfPossibleOrElseQueue(continuationTask, needsProtection: true); } else { try { continuationTask.ScheduleAndStart(needsProtection: true); } catch (TaskSchedulerException) { // No further action is necessary -- ScheduleAndStart() already transitioned the // task to faulted. But we want to make sure that no exception is thrown from here. } } } else { // Otherwise, the final state of this task does not match the desired continuation activation criteria; cancel it to denote this. Task.ContingentProperties? cp = continuationTask.m_contingentProperties; // no need to volatile read, as we only care about the token, which is only assignable at construction if (cp is null || cp.m_cancellationToken == default) { // With no cancellation token, use an optimized path that doesn't need to account for concurrent completion. // This is primarily valuable for continuations created with TaskContinuationOptions.NotOn* options, where // we'll cancel the continuation if it's not needed. continuationTask.InternalCancelContinueWithInitialState(); } else { // There's a non-default token. Follow the normal internal cancellation path. continuationTask.InternalCancel(); } } } internal override Delegate[]? GetDelegateContinuationsForDebugger() => m_task is null ? null : m_task.m_action is null ? m_task.GetDelegateContinuationsForDebugger() : new Delegate[] { m_task.m_action }; } /// <summary>Task continuation for awaiting with a current synchronization context.</summary> internal sealed class SynchronizationContextAwaitTaskContinuation : AwaitTaskContinuation { /// <summary>SendOrPostCallback delegate to invoke the action.</summary> private static readonly SendOrPostCallback s_postCallback = static state => { Debug.Assert(state is Action); ((Action)state)(); }; /// <summary>Cached delegate for PostAction</summary> private static ContextCallback? s_postActionCallback; /// <summary>The context with which to run the action.</summary> private readonly SynchronizationContext m_syncContext; /// <summary>Initializes the SynchronizationContextAwaitTaskContinuation.</summary> /// <param name="context">The synchronization context with which to invoke the action. Must not be null.</param> /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param> internal SynchronizationContextAwaitTaskContinuation( SynchronizationContext context, Action action, bool flowExecutionContext) : base(action, flowExecutionContext) { Debug.Assert(context != null); m_syncContext = context; } /// <summary>Inlines or schedules the continuation.</summary> /// <param name="task">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal sealed override void Run(Task task, bool canInlineContinuationTask) { // If we're allowed to inline, run the action on this thread. if (canInlineContinuationTask && m_syncContext == SynchronizationContext.Current) { RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask); } // Otherwise, Post the action back to the SynchronizationContext. else { TplEventSource log = TplEventSource.Log; if (log.IsEnabled()) { m_continuationId = Task.NewId(); log.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, m_continuationId); } RunCallback(GetPostActionCallback(), this, ref Task.t_currentTask); } // Any exceptions will be handled by RunCallback. } /// <summary>Calls InvokeOrPostAction(false) on the supplied SynchronizationContextAwaitTaskContinuation.</summary> /// <param name="state">The SynchronizationContextAwaitTaskContinuation.</param> private static void PostAction(object? state) { Debug.Assert(state is SynchronizationContextAwaitTaskContinuation); var c = (SynchronizationContextAwaitTaskContinuation)state; TplEventSource log = TplEventSource.Log; if (log.IsEnabled() && log.TasksSetActivityIds && c.m_continuationId != 0) { c.m_syncContext.Post(s_postCallback, GetActionLogDelegate(c.m_continuationId, c.m_action)); } else { c.m_syncContext.Post(s_postCallback, c.m_action); // s_postCallback is manually cached, as the compiler won't in a SecurityCritical method } } private static Action GetActionLogDelegate(int continuationId, Action action) { return () => { Guid activityId = TplEventSource.CreateGuidForTaskID(continuationId); System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(activityId, out Guid savedActivityId); try { action(); } finally { System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(savedActivityId); } }; } /// <summary>Gets a cached delegate for the PostAction method.</summary> /// <returns> /// A delegate for PostAction, which expects a SynchronizationContextAwaitTaskContinuation /// to be passed as state. /// </returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ContextCallback GetPostActionCallback() => s_postActionCallback ??= PostAction; } /// <summary>Task continuation for awaiting with a task scheduler.</summary> internal sealed class TaskSchedulerAwaitTaskContinuation : AwaitTaskContinuation { /// <summary>The scheduler on which to run the action.</summary> private readonly TaskScheduler m_scheduler; /// <summary>Initializes the TaskSchedulerAwaitTaskContinuation.</summary> /// <param name="scheduler">The task scheduler with which to invoke the action. Must not be null.</param> /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param> internal TaskSchedulerAwaitTaskContinuation( TaskScheduler scheduler, Action action, bool flowExecutionContext) : base(action, flowExecutionContext) { Debug.Assert(scheduler != null); m_scheduler = scheduler; } /// <summary>Inlines or schedules the continuation.</summary> /// <param name="ignored">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal sealed override void Run(Task ignored, bool canInlineContinuationTask) { // If we're targeting the default scheduler, we can use the faster path provided by the base class. if (m_scheduler == TaskScheduler.Default) { base.Run(ignored, canInlineContinuationTask); } else { // We permit inlining if the caller allows us to, and // either we're on a thread pool thread (in which case we're fine running arbitrary code) // or we're already on the target scheduler (in which case we'll just ask the scheduler // whether it's ok to run here). We include the IsThreadPoolThread check here, whereas // we don't in AwaitTaskContinuation.Run, since here it expands what's allowed as opposed // to in AwaitTaskContinuation.Run where it restricts what's allowed. bool inlineIfPossible = canInlineContinuationTask && (TaskScheduler.InternalCurrent == m_scheduler || Thread.CurrentThread.IsThreadPoolThread); // Create the continuation task task. If we're allowed to inline, try to do so. // The target scheduler may still deny us from executing on this thread, in which case this'll be queued. Task task = CreateTask(static state => { try { ((Action)state!)(); } catch (Exception exception) { Task.ThrowAsync(exception, targetContext: null); } }, m_action, m_scheduler); if (inlineIfPossible) { InlineIfPossibleOrElseQueue(task, needsProtection: false); } else { // We need to run asynchronously, so just schedule the task. try { task.ScheduleAndStart(needsProtection: false); } catch (TaskSchedulerException) { } // No further action is necessary, as ScheduleAndStart already transitioned task to faulted } } } } /// <summary>Base task continuation class used for await continuations.</summary> internal class AwaitTaskContinuation : TaskContinuation, IThreadPoolWorkItem { /// <summary>The ExecutionContext with which to run the continuation.</summary> private readonly ExecutionContext? m_capturedContext; /// <summary>The action to invoke.</summary> protected readonly Action m_action; protected int m_continuationId; /// <summary>Initializes the continuation.</summary> /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param> internal AwaitTaskContinuation(Action action, bool flowExecutionContext) { Debug.Assert(action != null); m_action = action; if (flowExecutionContext) { m_capturedContext = ExecutionContext.Capture(); } } /// <summary>Creates a task to run the action with the specified state on the specified scheduler.</summary> /// <param name="action">The action to run. Must not be null.</param> /// <param name="state">The state to pass to the action. Must not be null.</param> /// <param name="scheduler">The scheduler to target.</param> /// <returns>The created task.</returns> protected Task CreateTask(Action<object?> action, object? state, TaskScheduler scheduler) { Debug.Assert(action != null); Debug.Assert(scheduler != null); return new Task( action, state, null, default, TaskCreationOptions.None, InternalTaskOptions.QueuedByRuntime, scheduler) { CapturedContext = m_capturedContext }; } /// <summary>Inlines or schedules the continuation onto the default scheduler.</summary> /// <param name="task">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal override void Run(Task task, bool canInlineContinuationTask) { // For the base AwaitTaskContinuation, we allow inlining if our caller allows it // and if we're in a "valid location" for it. See the comments on // IsValidLocationForInlining for more about what's valid. For performance // reasons we would like to always inline, but we don't in some cases to avoid // running arbitrary amounts of work in suspected "bad locations", like UI threads. if (canInlineContinuationTask && IsValidLocationForInlining) { RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask); // any exceptions from m_action will be handled by s_callbackRunAction } else { TplEventSource log = TplEventSource.Log; if (log.IsEnabled()) { m_continuationId = Task.NewId(); log.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, m_continuationId); } // We couldn't inline, so now we need to schedule it ThreadPool.UnsafeQueueUserWorkItemInternal(this, preferLocal: true); } } /// <summary> /// Gets whether the current thread is an appropriate location to inline a continuation's execution. /// </summary> /// <remarks> /// Returns whether SynchronizationContext is null and we're in the default scheduler. /// If the await had a SynchronizationContext/TaskScheduler where it began and the /// default/ConfigureAwait(true) was used, then we won't be on this path. If, however, /// ConfigureAwait(false) was used, or the SynchronizationContext and TaskScheduler were /// naturally null/Default, then we might end up here. If we do, we need to make sure /// that we don't execute continuations in a place that isn't set up to handle them, e.g. /// running arbitrary amounts of code on the UI thread. It would be "correct", but very /// expensive, to always run the continuations asynchronously, incurring lots of context /// switches and allocations and locks and the like. As such, we employ the heuristic /// that if the current thread has a non-null SynchronizationContext or a non-default /// scheduler, then we better not run arbitrary continuations here. /// </remarks> internal static bool IsValidLocationForInlining { get { // If there's a SynchronizationContext, we'll be conservative and say // this is a bad location to inline. SynchronizationContext? ctx = SynchronizationContext.Current; if (ctx != null && ctx.GetType() != typeof(SynchronizationContext)) return false; // Similarly, if there's a non-default TaskScheduler, we'll be conservative // and say this is a bad location to inline. TaskScheduler? sched = TaskScheduler.InternalCurrent; return sched == null || sched == TaskScheduler.Default; } } void IThreadPoolWorkItem.Execute() { TplEventSource log = TplEventSource.Log; ExecutionContext? context = m_capturedContext; if (!log.IsEnabled() && context == null) { m_action(); return; } Guid savedActivityId = default; if (log.IsEnabled() && log.TasksSetActivityIds && m_continuationId != 0) { Guid activityId = TplEventSource.CreateGuidForTaskID(m_continuationId); System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(activityId, out savedActivityId); } try { // We're not inside of a task, so t_currentTask doesn't need to be specially maintained. // We're on a thread pool thread with no higher-level callers, so exceptions can just propagate. ExecutionContext.CheckThreadPoolAndContextsAreDefault(); // If there's no execution context or Default, just invoke the delegate as ThreadPool is on Default context. // We don't have to use ExecutionContext.Run for the Default context here as there is no extra processing after the delegate if (context == null || context.IsDefault) { m_action(); } // If there is an execution context, get the cached delegate and run the action under the context. else { ExecutionContext.RunForThreadPoolUnsafe(context, s_invokeAction, m_action); } // ThreadPoolWorkQueue.Dispatch handles notifications and reset context back to default } finally { if (log.IsEnabled() && log.TasksSetActivityIds && m_continuationId != 0) { System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(savedActivityId); } } } /// <summary>Cached delegate that invokes an Action passed as an object parameter.</summary> private static readonly ContextCallback s_invokeContextCallback = static (state) => { Debug.Assert(state is Action); ((Action)state)(); }; private static readonly Action<Action> s_invokeAction = (action) => action(); [MethodImpl(MethodImplOptions.AggressiveInlining)] protected static ContextCallback GetInvokeActionCallback() => s_invokeContextCallback; /// <summary>Runs the callback synchronously with the provided state.</summary> /// <param name="callback">The callback to run.</param> /// <param name="state">The state to pass to the callback.</param> /// <param name="currentTask">A reference to Task.t_currentTask.</param> protected void RunCallback(ContextCallback callback, object? state, ref Task? currentTask) { Debug.Assert(callback != null); Debug.Assert(currentTask == Task.t_currentTask); // Pretend there's no current task, so that no task is seen as a parent // and TaskScheduler.Current does not reflect false information Task? prevCurrentTask = currentTask; try { if (prevCurrentTask != null) currentTask = null; ExecutionContext? context = m_capturedContext; if (context == null) { // If there's no captured context, just run the callback directly. callback(state); } else { // Otherwise, use the captured context to do so. ExecutionContext.RunInternal(context, callback, state); } } catch (Exception exception) // we explicitly do not request handling of dangerous exceptions like AVs { Task.ThrowAsync(exception, targetContext: null); } finally { // Restore the current task information if (prevCurrentTask != null) currentTask = prevCurrentTask; } } /// <summary>Invokes or schedules the action to be executed.</summary> /// <param name="action">The action to invoke or queue.</param> /// <param name="allowInlining"> /// true to allow inlining, or false to force the action to run asynchronously. /// </param> /// <remarks> /// No ExecutionContext work is performed used. This method is only used in the /// case where a raw Action continuation delegate was stored into the Task, which /// only happens in Task.SetContinuationForAwait if execution context flow was disabled /// via using TaskAwaiter.UnsafeOnCompleted or a similar path. /// </remarks> internal static void RunOrScheduleAction(Action action, bool allowInlining) { ref Task? currentTask = ref Task.t_currentTask; Task? prevCurrentTask = currentTask; // If we're not allowed to run here, schedule the action if (!allowInlining || !IsValidLocationForInlining) { UnsafeScheduleAction(action, prevCurrentTask); return; } // Otherwise, run it, making sure that t_currentTask is null'd out appropriately during the execution try { if (prevCurrentTask != null) currentTask = null; action(); } catch (Exception exception) { Task.ThrowAsync(exception, targetContext: null); } finally { if (prevCurrentTask != null) currentTask = prevCurrentTask; } } /// <summary>Invokes or schedules the action to be executed.</summary> /// <param name="box">The <see cref="IAsyncStateMachineBox"/> that needs to be invoked or queued.</param> /// <param name="allowInlining"> /// true to allow inlining, or false to force the box's action to run asynchronously. /// </param> internal static void RunOrScheduleAction(IAsyncStateMachineBox box, bool allowInlining) { // Same logic as in the RunOrScheduleAction(Action, ...) overload, except invoking // box.Invoke instead of action(). ref Task? currentTask = ref Task.t_currentTask; Task? prevCurrentTask = currentTask; // If we're not allowed to run here, schedule the action if (!allowInlining || !IsValidLocationForInlining) { // If logging is disabled, we can simply queue the box itself as a custom work // item, and its work item execution will just invoke its MoveNext. However, if // logging is enabled, there is pre/post-work we need to do around logging to // match what's done for other continuations, and that requires flowing additional // information into the continuation, which we don't want to burden other cases of the // box with... so, in that case we just delegate to the AwaitTaskContinuation-based // path that already handles this, albeit at the expense of allocating the ATC // object, and potentially forcing the box's delegate into existence, when logging // is enabled. if (TplEventSource.Log.IsEnabled()) { UnsafeScheduleAction(box.MoveNextAction, prevCurrentTask); } else { ThreadPool.UnsafeQueueUserWorkItemInternal(box, preferLocal: true); } return; } // Otherwise, run it, making sure that t_currentTask is null'd out appropriately during the execution try { if (prevCurrentTask != null) currentTask = null; box.MoveNext(); } catch (Exception exception) { Task.ThrowAsync(exception, targetContext: null); } finally { if (prevCurrentTask != null) currentTask = prevCurrentTask; } } /// <summary>Schedules the action to be executed. No ExecutionContext work is performed used.</summary> /// <param name="action">The action to invoke or queue.</param> /// <param name="task">The task scheduling the action.</param> internal static void UnsafeScheduleAction(Action action, Task? task) { AwaitTaskContinuation atc = new AwaitTaskContinuation(action, flowExecutionContext: false); TplEventSource log = TplEventSource.Log; if (log.IsEnabled() && task != null) { atc.m_continuationId = Task.NewId(); log.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, atc.m_continuationId); } ThreadPool.UnsafeQueueUserWorkItemInternal(atc, preferLocal: true); } internal override Delegate[] GetDelegateContinuationsForDebugger() { Debug.Assert(m_action != null); return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) }; } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/Interop/PInvoke/Generics/GenericsTest.NullableC.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using Xunit; unsafe partial class GenericsNative { [DllImport(nameof(GenericsNative))] public static extern char? GetNullableC(bool hasValue, char value); [DllImport(nameof(GenericsNative))] public static extern void GetNullableCOut(bool hasValue, char value, out char? pValue); [DllImport(nameof(GenericsNative), EntryPoint = "GetNullableCPtr")] public static extern ref readonly char? GetNullableCRef(bool hasValue, char value); [DllImport(nameof(GenericsNative))] public static extern char? AddNullableC(char? lhs, char? rhs); [DllImport(nameof(GenericsNative))] public static extern char? AddNullableCs([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] char?[] pValues, int count); [DllImport(nameof(GenericsNative))] public static extern char? AddNullableCs(in char? pValues, int count); } unsafe partial class GenericsTest { private static void TestNullableC() { Assert.Throws<MarshalDirectiveException>(() => GenericsNative.GetNullableC(true, '1')); Assert.Throws<MarshalDirectiveException>(() => GenericsNative.GetNullableCOut(true, '1', out char? value3)); Assert.Throws<MarshalDirectiveException>(() => GenericsNative.AddNullableC(default, default)); char?[] values = new char?[] { default, default, default, default, default }; Assert.Throws<MarshalDirectiveException>(() => GenericsNative.AddNullableCs(values, values.Length)); Assert.Throws<MarshalDirectiveException>(() => GenericsNative.AddNullableCs(in values[0], values.Length)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using Xunit; unsafe partial class GenericsNative { [DllImport(nameof(GenericsNative))] public static extern char? GetNullableC(bool hasValue, char value); [DllImport(nameof(GenericsNative))] public static extern void GetNullableCOut(bool hasValue, char value, out char? pValue); [DllImport(nameof(GenericsNative), EntryPoint = "GetNullableCPtr")] public static extern ref readonly char? GetNullableCRef(bool hasValue, char value); [DllImport(nameof(GenericsNative))] public static extern char? AddNullableC(char? lhs, char? rhs); [DllImport(nameof(GenericsNative))] public static extern char? AddNullableCs([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] char?[] pValues, int count); [DllImport(nameof(GenericsNative))] public static extern char? AddNullableCs(in char? pValues, int count); } unsafe partial class GenericsTest { private static void TestNullableC() { Assert.Throws<MarshalDirectiveException>(() => GenericsNative.GetNullableC(true, '1')); Assert.Throws<MarshalDirectiveException>(() => GenericsNative.GetNullableCOut(true, '1', out char? value3)); Assert.Throws<MarshalDirectiveException>(() => GenericsNative.AddNullableC(default, default)); char?[] values = new char?[] { default, default, default, default, default }; Assert.Throws<MarshalDirectiveException>(() => GenericsNative.AddNullableCs(values, values.Length)); Assert.Throws<MarshalDirectiveException>(() => GenericsNative.AddNullableCs(in values[0], values.Length)); } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/JIT/HardwareIntrinsics/General/Vector256_1/op_Division.Double.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_DivisionDouble() { var test = new VectorBinaryOpTest__op_DivisionDouble(); // 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_DivisionDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Double> _fld1; public Vector256<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = Math.Max((double)(1), TestLibrary.Generator.GetDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__op_DivisionDouble 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<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__op_DivisionDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = Math.Max((double)(1), TestLibrary.Generator.GetDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); } public VectorBinaryOpTest__op_DivisionDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = Math.Max((double)(1), TestLibrary.Generator.GetDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = Math.Max((double)(1), TestLibrary.Generator.GetDouble()); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr) / Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector256<Double>).GetMethod("op_Division", new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(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<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Double>>(_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_DivisionDouble(); 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<Double> op1, Vector256<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (double)(left[0] / right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (double)(left[i] / right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_Division<Double>(Vector256<Double>, Vector256<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_DivisionDouble() { var test = new VectorBinaryOpTest__op_DivisionDouble(); // 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_DivisionDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Double> _fld1; public Vector256<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = Math.Max((double)(1), TestLibrary.Generator.GetDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__op_DivisionDouble 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<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__op_DivisionDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = Math.Max((double)(1), TestLibrary.Generator.GetDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); } public VectorBinaryOpTest__op_DivisionDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = Math.Max((double)(1), TestLibrary.Generator.GetDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = Math.Max((double)(1), TestLibrary.Generator.GetDouble()); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr) / Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector256<Double>).GetMethod("op_Division", new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(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<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Double>>(_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_DivisionDouble(); 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<Double> op1, Vector256<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (double)(left[0] / right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (double)(left[i] / right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_Division<Double>(Vector256<Double>, Vector256<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/coreclr/pal/tools/preptests.sh
# PrepTests.sh # Initializes our test running environment by setting environment variables appropriately. Already set variables # are not overwritten. This is intended for use on unix. # # Created 10/28/2014 - mmitche ExecPrepTestsCore() { unset -f ExecPrepTestsCore echo echo Preparing this window to run tests echo Setting up Exernal Environment Variables echo _TGTCPU - Target CPU echo BVT_ROOT - Root of tests to run echo CORE_RUN - Test host echo CORE_ROOT - Root of CLR drop. echo # Set $_TGTCPU based on the processor arch. In bash on an x64 linux machine, that will show up as x86_x64. # If so, then set to AMD64. Otherwise I386. if ! test $_TGTCPU then export _TGTCPU=`arch` if test $_TGTCPU = "x86_x64" then export _TGTCPU="AMD64" else export _TGTCPU="i386" fi fi # Set $BVT_ROOT based on current directory if ! test $BVT_ROOT then export BVT_ROOT=$PWD fi # Set $CORE_RUN based on current directory if ! test $CORE_RUN then if test -e $BVT_ROOT/Hosting/CoreClr/Activation/Host/TestHost.exe then export CORE_RUN=$BVT_ROOT/Hosting/CoreClr/Activation/Host/TestHost.exe else echo !!!ERROR: $BVT_ROOT/Hosting/CoreClr/Activation/Host/TestHost.exe does not exist. CORE_RUN not set. return 1 fi fi # Set $CORE_ROOT base to $PWD unless otherwise set. if ! test "$CORE_ROOT" then echo Warning. CORE_ROOT is not set at the moment. Setting it to $PWD export CORE_ROOT=$PWD fi # Report the current state of the environment echo _TGCPU is set to: $_TGTCPU echo BVT_ROOT is set to: $BVT_ROOT echo CORE_ROOT is set to: $CORE_ROOT echo CORE_RUN is set to $CORE_RUN echo return 0 } # This is explicitly so that we can RETURN and not exit this script. ExecPrepTestsCore $*
# PrepTests.sh # Initializes our test running environment by setting environment variables appropriately. Already set variables # are not overwritten. This is intended for use on unix. # # Created 10/28/2014 - mmitche ExecPrepTestsCore() { unset -f ExecPrepTestsCore echo echo Preparing this window to run tests echo Setting up Exernal Environment Variables echo _TGTCPU - Target CPU echo BVT_ROOT - Root of tests to run echo CORE_RUN - Test host echo CORE_ROOT - Root of CLR drop. echo # Set $_TGTCPU based on the processor arch. In bash on an x64 linux machine, that will show up as x86_x64. # If so, then set to AMD64. Otherwise I386. if ! test $_TGTCPU then export _TGTCPU=`arch` if test $_TGTCPU = "x86_x64" then export _TGTCPU="AMD64" else export _TGTCPU="i386" fi fi # Set $BVT_ROOT based on current directory if ! test $BVT_ROOT then export BVT_ROOT=$PWD fi # Set $CORE_RUN based on current directory if ! test $CORE_RUN then if test -e $BVT_ROOT/Hosting/CoreClr/Activation/Host/TestHost.exe then export CORE_RUN=$BVT_ROOT/Hosting/CoreClr/Activation/Host/TestHost.exe else echo !!!ERROR: $BVT_ROOT/Hosting/CoreClr/Activation/Host/TestHost.exe does not exist. CORE_RUN not set. return 1 fi fi # Set $CORE_ROOT base to $PWD unless otherwise set. if ! test "$CORE_ROOT" then echo Warning. CORE_ROOT is not set at the moment. Setting it to $PWD export CORE_ROOT=$PWD fi # Report the current state of the environment echo _TGCPU is set to: $_TGTCPU echo BVT_ROOT is set to: $BVT_ROOT echo CORE_ROOT is set to: $CORE_ROOT echo CORE_RUN is set to $CORE_RUN echo return 0 } # This is explicitly so that we can RETURN and not exit this script. ExecPrepTestsCore $*
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/JIT/IL_Conformance/Old/Conformance_Base/bgt_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 {} .class public _bgt { .field public static float32 _inf .field public static float32 _min .field public static float32 _one .field public static float32 _zero .field public static float32 zero .field public static float32 one .field public static float32 max .field public static float32 inf .field public static float32 NaN .method public static void initialize() { .maxstack 10 ldc.r4 float32(0xFF800000) stsfld float32 _bgt::_inf ldc.r4 float32(0xFF7FFFFF) stsfld float32 _bgt::_min ldc.r4 float32(0xBF800000) stsfld float32 _bgt::_one ldc.r4 float32(0x80000000) stsfld float32 _bgt::_zero ldc.r4 float32(0x00000000) stsfld float32 _bgt::zero ldc.r4 float32(0x3F800000) stsfld float32 _bgt::one ldc.r4 float32(0x7F7FFFFF) stsfld float32 _bgt::max ldc.r4 float32(0x7F800000) stsfld float32 _bgt::inf ldc.r4 float32(0x7FC00000) stsfld float32 _bgt::NaN ret } .method public static int32 main(class [mscorlib]System.String[]) { .entrypoint .maxstack 10 call void _bgt::initialize() ldsfld float32 _bgt::_inf ldsfld float32 _bgt::_inf bgt FAIL ldsfld float32 _bgt::_inf ldsfld float32 _bgt::_min bgt FAIL ldsfld float32 _bgt::_inf ldsfld float32 _bgt::_one bgt FAIL ldsfld float32 _bgt::_inf ldsfld float32 _bgt::_zero bgt FAIL ldsfld float32 _bgt::_inf ldsfld float32 _bgt::zero bgt FAIL ldsfld float32 _bgt::_inf ldsfld float32 _bgt::one bgt FAIL ldsfld float32 _bgt::_inf ldsfld float32 _bgt::max bgt FAIL ldsfld float32 _bgt::_inf ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::_inf ldsfld float32 _bgt::NaN bgt FAIL ldsfld float32 _bgt::_min ldsfld float32 _bgt::_inf bgt B br FAIL B: ldsfld float32 _bgt::_min ldsfld float32 _bgt::_min bgt FAIL ldsfld float32 _bgt::_min ldsfld float32 _bgt::_one bgt FAIL ldsfld float32 _bgt::_min ldsfld float32 _bgt::_zero bgt FAIL ldsfld float32 _bgt::_min ldsfld float32 _bgt::zero bgt FAIL ldsfld float32 _bgt::_min ldsfld float32 _bgt::one bgt FAIL ldsfld float32 _bgt::_min ldsfld float32 _bgt::max bgt FAIL ldsfld float32 _bgt::_min ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::_min ldsfld float32 _bgt::NaN bgt FAIL ldsfld float32 _bgt::_one ldsfld float32 _bgt::_inf bgt D br FAIL D: ldsfld float32 _bgt::_one ldsfld float32 _bgt::_min bgt E br FAIL E: ldsfld float32 _bgt::_one ldsfld float32 _bgt::_one bgt FAIL ldsfld float32 _bgt::_one ldsfld float32 _bgt::_zero bgt FAIL ldsfld float32 _bgt::_one ldsfld float32 _bgt::zero bgt FAIL ldsfld float32 _bgt::_one ldsfld float32 _bgt::one bgt FAIL ldsfld float32 _bgt::_one ldsfld float32 _bgt::max bgt FAIL ldsfld float32 _bgt::_one ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::_one ldsfld float32 _bgt::NaN bgt FAIL ldsfld float32 _bgt::_zero ldsfld float32 _bgt::_inf bgt G br FAIL G: ldsfld float32 _bgt::_zero ldsfld float32 _bgt::_min bgt H br FAIL H: ldsfld float32 _bgt::_zero ldsfld float32 _bgt::_one bgt I br FAIL I: ldsfld float32 _bgt::_zero ldsfld float32 _bgt::_zero bgt FAIL ldsfld float32 _bgt::_zero ldsfld float32 _bgt::zero bgt FAIL ldsfld float32 _bgt::_zero ldsfld float32 _bgt::one bgt FAIL ldsfld float32 _bgt::_zero ldsfld float32 _bgt::max bgt FAIL ldsfld float32 _bgt::_zero ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::_zero ldsfld float32 _bgt::NaN bgt FAIL ldsfld float32 _bgt::zero ldsfld float32 _bgt::_inf bgt K br FAIL K: ldsfld float32 _bgt::zero ldsfld float32 _bgt::_min bgt L br FAIL L: ldsfld float32 _bgt::zero ldsfld float32 _bgt::_one bgt M br FAIL M: ldsfld float32 _bgt::zero ldsfld float32 _bgt::_zero bgt FAIL ldsfld float32 _bgt::zero ldsfld float32 _bgt::zero bgt FAIL ldsfld float32 _bgt::zero ldsfld float32 _bgt::one bgt FAIL ldsfld float32 _bgt::zero ldsfld float32 _bgt::max bgt FAIL ldsfld float32 _bgt::zero ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::zero ldsfld float32 _bgt::NaN bgt FAIL ldsfld float32 _bgt::one ldsfld float32 _bgt::_inf bgt O br FAIL O: ldsfld float32 _bgt::one ldsfld float32 _bgt::_min bgt P br FAIL P: ldsfld float32 _bgt::one ldsfld float32 _bgt::_one bgt Q br FAIL Q: ldsfld float32 _bgt::one ldsfld float32 _bgt::_zero bgt R br FAIL R: ldsfld float32 _bgt::one ldsfld float32 _bgt::zero bgt S br FAIL S: ldsfld float32 _bgt::one ldsfld float32 _bgt::one bgt FAIL ldsfld float32 _bgt::one ldsfld float32 _bgt::max bgt FAIL ldsfld float32 _bgt::one ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::one ldsfld float32 _bgt::NaN bgt FAIL ldsfld float32 _bgt::max ldsfld float32 _bgt::_inf bgt U br FAIL U: ldsfld float32 _bgt::max ldsfld float32 _bgt::_min bgt V br FAIL V: ldsfld float32 _bgt::max ldsfld float32 _bgt::_one bgt W br FAIL W: ldsfld float32 _bgt::max ldsfld float32 _bgt::_zero bgt X br FAIL X: ldsfld float32 _bgt::max ldsfld float32 _bgt::zero bgt Y br FAIL Y: ldsfld float32 _bgt::max ldsfld float32 _bgt::one bgt Z br FAIL Z: ldsfld float32 _bgt::max ldsfld float32 _bgt::max bgt FAIL ldsfld float32 _bgt::max ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::max ldsfld float32 _bgt::NaN bgt FAIL ldsfld float32 _bgt::inf ldsfld float32 _bgt::_inf bgt BB br FAIL BB: ldsfld float32 _bgt::inf ldsfld float32 _bgt::_min bgt CC br FAIL CC: ldsfld float32 _bgt::inf ldsfld float32 _bgt::_one bgt DD br FAIL DD: ldsfld float32 _bgt::inf ldsfld float32 _bgt::_zero bgt EE br FAIL EE: ldsfld float32 _bgt::inf ldsfld float32 _bgt::zero bgt FF br FAIL FF: ldsfld float32 _bgt::inf ldsfld float32 _bgt::one bgt GG br FAIL GG: ldsfld float32 _bgt::inf ldsfld float32 _bgt::max bgt HH br FAIL HH: ldsfld float32 _bgt::inf ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::inf ldsfld float32 _bgt::NaN bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::_inf bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::_min bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::_one bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::_zero bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::zero bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::one bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::max bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::NaN bgt FAIL br BACKCHECK TOPASS: br PASS BACKCHECK: ldc.r4 0x1 ldc.r4 0x0 bgt TOPASS br FAIL PASS: ldc.i4 100 ret FAIL: ldc.i4 0x0 ret } } .assembly bgt_r4{}
// 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 {} .class public _bgt { .field public static float32 _inf .field public static float32 _min .field public static float32 _one .field public static float32 _zero .field public static float32 zero .field public static float32 one .field public static float32 max .field public static float32 inf .field public static float32 NaN .method public static void initialize() { .maxstack 10 ldc.r4 float32(0xFF800000) stsfld float32 _bgt::_inf ldc.r4 float32(0xFF7FFFFF) stsfld float32 _bgt::_min ldc.r4 float32(0xBF800000) stsfld float32 _bgt::_one ldc.r4 float32(0x80000000) stsfld float32 _bgt::_zero ldc.r4 float32(0x00000000) stsfld float32 _bgt::zero ldc.r4 float32(0x3F800000) stsfld float32 _bgt::one ldc.r4 float32(0x7F7FFFFF) stsfld float32 _bgt::max ldc.r4 float32(0x7F800000) stsfld float32 _bgt::inf ldc.r4 float32(0x7FC00000) stsfld float32 _bgt::NaN ret } .method public static int32 main(class [mscorlib]System.String[]) { .entrypoint .maxstack 10 call void _bgt::initialize() ldsfld float32 _bgt::_inf ldsfld float32 _bgt::_inf bgt FAIL ldsfld float32 _bgt::_inf ldsfld float32 _bgt::_min bgt FAIL ldsfld float32 _bgt::_inf ldsfld float32 _bgt::_one bgt FAIL ldsfld float32 _bgt::_inf ldsfld float32 _bgt::_zero bgt FAIL ldsfld float32 _bgt::_inf ldsfld float32 _bgt::zero bgt FAIL ldsfld float32 _bgt::_inf ldsfld float32 _bgt::one bgt FAIL ldsfld float32 _bgt::_inf ldsfld float32 _bgt::max bgt FAIL ldsfld float32 _bgt::_inf ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::_inf ldsfld float32 _bgt::NaN bgt FAIL ldsfld float32 _bgt::_min ldsfld float32 _bgt::_inf bgt B br FAIL B: ldsfld float32 _bgt::_min ldsfld float32 _bgt::_min bgt FAIL ldsfld float32 _bgt::_min ldsfld float32 _bgt::_one bgt FAIL ldsfld float32 _bgt::_min ldsfld float32 _bgt::_zero bgt FAIL ldsfld float32 _bgt::_min ldsfld float32 _bgt::zero bgt FAIL ldsfld float32 _bgt::_min ldsfld float32 _bgt::one bgt FAIL ldsfld float32 _bgt::_min ldsfld float32 _bgt::max bgt FAIL ldsfld float32 _bgt::_min ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::_min ldsfld float32 _bgt::NaN bgt FAIL ldsfld float32 _bgt::_one ldsfld float32 _bgt::_inf bgt D br FAIL D: ldsfld float32 _bgt::_one ldsfld float32 _bgt::_min bgt E br FAIL E: ldsfld float32 _bgt::_one ldsfld float32 _bgt::_one bgt FAIL ldsfld float32 _bgt::_one ldsfld float32 _bgt::_zero bgt FAIL ldsfld float32 _bgt::_one ldsfld float32 _bgt::zero bgt FAIL ldsfld float32 _bgt::_one ldsfld float32 _bgt::one bgt FAIL ldsfld float32 _bgt::_one ldsfld float32 _bgt::max bgt FAIL ldsfld float32 _bgt::_one ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::_one ldsfld float32 _bgt::NaN bgt FAIL ldsfld float32 _bgt::_zero ldsfld float32 _bgt::_inf bgt G br FAIL G: ldsfld float32 _bgt::_zero ldsfld float32 _bgt::_min bgt H br FAIL H: ldsfld float32 _bgt::_zero ldsfld float32 _bgt::_one bgt I br FAIL I: ldsfld float32 _bgt::_zero ldsfld float32 _bgt::_zero bgt FAIL ldsfld float32 _bgt::_zero ldsfld float32 _bgt::zero bgt FAIL ldsfld float32 _bgt::_zero ldsfld float32 _bgt::one bgt FAIL ldsfld float32 _bgt::_zero ldsfld float32 _bgt::max bgt FAIL ldsfld float32 _bgt::_zero ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::_zero ldsfld float32 _bgt::NaN bgt FAIL ldsfld float32 _bgt::zero ldsfld float32 _bgt::_inf bgt K br FAIL K: ldsfld float32 _bgt::zero ldsfld float32 _bgt::_min bgt L br FAIL L: ldsfld float32 _bgt::zero ldsfld float32 _bgt::_one bgt M br FAIL M: ldsfld float32 _bgt::zero ldsfld float32 _bgt::_zero bgt FAIL ldsfld float32 _bgt::zero ldsfld float32 _bgt::zero bgt FAIL ldsfld float32 _bgt::zero ldsfld float32 _bgt::one bgt FAIL ldsfld float32 _bgt::zero ldsfld float32 _bgt::max bgt FAIL ldsfld float32 _bgt::zero ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::zero ldsfld float32 _bgt::NaN bgt FAIL ldsfld float32 _bgt::one ldsfld float32 _bgt::_inf bgt O br FAIL O: ldsfld float32 _bgt::one ldsfld float32 _bgt::_min bgt P br FAIL P: ldsfld float32 _bgt::one ldsfld float32 _bgt::_one bgt Q br FAIL Q: ldsfld float32 _bgt::one ldsfld float32 _bgt::_zero bgt R br FAIL R: ldsfld float32 _bgt::one ldsfld float32 _bgt::zero bgt S br FAIL S: ldsfld float32 _bgt::one ldsfld float32 _bgt::one bgt FAIL ldsfld float32 _bgt::one ldsfld float32 _bgt::max bgt FAIL ldsfld float32 _bgt::one ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::one ldsfld float32 _bgt::NaN bgt FAIL ldsfld float32 _bgt::max ldsfld float32 _bgt::_inf bgt U br FAIL U: ldsfld float32 _bgt::max ldsfld float32 _bgt::_min bgt V br FAIL V: ldsfld float32 _bgt::max ldsfld float32 _bgt::_one bgt W br FAIL W: ldsfld float32 _bgt::max ldsfld float32 _bgt::_zero bgt X br FAIL X: ldsfld float32 _bgt::max ldsfld float32 _bgt::zero bgt Y br FAIL Y: ldsfld float32 _bgt::max ldsfld float32 _bgt::one bgt Z br FAIL Z: ldsfld float32 _bgt::max ldsfld float32 _bgt::max bgt FAIL ldsfld float32 _bgt::max ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::max ldsfld float32 _bgt::NaN bgt FAIL ldsfld float32 _bgt::inf ldsfld float32 _bgt::_inf bgt BB br FAIL BB: ldsfld float32 _bgt::inf ldsfld float32 _bgt::_min bgt CC br FAIL CC: ldsfld float32 _bgt::inf ldsfld float32 _bgt::_one bgt DD br FAIL DD: ldsfld float32 _bgt::inf ldsfld float32 _bgt::_zero bgt EE br FAIL EE: ldsfld float32 _bgt::inf ldsfld float32 _bgt::zero bgt FF br FAIL FF: ldsfld float32 _bgt::inf ldsfld float32 _bgt::one bgt GG br FAIL GG: ldsfld float32 _bgt::inf ldsfld float32 _bgt::max bgt HH br FAIL HH: ldsfld float32 _bgt::inf ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::inf ldsfld float32 _bgt::NaN bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::_inf bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::_min bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::_one bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::_zero bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::zero bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::one bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::max bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::inf bgt FAIL ldsfld float32 _bgt::NaN ldsfld float32 _bgt::NaN bgt FAIL br BACKCHECK TOPASS: br PASS BACKCHECK: ldc.r4 0x1 ldc.r4 0x0 bgt TOPASS br FAIL PASS: ldc.i4 100 ret FAIL: ldc.i4 0x0 ret } } .assembly bgt_r4{}
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeBuffer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================ ** ** Purpose: Unsafe code that uses pointers should use ** SafeBuffer to fix subtle lifetime problems with the ** underlying resource. ** ===========================================================*/ // Design points: // *) Avoid handle-recycling problems (including ones triggered via // resurrection attacks) for all accesses via pointers. This requires tying // together the lifetime of the unmanaged resource with the code that reads // from that resource, in a package that uses synchronization to enforce // the correct semantics during finalization. We're using SafeHandle's // ref count as a gate on whether the pointer can be dereferenced because that // controls the lifetime of the resource. // // *) Keep the penalties for using this class small, both in terms of space // and time. Having multiple threads reading from a memory mapped file // will already require 2 additional interlocked operations. If we add in // a "current position" concept, that requires additional space in memory and // synchronization. Since the position in memory is often (but not always) // something that can be stored on the stack, we can save some memory by // excluding it from this object. However, avoiding the need for // synchronization is a more significant win. This design allows multiple // threads to read and write memory simultaneously without locks (as long as // you don't write to a region of memory that overlaps with what another // thread is accessing). // // *) Space-wise, we use the following memory, including SafeHandle's fields: // Object Header MT* handle int bool bool <2 pad bytes> length // On 32 bit platforms: 24 bytes. On 64 bit platforms: 40 bytes. // (We can safe 4 bytes on x86 only by shrinking SafeHandle) // // *) Wrapping a SafeHandle would have been a nice solution, but without an // ordering between critical finalizable objects, it would have required // changes to each SafeHandle subclass to opt in to being usable from a // SafeBuffer (or some clever exposure of SafeHandle's state fields and a // way of forcing ReleaseHandle to run even after the SafeHandle has been // finalized with a ref count > 1). We can use less memory and create fewer // objects by simply inserting a SafeBuffer into the class hierarchy. // // *) In an ideal world, we could get marshaling support for SafeBuffer that // would allow us to annotate a P/Invoke declaration, saying this parameter // specifies the length of the buffer, and the units of that length are X. // P/Invoke would then pass that size parameter to SafeBuffer. // [DllImport(...)] // static extern SafeMemoryHandle AllocCharBuffer(int numChars); // If we could put an attribute on the SafeMemoryHandle saying numChars is // the element length, and it must be multiplied by 2 to get to the byte // length, we can simplify the usage model for SafeBuffer. // // *) This class could benefit from a constraint saying T is a value type // containing no GC references. // Implementation notes: // *) The Initialize method must be called before you use any instance of // a SafeBuffer. To avoid race conditions when storing SafeBuffers in statics, // you either need to take a lock when publishing the SafeBuffer, or you // need to create a local, initialize the SafeBuffer, then assign to the // static variable (perhaps using Interlocked.CompareExchange). Of course, // assignments in a static class constructor are under a lock implicitly. using System.Runtime.CompilerServices; using Microsoft.Win32.SafeHandles; namespace System.Runtime.InteropServices { public abstract unsafe class SafeBuffer : SafeHandleZeroOrMinusOneIsInvalid { private nuint _numBytes; protected SafeBuffer(bool ownsHandle) : base(ownsHandle) { _numBytes = Uninitialized; } private static nuint Uninitialized => nuint.MaxValue; /// <summary> /// Specifies the size of the region of memory, in bytes. Must be /// called before using the SafeBuffer. /// </summary> /// <param name="numBytes">Number of valid bytes in memory.</param> [CLSCompliant(false)] public void Initialize(ulong numBytes) { if (IntPtr.Size == 4 && numBytes > uint.MaxValue) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_AddressSpace); if (numBytes >= (ulong)Uninitialized) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_UIntPtrMax); _numBytes = (nuint)numBytes; } /// <summary> /// Specifies the size of the region in memory, as the number of /// elements in an array. Must be called before using the SafeBuffer. /// </summary> [CLSCompliant(false)] public void Initialize(uint numElements, uint sizeOfEachElement) { Initialize((ulong)numElements * sizeOfEachElement); } /// <summary> /// Specifies the size of the region in memory, as the number of /// elements in an array. Must be called before using the SafeBuffer. /// </summary> [CLSCompliant(false)] public void Initialize<T>(uint numElements) where T : struct { Initialize(numElements, AlignedSizeOf<T>()); } // Callers should ensure that they check whether the pointer ref param // is null when AcquirePointer returns. If it is not null, they must // call ReleasePointer. This method calls DangerousAddRef // & exposes the pointer. Unlike Read, it does not alter the "current // position" of the pointer. Here's how to use it: // // byte* pointer = null; // try { // safeBuffer.AcquirePointer(ref pointer); // // Use pointer here, with your own bounds checking // } // finally { // if (pointer != null) // safeBuffer.ReleasePointer(); // } // // Note: If you cast this byte* to a T*, you have to worry about // whether your pointer is aligned. Additionally, you must take // responsibility for all bounds checking with this pointer. /// <summary> /// Obtain the pointer from a SafeBuffer for a block of code, /// with the express responsibility for bounds checking and calling /// ReleasePointer later to ensure the pointer can be freed later. /// This method either completes successfully or throws an exception /// and returns with pointer set to null. /// </summary> /// <param name="pointer">A byte*, passed by reference, to receive /// the pointer from within the SafeBuffer. You must set /// pointer to null before calling this method.</param> [CLSCompliant(false)] public void AcquirePointer(ref byte* pointer) { if (_numBytes == Uninitialized) throw NotInitialized(); #pragma warning disable IDE0059 // https://github.com/dotnet/roslyn/issues/42761 pointer = null; #pragma warning restore IDE0059 bool junk = false; DangerousAddRef(ref junk); pointer = (byte*)handle; } public void ReleasePointer() { if (_numBytes == Uninitialized) throw NotInitialized(); DangerousRelease(); } /// <summary> /// Read a value type from memory at the given offset. This is /// equivalent to: return *(T*)(bytePtr + byteOffset); /// </summary> /// <typeparam name="T">The value type to read</typeparam> /// <param name="byteOffset">Where to start reading from memory. You /// may have to consider alignment.</param> /// <returns>An instance of T read from memory.</returns> [CLSCompliant(false)] public T Read<T>(ulong byteOffset) where T : struct { if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = SizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, sizeofT); // return *(T*) (_ptr + byteOffset); T value = default; bool mustCallRelease = false; try { DangerousAddRef(ref mustCallRelease); Buffer.Memmove(ref Unsafe.As<T, byte>(ref value), ref *ptr, sizeofT); } finally { if (mustCallRelease) DangerousRelease(); } return value; } /// <summary> /// Reads the specified number of value types from memory starting at the offset, and writes them into an array starting at the index.</summary> /// <typeparam name="T">The value type to read.</typeparam> /// <param name="byteOffset">The location from which to start reading.</param> /// <param name="array">The output array to write to.</param> /// <param name="index">The location in the output array to begin writing to.</param> /// <param name="count">The number of value types to read from the input array and to write to the output array.</param> [CLSCompliant(false)] public void ReadArray<T>(ulong byteOffset, T[] array!!, int index, int count) where T : struct { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); ReadSpan(byteOffset, new Span<T>(array, index, count)); } /// <summary> /// Reads value types from memory starting at the offset, and writes them into a span. The number of value types that will be read is determined by the length of the span.</summary> /// <typeparam name="T">The value type to read.</typeparam> /// <param name="byteOffset">The location from which to start reading.</param> /// <param name="buffer">The output span to write to.</param> [CLSCompliant(false)] public void ReadSpan<T>(ulong byteOffset, Span<T> buffer) where T : struct { if (_numBytes == Uninitialized) throw NotInitialized(); uint alignedSizeofT = AlignedSizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, checked((nuint)(alignedSizeofT * buffer.Length))); bool mustCallRelease = false; try { DangerousAddRef(ref mustCallRelease); ref T structure = ref MemoryMarshal.GetReference(buffer); for (int i = 0; i < buffer.Length; i++) Buffer.Memmove(ref Unsafe.Add(ref structure, i), ref Unsafe.AsRef<T>(ptr + alignedSizeofT * i), 1); } finally { if (mustCallRelease) DangerousRelease(); } } /// <summary> /// Write a value type to memory at the given offset. This is /// equivalent to: *(T*)(bytePtr + byteOffset) = value; /// </summary> /// <typeparam name="T">The type of the value type to write to memory.</typeparam> /// <param name="byteOffset">The location in memory to write to. You /// may have to consider alignment.</param> /// <param name="value">The value type to write to memory.</param> [CLSCompliant(false)] public void Write<T>(ulong byteOffset, T value) where T : struct { if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = SizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, sizeofT); // *((T*) (_ptr + byteOffset)) = value; bool mustCallRelease = false; try { DangerousAddRef(ref mustCallRelease); Buffer.Memmove(ref *ptr, ref Unsafe.As<T, byte>(ref value), sizeofT); } finally { if (mustCallRelease) DangerousRelease(); } } /// <summary> /// Writes the specified number of value types to a memory location by reading bytes starting from the specified location in the input array. /// </summary> /// <typeparam name="T">The value type to write.</typeparam> /// <param name="byteOffset">The location in memory to write to.</param> /// <param name="array">The input array.</param> /// <param name="index">The offset in the array to start reading from.</param> /// <param name="count">The number of value types to write.</param> [CLSCompliant(false)] public void WriteArray<T>(ulong byteOffset, T[] array!!, int index, int count) where T : struct { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); WriteSpan(byteOffset, new ReadOnlySpan<T>(array, index, count)); } /// <summary> /// Writes the value types from a read-only span to a memory location. /// </summary> /// <typeparam name="T">The value type to write.</typeparam> /// <param name="byteOffset">The location in memory to write to.</param> /// <param name="data">The input span.</param> [CLSCompliant(false)] public void WriteSpan<T>(ulong byteOffset, ReadOnlySpan<T> data) where T : struct { if (_numBytes == Uninitialized) throw NotInitialized(); uint alignedSizeofT = AlignedSizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, checked((nuint)(alignedSizeofT * data.Length))); bool mustCallRelease = false; try { DangerousAddRef(ref mustCallRelease); ref T structure = ref MemoryMarshal.GetReference(data); for (int i = 0; i < data.Length; i++) Buffer.Memmove(ref Unsafe.AsRef<T>(ptr + alignedSizeofT * i), ref Unsafe.Add(ref structure, i), 1); } finally { if (mustCallRelease) DangerousRelease(); } } /// <summary> /// Returns the number of bytes in the memory region. /// </summary> [CLSCompliant(false)] public ulong ByteLength { get { if (_numBytes == Uninitialized) throw NotInitialized(); return _numBytes; } } /* No indexer. The perf would be misleadingly bad. People should use * AcquirePointer and ReleasePointer instead. */ private void SpaceCheck(byte* ptr, nuint sizeInBytes) { if (_numBytes < sizeInBytes) NotEnoughRoom(); if ((ulong)(ptr - (byte*)handle) > (_numBytes - sizeInBytes)) NotEnoughRoom(); } private static void NotEnoughRoom() { throw new ArgumentException(SR.Arg_BufferTooSmall); } private static InvalidOperationException NotInitialized() { return new InvalidOperationException(SR.InvalidOperation_MustCallInitialize); } /// <summary> /// Returns the size that SafeBuffer (and hence, UnmanagedMemoryAccessor) reserves in the unmanaged buffer for each element of an array of T. This is not the same /// value that sizeof(T) returns! Since the primary use case is to parse memory mapped files, we cannot change this algorithm as this defines a de-facto serialization format. /// Throws if T contains GC references. /// </summary> internal static uint AlignedSizeOf<T>() where T : struct { uint size = SizeOf<T>(); if (size == 1 || size == 2) { return size; } return (uint)((size + 3) & (~3)); } /// <summary> /// Returns same value as sizeof(T) but throws if T contains GC references. /// </summary> internal static uint SizeOf<T>() where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) throw new ArgumentException(SR.Argument_NeedStructWithNoRefs); return (uint)Unsafe.SizeOf<T>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================ ** ** Purpose: Unsafe code that uses pointers should use ** SafeBuffer to fix subtle lifetime problems with the ** underlying resource. ** ===========================================================*/ // Design points: // *) Avoid handle-recycling problems (including ones triggered via // resurrection attacks) for all accesses via pointers. This requires tying // together the lifetime of the unmanaged resource with the code that reads // from that resource, in a package that uses synchronization to enforce // the correct semantics during finalization. We're using SafeHandle's // ref count as a gate on whether the pointer can be dereferenced because that // controls the lifetime of the resource. // // *) Keep the penalties for using this class small, both in terms of space // and time. Having multiple threads reading from a memory mapped file // will already require 2 additional interlocked operations. If we add in // a "current position" concept, that requires additional space in memory and // synchronization. Since the position in memory is often (but not always) // something that can be stored on the stack, we can save some memory by // excluding it from this object. However, avoiding the need for // synchronization is a more significant win. This design allows multiple // threads to read and write memory simultaneously without locks (as long as // you don't write to a region of memory that overlaps with what another // thread is accessing). // // *) Space-wise, we use the following memory, including SafeHandle's fields: // Object Header MT* handle int bool bool <2 pad bytes> length // On 32 bit platforms: 24 bytes. On 64 bit platforms: 40 bytes. // (We can safe 4 bytes on x86 only by shrinking SafeHandle) // // *) Wrapping a SafeHandle would have been a nice solution, but without an // ordering between critical finalizable objects, it would have required // changes to each SafeHandle subclass to opt in to being usable from a // SafeBuffer (or some clever exposure of SafeHandle's state fields and a // way of forcing ReleaseHandle to run even after the SafeHandle has been // finalized with a ref count > 1). We can use less memory and create fewer // objects by simply inserting a SafeBuffer into the class hierarchy. // // *) In an ideal world, we could get marshaling support for SafeBuffer that // would allow us to annotate a P/Invoke declaration, saying this parameter // specifies the length of the buffer, and the units of that length are X. // P/Invoke would then pass that size parameter to SafeBuffer. // [DllImport(...)] // static extern SafeMemoryHandle AllocCharBuffer(int numChars); // If we could put an attribute on the SafeMemoryHandle saying numChars is // the element length, and it must be multiplied by 2 to get to the byte // length, we can simplify the usage model for SafeBuffer. // // *) This class could benefit from a constraint saying T is a value type // containing no GC references. // Implementation notes: // *) The Initialize method must be called before you use any instance of // a SafeBuffer. To avoid race conditions when storing SafeBuffers in statics, // you either need to take a lock when publishing the SafeBuffer, or you // need to create a local, initialize the SafeBuffer, then assign to the // static variable (perhaps using Interlocked.CompareExchange). Of course, // assignments in a static class constructor are under a lock implicitly. using System.Runtime.CompilerServices; using Microsoft.Win32.SafeHandles; namespace System.Runtime.InteropServices { public abstract unsafe class SafeBuffer : SafeHandleZeroOrMinusOneIsInvalid { private nuint _numBytes; protected SafeBuffer(bool ownsHandle) : base(ownsHandle) { _numBytes = Uninitialized; } private static nuint Uninitialized => nuint.MaxValue; /// <summary> /// Specifies the size of the region of memory, in bytes. Must be /// called before using the SafeBuffer. /// </summary> /// <param name="numBytes">Number of valid bytes in memory.</param> [CLSCompliant(false)] public void Initialize(ulong numBytes) { if (IntPtr.Size == 4 && numBytes > uint.MaxValue) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_AddressSpace); if (numBytes >= (ulong)Uninitialized) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_UIntPtrMax); _numBytes = (nuint)numBytes; } /// <summary> /// Specifies the size of the region in memory, as the number of /// elements in an array. Must be called before using the SafeBuffer. /// </summary> [CLSCompliant(false)] public void Initialize(uint numElements, uint sizeOfEachElement) { Initialize((ulong)numElements * sizeOfEachElement); } /// <summary> /// Specifies the size of the region in memory, as the number of /// elements in an array. Must be called before using the SafeBuffer. /// </summary> [CLSCompliant(false)] public void Initialize<T>(uint numElements) where T : struct { Initialize(numElements, AlignedSizeOf<T>()); } // Callers should ensure that they check whether the pointer ref param // is null when AcquirePointer returns. If it is not null, they must // call ReleasePointer. This method calls DangerousAddRef // & exposes the pointer. Unlike Read, it does not alter the "current // position" of the pointer. Here's how to use it: // // byte* pointer = null; // try { // safeBuffer.AcquirePointer(ref pointer); // // Use pointer here, with your own bounds checking // } // finally { // if (pointer != null) // safeBuffer.ReleasePointer(); // } // // Note: If you cast this byte* to a T*, you have to worry about // whether your pointer is aligned. Additionally, you must take // responsibility for all bounds checking with this pointer. /// <summary> /// Obtain the pointer from a SafeBuffer for a block of code, /// with the express responsibility for bounds checking and calling /// ReleasePointer later to ensure the pointer can be freed later. /// This method either completes successfully or throws an exception /// and returns with pointer set to null. /// </summary> /// <param name="pointer">A byte*, passed by reference, to receive /// the pointer from within the SafeBuffer. You must set /// pointer to null before calling this method.</param> [CLSCompliant(false)] public void AcquirePointer(ref byte* pointer) { if (_numBytes == Uninitialized) throw NotInitialized(); #pragma warning disable IDE0059 // https://github.com/dotnet/roslyn/issues/42761 pointer = null; #pragma warning restore IDE0059 bool junk = false; DangerousAddRef(ref junk); pointer = (byte*)handle; } public void ReleasePointer() { if (_numBytes == Uninitialized) throw NotInitialized(); DangerousRelease(); } /// <summary> /// Read a value type from memory at the given offset. This is /// equivalent to: return *(T*)(bytePtr + byteOffset); /// </summary> /// <typeparam name="T">The value type to read</typeparam> /// <param name="byteOffset">Where to start reading from memory. You /// may have to consider alignment.</param> /// <returns>An instance of T read from memory.</returns> [CLSCompliant(false)] public T Read<T>(ulong byteOffset) where T : struct { if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = SizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, sizeofT); // return *(T*) (_ptr + byteOffset); T value = default; bool mustCallRelease = false; try { DangerousAddRef(ref mustCallRelease); Buffer.Memmove(ref Unsafe.As<T, byte>(ref value), ref *ptr, sizeofT); } finally { if (mustCallRelease) DangerousRelease(); } return value; } /// <summary> /// Reads the specified number of value types from memory starting at the offset, and writes them into an array starting at the index.</summary> /// <typeparam name="T">The value type to read.</typeparam> /// <param name="byteOffset">The location from which to start reading.</param> /// <param name="array">The output array to write to.</param> /// <param name="index">The location in the output array to begin writing to.</param> /// <param name="count">The number of value types to read from the input array and to write to the output array.</param> [CLSCompliant(false)] public void ReadArray<T>(ulong byteOffset, T[] array!!, int index, int count) where T : struct { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); ReadSpan(byteOffset, new Span<T>(array, index, count)); } /// <summary> /// Reads value types from memory starting at the offset, and writes them into a span. The number of value types that will be read is determined by the length of the span.</summary> /// <typeparam name="T">The value type to read.</typeparam> /// <param name="byteOffset">The location from which to start reading.</param> /// <param name="buffer">The output span to write to.</param> [CLSCompliant(false)] public void ReadSpan<T>(ulong byteOffset, Span<T> buffer) where T : struct { if (_numBytes == Uninitialized) throw NotInitialized(); uint alignedSizeofT = AlignedSizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, checked((nuint)(alignedSizeofT * buffer.Length))); bool mustCallRelease = false; try { DangerousAddRef(ref mustCallRelease); ref T structure = ref MemoryMarshal.GetReference(buffer); for (int i = 0; i < buffer.Length; i++) Buffer.Memmove(ref Unsafe.Add(ref structure, i), ref Unsafe.AsRef<T>(ptr + alignedSizeofT * i), 1); } finally { if (mustCallRelease) DangerousRelease(); } } /// <summary> /// Write a value type to memory at the given offset. This is /// equivalent to: *(T*)(bytePtr + byteOffset) = value; /// </summary> /// <typeparam name="T">The type of the value type to write to memory.</typeparam> /// <param name="byteOffset">The location in memory to write to. You /// may have to consider alignment.</param> /// <param name="value">The value type to write to memory.</param> [CLSCompliant(false)] public void Write<T>(ulong byteOffset, T value) where T : struct { if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = SizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, sizeofT); // *((T*) (_ptr + byteOffset)) = value; bool mustCallRelease = false; try { DangerousAddRef(ref mustCallRelease); Buffer.Memmove(ref *ptr, ref Unsafe.As<T, byte>(ref value), sizeofT); } finally { if (mustCallRelease) DangerousRelease(); } } /// <summary> /// Writes the specified number of value types to a memory location by reading bytes starting from the specified location in the input array. /// </summary> /// <typeparam name="T">The value type to write.</typeparam> /// <param name="byteOffset">The location in memory to write to.</param> /// <param name="array">The input array.</param> /// <param name="index">The offset in the array to start reading from.</param> /// <param name="count">The number of value types to write.</param> [CLSCompliant(false)] public void WriteArray<T>(ulong byteOffset, T[] array!!, int index, int count) where T : struct { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); WriteSpan(byteOffset, new ReadOnlySpan<T>(array, index, count)); } /// <summary> /// Writes the value types from a read-only span to a memory location. /// </summary> /// <typeparam name="T">The value type to write.</typeparam> /// <param name="byteOffset">The location in memory to write to.</param> /// <param name="data">The input span.</param> [CLSCompliant(false)] public void WriteSpan<T>(ulong byteOffset, ReadOnlySpan<T> data) where T : struct { if (_numBytes == Uninitialized) throw NotInitialized(); uint alignedSizeofT = AlignedSizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, checked((nuint)(alignedSizeofT * data.Length))); bool mustCallRelease = false; try { DangerousAddRef(ref mustCallRelease); ref T structure = ref MemoryMarshal.GetReference(data); for (int i = 0; i < data.Length; i++) Buffer.Memmove(ref Unsafe.AsRef<T>(ptr + alignedSizeofT * i), ref Unsafe.Add(ref structure, i), 1); } finally { if (mustCallRelease) DangerousRelease(); } } /// <summary> /// Returns the number of bytes in the memory region. /// </summary> [CLSCompliant(false)] public ulong ByteLength { get { if (_numBytes == Uninitialized) throw NotInitialized(); return _numBytes; } } /* No indexer. The perf would be misleadingly bad. People should use * AcquirePointer and ReleasePointer instead. */ private void SpaceCheck(byte* ptr, nuint sizeInBytes) { if (_numBytes < sizeInBytes) NotEnoughRoom(); if ((ulong)(ptr - (byte*)handle) > (_numBytes - sizeInBytes)) NotEnoughRoom(); } private static void NotEnoughRoom() { throw new ArgumentException(SR.Arg_BufferTooSmall); } private static InvalidOperationException NotInitialized() { return new InvalidOperationException(SR.InvalidOperation_MustCallInitialize); } /// <summary> /// Returns the size that SafeBuffer (and hence, UnmanagedMemoryAccessor) reserves in the unmanaged buffer for each element of an array of T. This is not the same /// value that sizeof(T) returns! Since the primary use case is to parse memory mapped files, we cannot change this algorithm as this defines a de-facto serialization format. /// Throws if T contains GC references. /// </summary> internal static uint AlignedSizeOf<T>() where T : struct { uint size = SizeOf<T>(); if (size == 1 || size == 2) { return size; } return (uint)((size + 3) & (~3)); } /// <summary> /// Returns same value as sizeof(T) but throws if T contains GC references. /// </summary> internal static uint SizeOf<T>() where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) throw new ArgumentException(SR.Argument_NeedStructWithNoRefs); return (uint)Unsafe.SizeOf<T>(); } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/System.Text.Json/Common/JsonKnownNamingPolicy.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 { /// <summary> /// The <see cref="Json.JsonNamingPolicy"/> to be used at run time. /// </summary> #if BUILDING_SOURCE_GENERATOR internal #else public #endif enum JsonKnownNamingPolicy { /// <summary> /// Specifies that JSON property names should not be converted. /// </summary> Unspecified = 0, /// <summary> /// Specifies that the built-in <see cref="Json.JsonNamingPolicy.CamelCase"/> be used to convert JSON property names. /// </summary> CamelCase = 1 } }
// 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 { /// <summary> /// The <see cref="Json.JsonNamingPolicy"/> to be used at run time. /// </summary> #if BUILDING_SOURCE_GENERATOR internal #else public #endif enum JsonKnownNamingPolicy { /// <summary> /// Specifies that JSON property names should not be converted. /// </summary> Unspecified = 0, /// <summary> /// Specifies that the built-in <see cref="Json.JsonNamingPolicy.CamelCase"/> be used to convert JSON property names. /// </summary> CamelCase = 1 } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/JIT/CodeGenBringUpTests/LocallocCnstB117_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="LocallocCnstB117.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="LocallocCnstB117.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/libraries/Common/src/System/Net/Http/aspnetcore/Http2/Hpack/Huffman.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable enable using System.Diagnostics; using System.Threading; namespace System.Net.Http.HPack { internal static class Huffman { // HPack static huffman code. see: https://httpwg.org/specs/rfc7541.html#huffman.code // Stored into two tables to optimize its initialization and memory consumption. private static readonly uint[] s_encodingTableCodes = new uint[257] { 0b11111111_11000000_00000000_00000000, 0b11111111_11111111_10110000_00000000, 0b11111111_11111111_11111110_00100000, 0b11111111_11111111_11111110_00110000, 0b11111111_11111111_11111110_01000000, 0b11111111_11111111_11111110_01010000, 0b11111111_11111111_11111110_01100000, 0b11111111_11111111_11111110_01110000, 0b11111111_11111111_11111110_10000000, 0b11111111_11111111_11101010_00000000, 0b11111111_11111111_11111111_11110000, 0b11111111_11111111_11111110_10010000, 0b11111111_11111111_11111110_10100000, 0b11111111_11111111_11111111_11110100, 0b11111111_11111111_11111110_10110000, 0b11111111_11111111_11111110_11000000, 0b11111111_11111111_11111110_11010000, 0b11111111_11111111_11111110_11100000, 0b11111111_11111111_11111110_11110000, 0b11111111_11111111_11111111_00000000, 0b11111111_11111111_11111111_00010000, 0b11111111_11111111_11111111_00100000, 0b11111111_11111111_11111111_11111000, 0b11111111_11111111_11111111_00110000, 0b11111111_11111111_11111111_01000000, 0b11111111_11111111_11111111_01010000, 0b11111111_11111111_11111111_01100000, 0b11111111_11111111_11111111_01110000, 0b11111111_11111111_11111111_10000000, 0b11111111_11111111_11111111_10010000, 0b11111111_11111111_11111111_10100000, 0b11111111_11111111_11111111_10110000, 0b01010000_00000000_00000000_00000000, 0b11111110_00000000_00000000_00000000, 0b11111110_01000000_00000000_00000000, 0b11111111_10100000_00000000_00000000, 0b11111111_11001000_00000000_00000000, 0b01010100_00000000_00000000_00000000, 0b11111000_00000000_00000000_00000000, 0b11111111_01000000_00000000_00000000, 0b11111110_10000000_00000000_00000000, 0b11111110_11000000_00000000_00000000, 0b11111001_00000000_00000000_00000000, 0b11111111_01100000_00000000_00000000, 0b11111010_00000000_00000000_00000000, 0b01011000_00000000_00000000_00000000, 0b01011100_00000000_00000000_00000000, 0b01100000_00000000_00000000_00000000, 0b00000000_00000000_00000000_00000000, 0b00001000_00000000_00000000_00000000, 0b00010000_00000000_00000000_00000000, 0b01100100_00000000_00000000_00000000, 0b01101000_00000000_00000000_00000000, 0b01101100_00000000_00000000_00000000, 0b01110000_00000000_00000000_00000000, 0b01110100_00000000_00000000_00000000, 0b01111000_00000000_00000000_00000000, 0b01111100_00000000_00000000_00000000, 0b10111000_00000000_00000000_00000000, 0b11111011_00000000_00000000_00000000, 0b11111111_11111000_00000000_00000000, 0b10000000_00000000_00000000_00000000, 0b11111111_10110000_00000000_00000000, 0b11111111_00000000_00000000_00000000, 0b11111111_11010000_00000000_00000000, 0b10000100_00000000_00000000_00000000, 0b10111010_00000000_00000000_00000000, 0b10111100_00000000_00000000_00000000, 0b10111110_00000000_00000000_00000000, 0b11000000_00000000_00000000_00000000, 0b11000010_00000000_00000000_00000000, 0b11000100_00000000_00000000_00000000, 0b11000110_00000000_00000000_00000000, 0b11001000_00000000_00000000_00000000, 0b11001010_00000000_00000000_00000000, 0b11001100_00000000_00000000_00000000, 0b11001110_00000000_00000000_00000000, 0b11010000_00000000_00000000_00000000, 0b11010010_00000000_00000000_00000000, 0b11010100_00000000_00000000_00000000, 0b11010110_00000000_00000000_00000000, 0b11011000_00000000_00000000_00000000, 0b11011010_00000000_00000000_00000000, 0b11011100_00000000_00000000_00000000, 0b11011110_00000000_00000000_00000000, 0b11100000_00000000_00000000_00000000, 0b11100010_00000000_00000000_00000000, 0b11100100_00000000_00000000_00000000, 0b11111100_00000000_00000000_00000000, 0b11100110_00000000_00000000_00000000, 0b11111101_00000000_00000000_00000000, 0b11111111_11011000_00000000_00000000, 0b11111111_11111110_00000000_00000000, 0b11111111_11100000_00000000_00000000, 0b11111111_11110000_00000000_00000000, 0b10001000_00000000_00000000_00000000, 0b11111111_11111010_00000000_00000000, 0b00011000_00000000_00000000_00000000, 0b10001100_00000000_00000000_00000000, 0b00100000_00000000_00000000_00000000, 0b10010000_00000000_00000000_00000000, 0b00101000_00000000_00000000_00000000, 0b10010100_00000000_00000000_00000000, 0b10011000_00000000_00000000_00000000, 0b10011100_00000000_00000000_00000000, 0b00110000_00000000_00000000_00000000, 0b11101000_00000000_00000000_00000000, 0b11101010_00000000_00000000_00000000, 0b10100000_00000000_00000000_00000000, 0b10100100_00000000_00000000_00000000, 0b10101000_00000000_00000000_00000000, 0b00111000_00000000_00000000_00000000, 0b10101100_00000000_00000000_00000000, 0b11101100_00000000_00000000_00000000, 0b10110000_00000000_00000000_00000000, 0b01000000_00000000_00000000_00000000, 0b01001000_00000000_00000000_00000000, 0b10110100_00000000_00000000_00000000, 0b11101110_00000000_00000000_00000000, 0b11110000_00000000_00000000_00000000, 0b11110010_00000000_00000000_00000000, 0b11110100_00000000_00000000_00000000, 0b11110110_00000000_00000000_00000000, 0b11111111_11111100_00000000_00000000, 0b11111111_10000000_00000000_00000000, 0b11111111_11110100_00000000_00000000, 0b11111111_11101000_00000000_00000000, 0b11111111_11111111_11111111_11000000, 0b11111111_11111110_01100000_00000000, 0b11111111_11111111_01001000_00000000, 0b11111111_11111110_01110000_00000000, 0b11111111_11111110_10000000_00000000, 0b11111111_11111111_01001100_00000000, 0b11111111_11111111_01010000_00000000, 0b11111111_11111111_01010100_00000000, 0b11111111_11111111_10110010_00000000, 0b11111111_11111111_01011000_00000000, 0b11111111_11111111_10110100_00000000, 0b11111111_11111111_10110110_00000000, 0b11111111_11111111_10111000_00000000, 0b11111111_11111111_10111010_00000000, 0b11111111_11111111_10111100_00000000, 0b11111111_11111111_11101011_00000000, 0b11111111_11111111_10111110_00000000, 0b11111111_11111111_11101100_00000000, 0b11111111_11111111_11101101_00000000, 0b11111111_11111111_01011100_00000000, 0b11111111_11111111_11000000_00000000, 0b11111111_11111111_11101110_00000000, 0b11111111_11111111_11000010_00000000, 0b11111111_11111111_11000100_00000000, 0b11111111_11111111_11000110_00000000, 0b11111111_11111111_11001000_00000000, 0b11111111_11111110_11100000_00000000, 0b11111111_11111111_01100000_00000000, 0b11111111_11111111_11001010_00000000, 0b11111111_11111111_01100100_00000000, 0b11111111_11111111_11001100_00000000, 0b11111111_11111111_11001110_00000000, 0b11111111_11111111_11101111_00000000, 0b11111111_11111111_01101000_00000000, 0b11111111_11111110_11101000_00000000, 0b11111111_11111110_10010000_00000000, 0b11111111_11111111_01101100_00000000, 0b11111111_11111111_01110000_00000000, 0b11111111_11111111_11010000_00000000, 0b11111111_11111111_11010010_00000000, 0b11111111_11111110_11110000_00000000, 0b11111111_11111111_11010100_00000000, 0b11111111_11111111_01110100_00000000, 0b11111111_11111111_01111000_00000000, 0b11111111_11111111_11110000_00000000, 0b11111111_11111110_11111000_00000000, 0b11111111_11111111_01111100_00000000, 0b11111111_11111111_11010110_00000000, 0b11111111_11111111_11011000_00000000, 0b11111111_11111111_00000000_00000000, 0b11111111_11111111_00001000_00000000, 0b11111111_11111111_10000000_00000000, 0b11111111_11111111_00010000_00000000, 0b11111111_11111111_11011010_00000000, 0b11111111_11111111_10000100_00000000, 0b11111111_11111111_11011100_00000000, 0b11111111_11111111_11011110_00000000, 0b11111111_11111110_10100000_00000000, 0b11111111_11111111_10001000_00000000, 0b11111111_11111111_10001100_00000000, 0b11111111_11111111_10010000_00000000, 0b11111111_11111111_11100000_00000000, 0b11111111_11111111_10010100_00000000, 0b11111111_11111111_10011000_00000000, 0b11111111_11111111_11100010_00000000, 0b11111111_11111111_11111000_00000000, 0b11111111_11111111_11111000_01000000, 0b11111111_11111110_10110000_00000000, 0b11111111_11111110_00100000_00000000, 0b11111111_11111111_10011100_00000000, 0b11111111_11111111_11100100_00000000, 0b11111111_11111111_10100000_00000000, 0b11111111_11111111_11110110_00000000, 0b11111111_11111111_11111000_10000000, 0b11111111_11111111_11111000_11000000, 0b11111111_11111111_11111001_00000000, 0b11111111_11111111_11111011_11000000, 0b11111111_11111111_11111011_11100000, 0b11111111_11111111_11111001_01000000, 0b11111111_11111111_11110001_00000000, 0b11111111_11111111_11110110_10000000, 0b11111111_11111110_01000000_00000000, 0b11111111_11111111_00011000_00000000, 0b11111111_11111111_11111001_10000000, 0b11111111_11111111_11111100_00000000, 0b11111111_11111111_11111100_00100000, 0b11111111_11111111_11111001_11000000, 0b11111111_11111111_11111100_01000000, 0b11111111_11111111_11110010_00000000, 0b11111111_11111111_00100000_00000000, 0b11111111_11111111_00101000_00000000, 0b11111111_11111111_11111010_00000000, 0b11111111_11111111_11111010_01000000, 0b11111111_11111111_11111111_11010000, 0b11111111_11111111_11111100_01100000, 0b11111111_11111111_11111100_10000000, 0b11111111_11111111_11111100_10100000, 0b11111111_11111110_11000000_00000000, 0b11111111_11111111_11110011_00000000, 0b11111111_11111110_11010000_00000000, 0b11111111_11111111_00110000_00000000, 0b11111111_11111111_10100100_00000000, 0b11111111_11111111_00111000_00000000, 0b11111111_11111111_01000000_00000000, 0b11111111_11111111_11100110_00000000, 0b11111111_11111111_10101000_00000000, 0b11111111_11111111_10101100_00000000, 0b11111111_11111111_11110111_00000000, 0b11111111_11111111_11110111_10000000, 0b11111111_11111111_11110100_00000000, 0b11111111_11111111_11110101_00000000, 0b11111111_11111111_11111010_10000000, 0b11111111_11111111_11101000_00000000, 0b11111111_11111111_11111010_11000000, 0b11111111_11111111_11111100_11000000, 0b11111111_11111111_11111011_00000000, 0b11111111_11111111_11111011_01000000, 0b11111111_11111111_11111100_11100000, 0b11111111_11111111_11111101_00000000, 0b11111111_11111111_11111101_00100000, 0b11111111_11111111_11111101_01000000, 0b11111111_11111111_11111101_01100000, 0b11111111_11111111_11111111_11100000, 0b11111111_11111111_11111101_10000000, 0b11111111_11111111_11111101_10100000, 0b11111111_11111111_11111101_11000000, 0b11111111_11111111_11111101_11100000, 0b11111111_11111111_11111110_00000000, 0b11111111_11111111_11111011_10000000, 0b11111111_11111111_11111111_11111100, }; private static ReadOnlySpan<byte> EncodingTableBitLengths => new byte[257] { 13, 23, 28, 28, 28, 28, 28, 28, 28, 24, 30, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 28, 6, 10, 10, 12, 13, 6, 8, 11, 10, 10, 8, 11, 8, 6, 6, 6, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 8, 15, 6, 12, 10, 13, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 13, 19, 13, 14, 6, 15, 5, 6, 5, 6, 5, 6, 6, 6, 5, 7, 7, 6, 6, 6, 5, 6, 7, 6, 5, 5, 6, 7, 7, 7, 7, 7, 15, 11, 14, 13, 28, 20, 22, 20, 20, 22, 22, 22, 23, 22, 23, 23, 23, 23, 23, 24, 23, 24, 24, 22, 23, 24, 23, 23, 23, 23, 21, 22, 23, 22, 23, 23, 24, 22, 21, 20, 22, 22, 23, 23, 21, 23, 22, 22, 24, 21, 22, 23, 23, 21, 21, 22, 21, 23, 22, 23, 23, 20, 22, 22, 22, 23, 22, 22, 23, 26, 26, 20, 19, 22, 23, 22, 25, 26, 26, 26, 27, 27, 26, 24, 25, 19, 21, 26, 27, 27, 26, 27, 24, 21, 21, 26, 26, 28, 27, 27, 27, 20, 24, 20, 21, 22, 21, 21, 23, 22, 22, 25, 25, 24, 24, 26, 23, 26, 27, 26, 26, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 26, 30 }; private static readonly ushort[] s_decodingTree = GenerateDecodingLookupTree(); public static (uint encoded, int bitLength) Encode(int data) { return (s_encodingTableCodes[data], EncodingTableBitLengths[data]); } private static ushort[] GenerateDecodingLookupTree() { // Decoding lookup tree is a tree of 8 bit lookup tables stored in // one dimensional array of ushort to reduce allocations. // First 256 ushort is lookup table with index 0, next 256 ushort is lookup table with index 1, etc... // lookup_value = [(lookup_table_index << 8) + lookup_index] // lookup_index is next 8 bits of huffman code, if there is less than 8 bits in source. // lookup_index MUST be aligned to 8 bits with LSB bits set to anything (zeros are recommended). // Lookup value is encoded in ushort as either. // ----------------------------------------------------------------- // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // | 1 | next_lookup_table_index | not_used | // +---+---------------------------+-------------------------------+ // or // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // | 0 | number_of_used_bits | octet | // +---+---------------------------+-------------------------------+ // Bit 15 unset indicates a leaf value of decoding tree. // For example value 0x0241 means that we have reached end of huffman code // with result byte 0x41 'A' and from lookup bits only rightmost 2 bits were used // and rest of bits are part of next huffman code. // Bit 15 set indicates that code is not yet decoded and next lookup table index shall be used // for next n bits of huffman code. // 0 in 'next lookup table index' is considered as decoding error - invalid huffman code // Because HPack uses static huffman code defined in RFC https://httpwg.org/specs/rfc7541.html#huffman.code // it is guaranteed that for this huffman code generated decoding lookup tree MUST consist of exactly 15 lookup tables var decodingTree = new ushort[15 * 256]; uint[] encodingTableCodes = s_encodingTableCodes; ReadOnlySpan<byte> encodingTableBitLengths = EncodingTableBitLengths; int allocatedLookupTableIndex = 0; // Create traverse path for all 0..256 octets, 256 is EOS, see: http://httpwg.org/specs/rfc7541.html#rfc.section.5.2 for (int octet = 0; octet <= 256; octet++) { uint code = encodingTableCodes[octet]; int bitLength = encodingTableBitLengths[octet]; int lookupTableIndex = 0; int bitsLeft = bitLength; while (bitsLeft > 0) { // read next 8 bits from huffman code int indexInLookupTable = (int)(code >> (32 - 8)); if (bitsLeft <= 8) { // Reached last lookup table for this huffman code. // Identical lookup value has to be stored for every combination of unused bits, // For example: 12 bit code could be looked up during decoding as this: // --------------------------------- // 7 6 5 4 3 2 1 0 // +---+---+---+---+---+---+---+---+ // |last_code_bits | next_code_bits| // +-------------------------------+ // next_code_bits are 'random' bits of next huffman code, so in order for lookup // to work, lookup value has to be stored for all 4 unused bits, in this case for suffix 0..15 int suffixCount = 1 << (8 - bitsLeft); for (int suffix = 0; suffix < suffixCount; suffix++) { if (octet == 256) { // EOS (in our case 256) have special meaning in HPack static huffman code // see: http://httpwg.org/specs/rfc7541.html#rfc.section.5.2 // > A Huffman-encoded string literal containing the EOS symbol MUST be treated as a decoding error. // To force decoding error we store 0 as 'next lookup table index' which MUST be treated as decoding error. // Invalid huffman code - EOS // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // | 1 | 0 0 0 0 0 0 0 | 1 1 1 1 1 1 1 1 | // +---+---------------------------+-------------------------------+ decodingTree[(lookupTableIndex << 8) + (indexInLookupTable | suffix)] = 0x80ff; } else { // Leaf lookup value // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // | 0 | number_of_used_bits | code | // +---+---------------------------+-------------------------------+ decodingTree[(lookupTableIndex << 8) + (indexInLookupTable | suffix)] = (ushort)((bitsLeft << 8) | octet); } } } else { // More than 8 bits left in huffman code means that we need to traverse to another lookup table for next 8 bits ushort lookupValue = decodingTree[(lookupTableIndex << 8) + indexInLookupTable]; // Because next_lookup_table_index can not be 0, as 0 is index of root table, default value of array element // means that we have not initialized it yet => lookup table MUST be allocated and its index assigned to that lookup value // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // | 1 | next_lookup_table_index | not_used | // +---+---------------------------+-------------------------------+ if (lookupValue == 0) { ++allocatedLookupTableIndex; decodingTree[(lookupTableIndex << 8) + indexInLookupTable] = (ushort)((0x80 | allocatedLookupTableIndex) << 8); lookupTableIndex = allocatedLookupTableIndex; } else { lookupTableIndex = (lookupValue & 0x7f00) >> 8; } } bitsLeft -= 8; code <<= 8; } } return decodingTree; } /// <summary> /// Decodes a Huffman encoded string from a byte array. /// </summary> /// <param name="src">The source byte array containing the encoded data.</param> /// <param name="dstArray">The destination byte array to store the decoded data. This may grow if its size is insufficient.</param> /// <returns>The number of decoded symbols.</returns> public static int Decode(ReadOnlySpan<byte> src, ref byte[] dstArray) { // The code below implements the decoding logic for an HPack huffman encoded literal values. // https://httpwg.org/specs/rfc7541.html#string.literal.representation // // To decode a symbol, we traverse the decoding lookup table tree by 8 bits for each lookup // until we found a leaf - which contains decoded symbol (octet) // // see comments in GenerateDecodingLookupTree() describing decoding table Span<byte> dst = dstArray; Debug.Assert(dst != null && dst.Length > 0); ushort[] decodingTree = s_decodingTree; int lookupTableIndex = 0; int lookupIndex; uint acc = 0; int bitsInAcc = 0; int i = 0; int j = 0; while (i < src.Length) { // Load next 8 bits into accumulator. acc <<= 8; acc |= src[i++]; bitsInAcc += 8; // Decode bits in accumulator. do { lookupIndex = (byte)(acc >> (bitsInAcc - 8)); int lookupValue = decodingTree[(lookupTableIndex << 8) + lookupIndex]; if (lookupValue < 0x80_00) { // Octet found. // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // | 0 | number_of_used_bits | octet | // +---+---------------------------+-------------------------------+ if (j == dst.Length) { Array.Resize(ref dstArray, dst.Length * 2); dst = dstArray; } dst[j++] = (byte)lookupValue; // Start lookup of next symbol lookupTableIndex = 0; bitsInAcc -= lookupValue >> 8; } else { // Traverse to next lookup table. // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // | 1 | next_lookup_table_index | not_used | // +---+---------------------------+-------------------------------+ lookupTableIndex = (lookupValue & 0x7f00) >> 8; if (lookupTableIndex == 0) { // No valid symbol could be decoded or EOS was decoded throw new HuffmanDecodingException(SR.net_http_hpack_huffman_decode_failed); } bitsInAcc -= 8; } } while (bitsInAcc >= 8); } // Finish decoding last < 8 bits of src. // Processing of the last byte has to handle several corner cases // so it's extracted outside of the main loop for performance reasons. while (bitsInAcc > 0) { Debug.Assert(bitsInAcc < 8); // Check for correct EOS, which is padding with ones till end of byte // when we STARTED new huffman code in last 8 bits (lookupTableIndex was reset to 0 -> root lookup table). if (lookupTableIndex == 0) { // Check if all remaining bits are ones. uint ones = uint.MaxValue >> (32 - bitsInAcc); if ((acc & ones) == ones) { // Is it a EOS. See: http://httpwg.org/specs/rfc7541.html#rfc.section.5.2 break; } } // Lookup index has to be 8 bits aligned to MSB lookupIndex = (byte)(acc << (8 - bitsInAcc)); int lookupValue = decodingTree[(lookupTableIndex << 8) + lookupIndex]; if (lookupValue < 0x80_00) { // Octet found. // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // | 0 | number_of_used_bits | octet | // +---+---------------------------+-------------------------------+ bitsInAcc -= lookupValue >> 8; if (bitsInAcc < 0) { // Last looked up code had more bits than was left in accumulator which indicated invalid or incomplete source throw new HuffmanDecodingException(SR.net_http_hpack_huffman_decode_failed); } if (j == dst.Length) { Array.Resize(ref dstArray, dst.Length * 2); dst = dstArray; } dst[j++] = (byte)lookupValue; // Set table index to root - start of new huffman code. lookupTableIndex = 0; } else { // Src was depleted in middle of lookup tree or EOS was decoded. throw new HuffmanDecodingException(SR.net_http_hpack_huffman_decode_failed); } } if (lookupTableIndex != 0) { // Finished in middle of traversing - no valid symbol could be decoded // or too long EOS padding (7 bits plus). See: http://httpwg.org/specs/rfc7541.html#rfc.section.5.2 throw new HuffmanDecodingException(SR.net_http_hpack_huffman_decode_failed); } return j; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable enable using System.Diagnostics; using System.Threading; namespace System.Net.Http.HPack { internal static class Huffman { // HPack static huffman code. see: https://httpwg.org/specs/rfc7541.html#huffman.code // Stored into two tables to optimize its initialization and memory consumption. private static readonly uint[] s_encodingTableCodes = new uint[257] { 0b11111111_11000000_00000000_00000000, 0b11111111_11111111_10110000_00000000, 0b11111111_11111111_11111110_00100000, 0b11111111_11111111_11111110_00110000, 0b11111111_11111111_11111110_01000000, 0b11111111_11111111_11111110_01010000, 0b11111111_11111111_11111110_01100000, 0b11111111_11111111_11111110_01110000, 0b11111111_11111111_11111110_10000000, 0b11111111_11111111_11101010_00000000, 0b11111111_11111111_11111111_11110000, 0b11111111_11111111_11111110_10010000, 0b11111111_11111111_11111110_10100000, 0b11111111_11111111_11111111_11110100, 0b11111111_11111111_11111110_10110000, 0b11111111_11111111_11111110_11000000, 0b11111111_11111111_11111110_11010000, 0b11111111_11111111_11111110_11100000, 0b11111111_11111111_11111110_11110000, 0b11111111_11111111_11111111_00000000, 0b11111111_11111111_11111111_00010000, 0b11111111_11111111_11111111_00100000, 0b11111111_11111111_11111111_11111000, 0b11111111_11111111_11111111_00110000, 0b11111111_11111111_11111111_01000000, 0b11111111_11111111_11111111_01010000, 0b11111111_11111111_11111111_01100000, 0b11111111_11111111_11111111_01110000, 0b11111111_11111111_11111111_10000000, 0b11111111_11111111_11111111_10010000, 0b11111111_11111111_11111111_10100000, 0b11111111_11111111_11111111_10110000, 0b01010000_00000000_00000000_00000000, 0b11111110_00000000_00000000_00000000, 0b11111110_01000000_00000000_00000000, 0b11111111_10100000_00000000_00000000, 0b11111111_11001000_00000000_00000000, 0b01010100_00000000_00000000_00000000, 0b11111000_00000000_00000000_00000000, 0b11111111_01000000_00000000_00000000, 0b11111110_10000000_00000000_00000000, 0b11111110_11000000_00000000_00000000, 0b11111001_00000000_00000000_00000000, 0b11111111_01100000_00000000_00000000, 0b11111010_00000000_00000000_00000000, 0b01011000_00000000_00000000_00000000, 0b01011100_00000000_00000000_00000000, 0b01100000_00000000_00000000_00000000, 0b00000000_00000000_00000000_00000000, 0b00001000_00000000_00000000_00000000, 0b00010000_00000000_00000000_00000000, 0b01100100_00000000_00000000_00000000, 0b01101000_00000000_00000000_00000000, 0b01101100_00000000_00000000_00000000, 0b01110000_00000000_00000000_00000000, 0b01110100_00000000_00000000_00000000, 0b01111000_00000000_00000000_00000000, 0b01111100_00000000_00000000_00000000, 0b10111000_00000000_00000000_00000000, 0b11111011_00000000_00000000_00000000, 0b11111111_11111000_00000000_00000000, 0b10000000_00000000_00000000_00000000, 0b11111111_10110000_00000000_00000000, 0b11111111_00000000_00000000_00000000, 0b11111111_11010000_00000000_00000000, 0b10000100_00000000_00000000_00000000, 0b10111010_00000000_00000000_00000000, 0b10111100_00000000_00000000_00000000, 0b10111110_00000000_00000000_00000000, 0b11000000_00000000_00000000_00000000, 0b11000010_00000000_00000000_00000000, 0b11000100_00000000_00000000_00000000, 0b11000110_00000000_00000000_00000000, 0b11001000_00000000_00000000_00000000, 0b11001010_00000000_00000000_00000000, 0b11001100_00000000_00000000_00000000, 0b11001110_00000000_00000000_00000000, 0b11010000_00000000_00000000_00000000, 0b11010010_00000000_00000000_00000000, 0b11010100_00000000_00000000_00000000, 0b11010110_00000000_00000000_00000000, 0b11011000_00000000_00000000_00000000, 0b11011010_00000000_00000000_00000000, 0b11011100_00000000_00000000_00000000, 0b11011110_00000000_00000000_00000000, 0b11100000_00000000_00000000_00000000, 0b11100010_00000000_00000000_00000000, 0b11100100_00000000_00000000_00000000, 0b11111100_00000000_00000000_00000000, 0b11100110_00000000_00000000_00000000, 0b11111101_00000000_00000000_00000000, 0b11111111_11011000_00000000_00000000, 0b11111111_11111110_00000000_00000000, 0b11111111_11100000_00000000_00000000, 0b11111111_11110000_00000000_00000000, 0b10001000_00000000_00000000_00000000, 0b11111111_11111010_00000000_00000000, 0b00011000_00000000_00000000_00000000, 0b10001100_00000000_00000000_00000000, 0b00100000_00000000_00000000_00000000, 0b10010000_00000000_00000000_00000000, 0b00101000_00000000_00000000_00000000, 0b10010100_00000000_00000000_00000000, 0b10011000_00000000_00000000_00000000, 0b10011100_00000000_00000000_00000000, 0b00110000_00000000_00000000_00000000, 0b11101000_00000000_00000000_00000000, 0b11101010_00000000_00000000_00000000, 0b10100000_00000000_00000000_00000000, 0b10100100_00000000_00000000_00000000, 0b10101000_00000000_00000000_00000000, 0b00111000_00000000_00000000_00000000, 0b10101100_00000000_00000000_00000000, 0b11101100_00000000_00000000_00000000, 0b10110000_00000000_00000000_00000000, 0b01000000_00000000_00000000_00000000, 0b01001000_00000000_00000000_00000000, 0b10110100_00000000_00000000_00000000, 0b11101110_00000000_00000000_00000000, 0b11110000_00000000_00000000_00000000, 0b11110010_00000000_00000000_00000000, 0b11110100_00000000_00000000_00000000, 0b11110110_00000000_00000000_00000000, 0b11111111_11111100_00000000_00000000, 0b11111111_10000000_00000000_00000000, 0b11111111_11110100_00000000_00000000, 0b11111111_11101000_00000000_00000000, 0b11111111_11111111_11111111_11000000, 0b11111111_11111110_01100000_00000000, 0b11111111_11111111_01001000_00000000, 0b11111111_11111110_01110000_00000000, 0b11111111_11111110_10000000_00000000, 0b11111111_11111111_01001100_00000000, 0b11111111_11111111_01010000_00000000, 0b11111111_11111111_01010100_00000000, 0b11111111_11111111_10110010_00000000, 0b11111111_11111111_01011000_00000000, 0b11111111_11111111_10110100_00000000, 0b11111111_11111111_10110110_00000000, 0b11111111_11111111_10111000_00000000, 0b11111111_11111111_10111010_00000000, 0b11111111_11111111_10111100_00000000, 0b11111111_11111111_11101011_00000000, 0b11111111_11111111_10111110_00000000, 0b11111111_11111111_11101100_00000000, 0b11111111_11111111_11101101_00000000, 0b11111111_11111111_01011100_00000000, 0b11111111_11111111_11000000_00000000, 0b11111111_11111111_11101110_00000000, 0b11111111_11111111_11000010_00000000, 0b11111111_11111111_11000100_00000000, 0b11111111_11111111_11000110_00000000, 0b11111111_11111111_11001000_00000000, 0b11111111_11111110_11100000_00000000, 0b11111111_11111111_01100000_00000000, 0b11111111_11111111_11001010_00000000, 0b11111111_11111111_01100100_00000000, 0b11111111_11111111_11001100_00000000, 0b11111111_11111111_11001110_00000000, 0b11111111_11111111_11101111_00000000, 0b11111111_11111111_01101000_00000000, 0b11111111_11111110_11101000_00000000, 0b11111111_11111110_10010000_00000000, 0b11111111_11111111_01101100_00000000, 0b11111111_11111111_01110000_00000000, 0b11111111_11111111_11010000_00000000, 0b11111111_11111111_11010010_00000000, 0b11111111_11111110_11110000_00000000, 0b11111111_11111111_11010100_00000000, 0b11111111_11111111_01110100_00000000, 0b11111111_11111111_01111000_00000000, 0b11111111_11111111_11110000_00000000, 0b11111111_11111110_11111000_00000000, 0b11111111_11111111_01111100_00000000, 0b11111111_11111111_11010110_00000000, 0b11111111_11111111_11011000_00000000, 0b11111111_11111111_00000000_00000000, 0b11111111_11111111_00001000_00000000, 0b11111111_11111111_10000000_00000000, 0b11111111_11111111_00010000_00000000, 0b11111111_11111111_11011010_00000000, 0b11111111_11111111_10000100_00000000, 0b11111111_11111111_11011100_00000000, 0b11111111_11111111_11011110_00000000, 0b11111111_11111110_10100000_00000000, 0b11111111_11111111_10001000_00000000, 0b11111111_11111111_10001100_00000000, 0b11111111_11111111_10010000_00000000, 0b11111111_11111111_11100000_00000000, 0b11111111_11111111_10010100_00000000, 0b11111111_11111111_10011000_00000000, 0b11111111_11111111_11100010_00000000, 0b11111111_11111111_11111000_00000000, 0b11111111_11111111_11111000_01000000, 0b11111111_11111110_10110000_00000000, 0b11111111_11111110_00100000_00000000, 0b11111111_11111111_10011100_00000000, 0b11111111_11111111_11100100_00000000, 0b11111111_11111111_10100000_00000000, 0b11111111_11111111_11110110_00000000, 0b11111111_11111111_11111000_10000000, 0b11111111_11111111_11111000_11000000, 0b11111111_11111111_11111001_00000000, 0b11111111_11111111_11111011_11000000, 0b11111111_11111111_11111011_11100000, 0b11111111_11111111_11111001_01000000, 0b11111111_11111111_11110001_00000000, 0b11111111_11111111_11110110_10000000, 0b11111111_11111110_01000000_00000000, 0b11111111_11111111_00011000_00000000, 0b11111111_11111111_11111001_10000000, 0b11111111_11111111_11111100_00000000, 0b11111111_11111111_11111100_00100000, 0b11111111_11111111_11111001_11000000, 0b11111111_11111111_11111100_01000000, 0b11111111_11111111_11110010_00000000, 0b11111111_11111111_00100000_00000000, 0b11111111_11111111_00101000_00000000, 0b11111111_11111111_11111010_00000000, 0b11111111_11111111_11111010_01000000, 0b11111111_11111111_11111111_11010000, 0b11111111_11111111_11111100_01100000, 0b11111111_11111111_11111100_10000000, 0b11111111_11111111_11111100_10100000, 0b11111111_11111110_11000000_00000000, 0b11111111_11111111_11110011_00000000, 0b11111111_11111110_11010000_00000000, 0b11111111_11111111_00110000_00000000, 0b11111111_11111111_10100100_00000000, 0b11111111_11111111_00111000_00000000, 0b11111111_11111111_01000000_00000000, 0b11111111_11111111_11100110_00000000, 0b11111111_11111111_10101000_00000000, 0b11111111_11111111_10101100_00000000, 0b11111111_11111111_11110111_00000000, 0b11111111_11111111_11110111_10000000, 0b11111111_11111111_11110100_00000000, 0b11111111_11111111_11110101_00000000, 0b11111111_11111111_11111010_10000000, 0b11111111_11111111_11101000_00000000, 0b11111111_11111111_11111010_11000000, 0b11111111_11111111_11111100_11000000, 0b11111111_11111111_11111011_00000000, 0b11111111_11111111_11111011_01000000, 0b11111111_11111111_11111100_11100000, 0b11111111_11111111_11111101_00000000, 0b11111111_11111111_11111101_00100000, 0b11111111_11111111_11111101_01000000, 0b11111111_11111111_11111101_01100000, 0b11111111_11111111_11111111_11100000, 0b11111111_11111111_11111101_10000000, 0b11111111_11111111_11111101_10100000, 0b11111111_11111111_11111101_11000000, 0b11111111_11111111_11111101_11100000, 0b11111111_11111111_11111110_00000000, 0b11111111_11111111_11111011_10000000, 0b11111111_11111111_11111111_11111100, }; private static ReadOnlySpan<byte> EncodingTableBitLengths => new byte[257] { 13, 23, 28, 28, 28, 28, 28, 28, 28, 24, 30, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 28, 6, 10, 10, 12, 13, 6, 8, 11, 10, 10, 8, 11, 8, 6, 6, 6, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 8, 15, 6, 12, 10, 13, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 13, 19, 13, 14, 6, 15, 5, 6, 5, 6, 5, 6, 6, 6, 5, 7, 7, 6, 6, 6, 5, 6, 7, 6, 5, 5, 6, 7, 7, 7, 7, 7, 15, 11, 14, 13, 28, 20, 22, 20, 20, 22, 22, 22, 23, 22, 23, 23, 23, 23, 23, 24, 23, 24, 24, 22, 23, 24, 23, 23, 23, 23, 21, 22, 23, 22, 23, 23, 24, 22, 21, 20, 22, 22, 23, 23, 21, 23, 22, 22, 24, 21, 22, 23, 23, 21, 21, 22, 21, 23, 22, 23, 23, 20, 22, 22, 22, 23, 22, 22, 23, 26, 26, 20, 19, 22, 23, 22, 25, 26, 26, 26, 27, 27, 26, 24, 25, 19, 21, 26, 27, 27, 26, 27, 24, 21, 21, 26, 26, 28, 27, 27, 27, 20, 24, 20, 21, 22, 21, 21, 23, 22, 22, 25, 25, 24, 24, 26, 23, 26, 27, 26, 26, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 26, 30 }; private static readonly ushort[] s_decodingTree = GenerateDecodingLookupTree(); public static (uint encoded, int bitLength) Encode(int data) { return (s_encodingTableCodes[data], EncodingTableBitLengths[data]); } private static ushort[] GenerateDecodingLookupTree() { // Decoding lookup tree is a tree of 8 bit lookup tables stored in // one dimensional array of ushort to reduce allocations. // First 256 ushort is lookup table with index 0, next 256 ushort is lookup table with index 1, etc... // lookup_value = [(lookup_table_index << 8) + lookup_index] // lookup_index is next 8 bits of huffman code, if there is less than 8 bits in source. // lookup_index MUST be aligned to 8 bits with LSB bits set to anything (zeros are recommended). // Lookup value is encoded in ushort as either. // ----------------------------------------------------------------- // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // | 1 | next_lookup_table_index | not_used | // +---+---------------------------+-------------------------------+ // or // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // | 0 | number_of_used_bits | octet | // +---+---------------------------+-------------------------------+ // Bit 15 unset indicates a leaf value of decoding tree. // For example value 0x0241 means that we have reached end of huffman code // with result byte 0x41 'A' and from lookup bits only rightmost 2 bits were used // and rest of bits are part of next huffman code. // Bit 15 set indicates that code is not yet decoded and next lookup table index shall be used // for next n bits of huffman code. // 0 in 'next lookup table index' is considered as decoding error - invalid huffman code // Because HPack uses static huffman code defined in RFC https://httpwg.org/specs/rfc7541.html#huffman.code // it is guaranteed that for this huffman code generated decoding lookup tree MUST consist of exactly 15 lookup tables var decodingTree = new ushort[15 * 256]; uint[] encodingTableCodes = s_encodingTableCodes; ReadOnlySpan<byte> encodingTableBitLengths = EncodingTableBitLengths; int allocatedLookupTableIndex = 0; // Create traverse path for all 0..256 octets, 256 is EOS, see: http://httpwg.org/specs/rfc7541.html#rfc.section.5.2 for (int octet = 0; octet <= 256; octet++) { uint code = encodingTableCodes[octet]; int bitLength = encodingTableBitLengths[octet]; int lookupTableIndex = 0; int bitsLeft = bitLength; while (bitsLeft > 0) { // read next 8 bits from huffman code int indexInLookupTable = (int)(code >> (32 - 8)); if (bitsLeft <= 8) { // Reached last lookup table for this huffman code. // Identical lookup value has to be stored for every combination of unused bits, // For example: 12 bit code could be looked up during decoding as this: // --------------------------------- // 7 6 5 4 3 2 1 0 // +---+---+---+---+---+---+---+---+ // |last_code_bits | next_code_bits| // +-------------------------------+ // next_code_bits are 'random' bits of next huffman code, so in order for lookup // to work, lookup value has to be stored for all 4 unused bits, in this case for suffix 0..15 int suffixCount = 1 << (8 - bitsLeft); for (int suffix = 0; suffix < suffixCount; suffix++) { if (octet == 256) { // EOS (in our case 256) have special meaning in HPack static huffman code // see: http://httpwg.org/specs/rfc7541.html#rfc.section.5.2 // > A Huffman-encoded string literal containing the EOS symbol MUST be treated as a decoding error. // To force decoding error we store 0 as 'next lookup table index' which MUST be treated as decoding error. // Invalid huffman code - EOS // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // | 1 | 0 0 0 0 0 0 0 | 1 1 1 1 1 1 1 1 | // +---+---------------------------+-------------------------------+ decodingTree[(lookupTableIndex << 8) + (indexInLookupTable | suffix)] = 0x80ff; } else { // Leaf lookup value // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // | 0 | number_of_used_bits | code | // +---+---------------------------+-------------------------------+ decodingTree[(lookupTableIndex << 8) + (indexInLookupTable | suffix)] = (ushort)((bitsLeft << 8) | octet); } } } else { // More than 8 bits left in huffman code means that we need to traverse to another lookup table for next 8 bits ushort lookupValue = decodingTree[(lookupTableIndex << 8) + indexInLookupTable]; // Because next_lookup_table_index can not be 0, as 0 is index of root table, default value of array element // means that we have not initialized it yet => lookup table MUST be allocated and its index assigned to that lookup value // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // | 1 | next_lookup_table_index | not_used | // +---+---------------------------+-------------------------------+ if (lookupValue == 0) { ++allocatedLookupTableIndex; decodingTree[(lookupTableIndex << 8) + indexInLookupTable] = (ushort)((0x80 | allocatedLookupTableIndex) << 8); lookupTableIndex = allocatedLookupTableIndex; } else { lookupTableIndex = (lookupValue & 0x7f00) >> 8; } } bitsLeft -= 8; code <<= 8; } } return decodingTree; } /// <summary> /// Decodes a Huffman encoded string from a byte array. /// </summary> /// <param name="src">The source byte array containing the encoded data.</param> /// <param name="dstArray">The destination byte array to store the decoded data. This may grow if its size is insufficient.</param> /// <returns>The number of decoded symbols.</returns> public static int Decode(ReadOnlySpan<byte> src, ref byte[] dstArray) { // The code below implements the decoding logic for an HPack huffman encoded literal values. // https://httpwg.org/specs/rfc7541.html#string.literal.representation // // To decode a symbol, we traverse the decoding lookup table tree by 8 bits for each lookup // until we found a leaf - which contains decoded symbol (octet) // // see comments in GenerateDecodingLookupTree() describing decoding table Span<byte> dst = dstArray; Debug.Assert(dst != null && dst.Length > 0); ushort[] decodingTree = s_decodingTree; int lookupTableIndex = 0; int lookupIndex; uint acc = 0; int bitsInAcc = 0; int i = 0; int j = 0; while (i < src.Length) { // Load next 8 bits into accumulator. acc <<= 8; acc |= src[i++]; bitsInAcc += 8; // Decode bits in accumulator. do { lookupIndex = (byte)(acc >> (bitsInAcc - 8)); int lookupValue = decodingTree[(lookupTableIndex << 8) + lookupIndex]; if (lookupValue < 0x80_00) { // Octet found. // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // | 0 | number_of_used_bits | octet | // +---+---------------------------+-------------------------------+ if (j == dst.Length) { Array.Resize(ref dstArray, dst.Length * 2); dst = dstArray; } dst[j++] = (byte)lookupValue; // Start lookup of next symbol lookupTableIndex = 0; bitsInAcc -= lookupValue >> 8; } else { // Traverse to next lookup table. // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // | 1 | next_lookup_table_index | not_used | // +---+---------------------------+-------------------------------+ lookupTableIndex = (lookupValue & 0x7f00) >> 8; if (lookupTableIndex == 0) { // No valid symbol could be decoded or EOS was decoded throw new HuffmanDecodingException(SR.net_http_hpack_huffman_decode_failed); } bitsInAcc -= 8; } } while (bitsInAcc >= 8); } // Finish decoding last < 8 bits of src. // Processing of the last byte has to handle several corner cases // so it's extracted outside of the main loop for performance reasons. while (bitsInAcc > 0) { Debug.Assert(bitsInAcc < 8); // Check for correct EOS, which is padding with ones till end of byte // when we STARTED new huffman code in last 8 bits (lookupTableIndex was reset to 0 -> root lookup table). if (lookupTableIndex == 0) { // Check if all remaining bits are ones. uint ones = uint.MaxValue >> (32 - bitsInAcc); if ((acc & ones) == ones) { // Is it a EOS. See: http://httpwg.org/specs/rfc7541.html#rfc.section.5.2 break; } } // Lookup index has to be 8 bits aligned to MSB lookupIndex = (byte)(acc << (8 - bitsInAcc)); int lookupValue = decodingTree[(lookupTableIndex << 8) + lookupIndex]; if (lookupValue < 0x80_00) { // Octet found. // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // | 0 | number_of_used_bits | octet | // +---+---------------------------+-------------------------------+ bitsInAcc -= lookupValue >> 8; if (bitsInAcc < 0) { // Last looked up code had more bits than was left in accumulator which indicated invalid or incomplete source throw new HuffmanDecodingException(SR.net_http_hpack_huffman_decode_failed); } if (j == dst.Length) { Array.Resize(ref dstArray, dst.Length * 2); dst = dstArray; } dst[j++] = (byte)lookupValue; // Set table index to root - start of new huffman code. lookupTableIndex = 0; } else { // Src was depleted in middle of lookup tree or EOS was decoded. throw new HuffmanDecodingException(SR.net_http_hpack_huffman_decode_failed); } } if (lookupTableIndex != 0) { // Finished in middle of traversing - no valid symbol could be decoded // or too long EOS padding (7 bits plus). See: http://httpwg.org/specs/rfc7541.html#rfc.section.5.2 throw new HuffmanDecodingException(SR.net_http_hpack_huffman_decode_failed); } return j; } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/mono/mono/tests/stringbuilder.cs
using System.Text; namespace test { public class Test { public static int Main() { StringBuilder b = new StringBuilder (); /*b.Append ('A'); b.Append ('b'); b.Append ('r');*/ b.Append ("Abr"); if (b.ToString() != "Abr") { System.Console.WriteLine ("Got: " + b.ToString()); return 1; } b.Append ('a'); b.Append ("cadabra"); if (b.ToString() != "Abracadabra") { System.Console.WriteLine ("Got: " + b.ToString()); return 2; } return 0; } } }
using System.Text; namespace test { public class Test { public static int Main() { StringBuilder b = new StringBuilder (); /*b.Append ('A'); b.Append ('b'); b.Append ('r');*/ b.Append ("Abr"); if (b.ToString() != "Abr") { System.Console.WriteLine ("Got: " + b.ToString()); return 1; } b.Append ('a'); b.Append ("cadabra"); if (b.ToString() != "Abracadabra") { System.Console.WriteLine ("Got: " + b.ToString()); return 2; } return 0; } } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b31780/b31780.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly 'b31780' {} .assembly extern xunit.core {} .class ILGEN_0xc5f46dbe { .method static int32 Method_0x3179() { .maxstack 19 .locals (unsigned int32[] local_0x0,unsigned int16 local_0x3,int16 local_0x4) ldc.i4 255 newarr [mscorlib]System.UInt32 stloc local_0x0 Start_Orphan_3: ldloc local_0x0 ldlen stloc local_0x3 End_Orphan_3: Start_Orphan_b: ldloc local_0x0 ldlen stloc local_0x4 End_Orphan_b: ldc.i4 0 ret } .method static int32 Main() { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 20 call int32 ILGEN_0xc5f46dbe::Method_0x3179() ldc.i4 100 add ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly 'b31780' {} .assembly extern xunit.core {} .class ILGEN_0xc5f46dbe { .method static int32 Method_0x3179() { .maxstack 19 .locals (unsigned int32[] local_0x0,unsigned int16 local_0x3,int16 local_0x4) ldc.i4 255 newarr [mscorlib]System.UInt32 stloc local_0x0 Start_Orphan_3: ldloc local_0x0 ldlen stloc local_0x3 End_Orphan_3: Start_Orphan_b: ldloc local_0x0 ldlen stloc local_0x4 End_Orphan_b: ldc.i4 0 ret } .method static int32 Main() { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 20 call int32 ILGEN_0xc5f46dbe::Method_0x3179() ldc.i4 100 add ret } }
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/JIT/Performance/CodeQuality/V8/Crypto/THIRD-PARTY-NOTICES
.NET Core uses third-party libraries or other resources that may be distributed under licenses different than the .NET Core software. In the event that we accidentally failed to list a required notice, please bring it to our attention. Post an issue or email us: [email protected] The attached notices are provided for information only. License notice for V8.Crypto ---------------------------- Copyright (c) 2003-2005 Tom Wu All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. In addition, the following condition applies: All redistributions must retain an intact copy of this copyright notice and disclaimer.
.NET Core uses third-party libraries or other resources that may be distributed under licenses different than the .NET Core software. In the event that we accidentally failed to list a required notice, please bring it to our attention. Post an issue or email us: [email protected] The attached notices are provided for information only. License notice for V8.Crypto ---------------------------- Copyright (c) 2003-2005 Tom Wu All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. In addition, the following condition applies: All redistributions must retain an intact copy of this copyright notice and disclaimer.
-1
dotnet/runtime
66,192
delete the test file with custom security settings when it's being closed
The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
adamsitnik
2022-03-04T12:54:51Z
2022-03-04T15:07:03Z
b8dff9ac2ea0b99236ca1c4c4a82cbcf3f1052e3
51d11ebbaff4e967652e61b2b371e0d2f04c6fba
delete the test file with custom security settings when it's being closed. The problematic files/folders names were just guids, so it was hard to find out which test is creating them. So in the first commit, I've added a logic that uses the test name when generating the paths. This has allowed me to identify that `FileInfo_Create_FileSecurity_Successful` is the method which creates unremovable files. The fix was to use `FileOptions.DeleteOnClose` which ensures that given file is being deleted when it's getting closed. fixes #66108
./src/tests/Loader/classloader/v1/Beta1/Layout/Matrix/cs/L-2-12-3D.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. public interface A{ ////////////////////////////// // Instance Methods int MethPubInst(); } public interface B{ int MethPubInst2(); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. public interface A{ ////////////////////////////// // Instance Methods int MethPubInst(); } public interface B{ int MethPubInst2(); }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/CborConformanceLevel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; namespace System.Formats.Cbor { /// <summary>Defines supported conformance modes for encoding and decoding CBOR data.</summary> public enum CborConformanceMode { /// <summary>Ensures that the CBOR data is well-formed, as specified in RFC7049.</summary> Lax, /// <summary> /// <para>Ensures that the CBOR data adheres to strict mode, as specified in RFC7049 section 3.10.</para> /// <para>Extends lax conformance with the following requirements:</para> /// <list type="bullet"> /// <item>Maps (major type 5) must not contain duplicate keys.</item> /// <item>Simple values (major type 7) must be encoded as small a possible and exclude the reserved values 24-31.</item> /// <item>UTF-8 string encodings must be valid.</item> /// </list> /// </summary> Strict, /// <summary> /// <para>Ensures that the CBOR data is canonical, as specified in RFC7049 section 3.9.</para> /// <para>Extends strict conformance with the following requirements:</para> /// <list type="bullet"> /// <item>Integers must be encoded as small as possible.</item> /// <item>Maps (major type 5) must contain keys sorted by encoding.</item> /// <item>Indefinite-length items must be made into definite-length items.</item> /// </list> /// </summary> Canonical, /// <summary> /// <para>Ensures that the CBOR data is canonical, as specified by the CTAP v2.0 standard, section 6.</para> /// <para>Extends strict conformance with the following requirements:</para> /// <list type="bullet"> /// <item>Maps (major type 5) must contain keys sorted by encoding.</item> /// <item>Indefinite-length items must be made into definite-length items.</item> /// <item>Integers must be encoded as small as possible.</item> /// <item>The representations of any floating-point values are not changed.</item> /// <item>CBOR tags (major type 6) are not permitted.</item> /// </list> /// </summary> Ctap2Canonical, } internal static class CborConformanceModeHelpers { private static readonly UTF8Encoding s_utf8EncodingLax = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false); private static readonly UTF8Encoding s_utf8EncodingStrict = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); public static void Validate(CborConformanceMode conformanceMode) { if (conformanceMode < CborConformanceMode.Lax || conformanceMode > CborConformanceMode.Ctap2Canonical) { throw new ArgumentOutOfRangeException(nameof(conformanceMode)); } } public static bool RequiresCanonicalIntegerRepresentation(CborConformanceMode conformanceMode) { switch (conformanceMode) { case CborConformanceMode.Lax: case CborConformanceMode.Strict: return false; case CborConformanceMode.Canonical: case CborConformanceMode.Ctap2Canonical: return true; default: throw new ArgumentOutOfRangeException(nameof(conformanceMode)); }; } public static bool RequiresPreservingFloatPrecision(CborConformanceMode conformanceMode) { switch (conformanceMode) { case CborConformanceMode.Lax: case CborConformanceMode.Strict: case CborConformanceMode.Canonical: return false; case CborConformanceMode.Ctap2Canonical: return true; default: throw new ArgumentOutOfRangeException(nameof(conformanceMode)); }; } public static bool RequiresUtf8Validation(CborConformanceMode conformanceMode) { switch (conformanceMode) { case CborConformanceMode.Lax: return false; case CborConformanceMode.Strict: case CborConformanceMode.Canonical: case CborConformanceMode.Ctap2Canonical: return true; default: throw new ArgumentOutOfRangeException(nameof(conformanceMode)); }; } public static Encoding GetUtf8Encoding(CborConformanceMode conformanceMode) { return conformanceMode == CborConformanceMode.Lax ? s_utf8EncodingLax : s_utf8EncodingStrict; } public static bool RequiresDefiniteLengthItems(CborConformanceMode conformanceMode) { switch (conformanceMode) { case CborConformanceMode.Lax: case CborConformanceMode.Strict: return false; case CborConformanceMode.Canonical: case CborConformanceMode.Ctap2Canonical: return true; default: throw new ArgumentOutOfRangeException(nameof(conformanceMode)); }; } public static bool AllowsTags(CborConformanceMode conformanceMode) { switch (conformanceMode) { case CborConformanceMode.Lax: case CborConformanceMode.Strict: case CborConformanceMode.Canonical: return true; case CborConformanceMode.Ctap2Canonical: return false; default: throw new ArgumentOutOfRangeException(nameof(conformanceMode)); }; } public static bool RequiresUniqueKeys(CborConformanceMode conformanceMode) { switch (conformanceMode) { case CborConformanceMode.Lax: return false; case CborConformanceMode.Strict: case CborConformanceMode.Canonical: case CborConformanceMode.Ctap2Canonical: return true; default: throw new ArgumentOutOfRangeException(nameof(conformanceMode)); }; } public static bool RequiresSortedKeys(CborConformanceMode conformanceMode) { switch (conformanceMode) { case CborConformanceMode.Strict: case CborConformanceMode.Lax: return false; case CborConformanceMode.Canonical: case CborConformanceMode.Ctap2Canonical: return true; default: throw new ArgumentOutOfRangeException(nameof(conformanceMode)); }; } public static bool RequireCanonicalSimpleValueEncodings(CborConformanceMode conformanceMode) { switch (conformanceMode) { case CborConformanceMode.Lax: return false; case CborConformanceMode.Strict: case CborConformanceMode.Canonical: case CborConformanceMode.Ctap2Canonical: return true; default: throw new ArgumentOutOfRangeException(nameof(conformanceMode)); } } public static int GetKeyEncodingHashCode(ReadOnlySpan<byte> encoding) { HashCode hash = default; #if NETCOREAPP hash.AddBytes(encoding); #else while (encoding.Length >= sizeof(int)) { hash.Add(MemoryMarshal.Read<int>(encoding)); encoding = encoding.Slice(sizeof(int)); } foreach (byte b in encoding) { hash.Add(b); } #endif return hash.ToHashCode(); } public static bool AreEqualKeyEncodings(ReadOnlySpan<byte> left, ReadOnlySpan<byte> right) { return left.SequenceEqual(right); } public static int CompareKeyEncodings(ReadOnlySpan<byte> left, ReadOnlySpan<byte> right, CborConformanceMode mode) { Debug.Assert(!left.IsEmpty && !right.IsEmpty); switch (mode) { case CborConformanceMode.Canonical: // Implements key sorting according to // https://tools.ietf.org/html/rfc7049#section-3.9 if (left.Length != right.Length) { return left.Length - right.Length; } return left.SequenceCompareTo(right); case CborConformanceMode.Ctap2Canonical: // Implements key sorting according to // https://fidoalliance.org/specs/fido-v2.0-ps-20190130/fido-client-to-authenticator-protocol-v2.0-ps-20190130.html#message-encoding int leftMt = (int)new CborInitialByte(left[0]).MajorType; int rightMt = (int)new CborInitialByte(right[0]).MajorType; if (leftMt != rightMt) { return leftMt - rightMt; } if (left.Length != right.Length) { return left.Length - right.Length; } return left.SequenceCompareTo(right); default: Debug.Fail("Invalid conformance mode used in encoding sort."); throw new Exception(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; namespace System.Formats.Cbor { /// <summary>Defines supported conformance modes for encoding and decoding CBOR data.</summary> public enum CborConformanceMode { /// <summary>Ensures that the CBOR data is well-formed, as specified in RFC7049.</summary> Lax, /// <summary> /// <para>Ensures that the CBOR data adheres to strict mode, as specified in RFC7049 section 3.10.</para> /// <para>Extends lax conformance with the following requirements:</para> /// <list type="bullet"> /// <item><description>Maps (major type 5) must not contain duplicate keys.</description></item> /// <item><description>Simple values (major type 7) must be encoded as small a possible and exclude the reserved values 24-31.</description></item> /// <item><description>UTF-8 string encodings must be valid.</description></item> /// </list> /// </summary> Strict, /// <summary> /// <para>Ensures that the CBOR data is canonical, as specified in RFC7049 section 3.9.</para> /// <para>Extends strict conformance with the following requirements:</para> /// <list type="bullet"> /// <item><description>Integers must be encoded as small as possible.</description></item> /// <item><description>Maps (major type 5) must contain keys sorted by encoding.</description></item> /// <item><description>Indefinite-length items must be made into definite-length items.</description></item> /// </list> /// </summary> Canonical, /// <summary> /// <para>Ensures that the CBOR data is canonical, as specified by the CTAP v2.0 standard, section 6.</para> /// <para>Extends strict conformance with the following requirements:</para> /// <list type="bullet"> /// <item><description>Maps (major type 5) must contain keys sorted by encoding.</description></item> /// <item><description>Indefinite-length items must be made into definite-length items.</description></item> /// <item><description>Integers must be encoded as small as possible.</description></item> /// <item><description>The representations of any floating-point values are not changed.</description></item> /// <item><description>CBOR tags (major type 6) are not permitted.</description></item> /// </list> /// </summary> Ctap2Canonical, } internal static class CborConformanceModeHelpers { private static readonly UTF8Encoding s_utf8EncodingLax = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false); private static readonly UTF8Encoding s_utf8EncodingStrict = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); public static void Validate(CborConformanceMode conformanceMode) { if (conformanceMode < CborConformanceMode.Lax || conformanceMode > CborConformanceMode.Ctap2Canonical) { throw new ArgumentOutOfRangeException(nameof(conformanceMode)); } } public static bool RequiresCanonicalIntegerRepresentation(CborConformanceMode conformanceMode) { switch (conformanceMode) { case CborConformanceMode.Lax: case CborConformanceMode.Strict: return false; case CborConformanceMode.Canonical: case CborConformanceMode.Ctap2Canonical: return true; default: throw new ArgumentOutOfRangeException(nameof(conformanceMode)); }; } public static bool RequiresPreservingFloatPrecision(CborConformanceMode conformanceMode) { switch (conformanceMode) { case CborConformanceMode.Lax: case CborConformanceMode.Strict: case CborConformanceMode.Canonical: return false; case CborConformanceMode.Ctap2Canonical: return true; default: throw new ArgumentOutOfRangeException(nameof(conformanceMode)); }; } public static bool RequiresUtf8Validation(CborConformanceMode conformanceMode) { switch (conformanceMode) { case CborConformanceMode.Lax: return false; case CborConformanceMode.Strict: case CborConformanceMode.Canonical: case CborConformanceMode.Ctap2Canonical: return true; default: throw new ArgumentOutOfRangeException(nameof(conformanceMode)); }; } public static Encoding GetUtf8Encoding(CborConformanceMode conformanceMode) { return conformanceMode == CborConformanceMode.Lax ? s_utf8EncodingLax : s_utf8EncodingStrict; } public static bool RequiresDefiniteLengthItems(CborConformanceMode conformanceMode) { switch (conformanceMode) { case CborConformanceMode.Lax: case CborConformanceMode.Strict: return false; case CborConformanceMode.Canonical: case CborConformanceMode.Ctap2Canonical: return true; default: throw new ArgumentOutOfRangeException(nameof(conformanceMode)); }; } public static bool AllowsTags(CborConformanceMode conformanceMode) { switch (conformanceMode) { case CborConformanceMode.Lax: case CborConformanceMode.Strict: case CborConformanceMode.Canonical: return true; case CborConformanceMode.Ctap2Canonical: return false; default: throw new ArgumentOutOfRangeException(nameof(conformanceMode)); }; } public static bool RequiresUniqueKeys(CborConformanceMode conformanceMode) { switch (conformanceMode) { case CborConformanceMode.Lax: return false; case CborConformanceMode.Strict: case CborConformanceMode.Canonical: case CborConformanceMode.Ctap2Canonical: return true; default: throw new ArgumentOutOfRangeException(nameof(conformanceMode)); }; } public static bool RequiresSortedKeys(CborConformanceMode conformanceMode) { switch (conformanceMode) { case CborConformanceMode.Strict: case CborConformanceMode.Lax: return false; case CborConformanceMode.Canonical: case CborConformanceMode.Ctap2Canonical: return true; default: throw new ArgumentOutOfRangeException(nameof(conformanceMode)); }; } public static bool RequireCanonicalSimpleValueEncodings(CborConformanceMode conformanceMode) { switch (conformanceMode) { case CborConformanceMode.Lax: return false; case CborConformanceMode.Strict: case CborConformanceMode.Canonical: case CborConformanceMode.Ctap2Canonical: return true; default: throw new ArgumentOutOfRangeException(nameof(conformanceMode)); } } public static int GetKeyEncodingHashCode(ReadOnlySpan<byte> encoding) { HashCode hash = default; #if NETCOREAPP hash.AddBytes(encoding); #else while (encoding.Length >= sizeof(int)) { hash.Add(MemoryMarshal.Read<int>(encoding)); encoding = encoding.Slice(sizeof(int)); } foreach (byte b in encoding) { hash.Add(b); } #endif return hash.ToHashCode(); } public static bool AreEqualKeyEncodings(ReadOnlySpan<byte> left, ReadOnlySpan<byte> right) { return left.SequenceEqual(right); } public static int CompareKeyEncodings(ReadOnlySpan<byte> left, ReadOnlySpan<byte> right, CborConformanceMode mode) { Debug.Assert(!left.IsEmpty && !right.IsEmpty); switch (mode) { case CborConformanceMode.Canonical: // Implements key sorting according to // https://tools.ietf.org/html/rfc7049#section-3.9 if (left.Length != right.Length) { return left.Length - right.Length; } return left.SequenceCompareTo(right); case CborConformanceMode.Ctap2Canonical: // Implements key sorting according to // https://fidoalliance.org/specs/fido-v2.0-ps-20190130/fido-client-to-authenticator-protocol-v2.0-ps-20190130.html#message-encoding int leftMt = (int)new CborInitialByte(left[0]).MajorType; int rightMt = (int)new CborInitialByte(right[0]).MajorType; if (leftMt != rightMt) { return leftMt - rightMt; } if (left.Length != right.Length) { return left.Length - right.Length; } return left.SequenceCompareTo(right); default: Debug.Fail("Invalid conformance mode used in encoding sort."); throw new Exception(); } } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/CborContentException.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.Serialization; namespace System.Formats.Cbor { /// <summary>The exception that's thrown when CBOR data is invalid.</summary> [Serializable] public class CborContentException : Exception { /// <summary> /// Initializes a new instance of the <see cref="CborContentException" /> class, using the provided message. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> public CborContentException(string? message) : base(message ?? SR.CborContentException_DefaultMessage) { } /// <summary> /// Initializes a new instance of the <see cref="CborContentException" /> class, /// using the provided message and exception that is the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="inner">The exception that is the cause of the current exception.</param> public CborContentException(string? message, Exception? inner) : base(message ?? SR.CborContentException_DefaultMessage, inner) { } /// <summary> /// Initializes a new instance of the <see cref="CborContentException" /> class with serialized data. /// </summary> /// <param name="info">The object that holds the serialized object data.</param> /// <param name="context">The contextual information about the source or destination.</param> protected CborContentException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
// 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.Serialization; namespace System.Formats.Cbor { /// <summary>The exception that's thrown when CBOR data is invalid.</summary> [Serializable] public class CborContentException : Exception { /// <summary> /// Initializes a new instance of the <see cref="CborContentException" /> class using the provided message. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> public CborContentException(string? message) : base(message ?? SR.CborContentException_DefaultMessage) { } /// <summary> /// Initializes a new instance of the <see cref="CborContentException" /> class, /// using the provided message and exception that is the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="inner">The exception that is the cause of the current exception.</param> public CborContentException(string? message, Exception? inner) : base(message ?? SR.CborContentException_DefaultMessage, inner) { } /// <summary> /// Initializes a new instance of the <see cref="CborContentException" /> class with serialized data. /// </summary> /// <param name="info">The object that holds the serialized object data.</param> /// <param name="context">The contextual information about the source or destination.</param> protected CborContentException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Reader/CborReader.Array.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.Formats.Cbor { public partial class CborReader { /// <summary>Reads the next data item as the start of an array (major type 4).</summary> /// <returns>The length of the definite-length array, or <see langword="null" /> if the array is indefinite-length.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public int? ReadStartArray() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Array); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } AdvanceBuffer(1); PushDataItem(CborMajorType.Array, null); return null; } else { ReadOnlySpan<byte> buffer = GetRemainingBytes(); int arrayLength = DecodeDefiniteLength(header, buffer, out int bytesRead); AdvanceBuffer(bytesRead); PushDataItem(CborMajorType.Array, arrayLength); return arrayLength; } } /// <summary>Reads the end of an array (major type 4).</summary> /// <exception cref="InvalidOperationException">The current context is not an array. /// -or- /// The reader is not at the end of the array.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data.</exception> public void ReadEndArray() { if (_definiteLength is null) { ValidateNextByteIsBreakByte(); PopDataItem(expectedType: CborMajorType.Array); AdvanceDataItemCounters(); AdvanceBuffer(1); } else { PopDataItem(expectedType: CborMajorType.Array); AdvanceDataItemCounters(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Formats.Cbor { public partial class CborReader { /// <summary>Reads the next data item as the start of an array (major type 4).</summary> /// <returns>The length of the definite-length array, or <see langword="null" /> if the array is indefinite-length.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public int? ReadStartArray() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Array); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } AdvanceBuffer(1); PushDataItem(CborMajorType.Array, null); return null; } else { ReadOnlySpan<byte> buffer = GetRemainingBytes(); int arrayLength = DecodeDefiniteLength(header, buffer, out int bytesRead); AdvanceBuffer(bytesRead); PushDataItem(CborMajorType.Array, arrayLength); return arrayLength; } } /// <summary>Reads the end of an array (major type 4).</summary> /// <exception cref="InvalidOperationException"><para>The current context is not an array.</para> /// <para>-or-</para> /// <para>The reader is not at the end of the array.</para></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para></exception> public void ReadEndArray() { if (_definiteLength is null) { ValidateNextByteIsBreakByte(); PopDataItem(expectedType: CborMajorType.Array); AdvanceDataItemCounters(); AdvanceBuffer(1); } else { PopDataItem(expectedType: CborMajorType.Array); AdvanceDataItemCounters(); } } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Reader/CborReader.Integer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; namespace System.Formats.Cbor { public partial class CborReader { // Implements major type 0,1 decoding per https://tools.ietf.org/html/rfc7049#section-2.1 /// <summary>Reads the next data item as a signed integer (major types 0,1)</summary> /// <returns>The decoded integer value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="OverflowException">The encoded integer is out of range for <see cref="int" />.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public int ReadInt32() { int value = checked((int)PeekSignedInteger(out int bytesRead)); AdvanceBuffer(bytesRead); AdvanceDataItemCounters(); return value; } /// <summary>Reads the next data item as an unsigned integer (major type 0).</summary> /// <returns>The decoded integer value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="OverflowException">The encoded integer is out of range for <see cref="uint" />.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> [CLSCompliant(false)] public uint ReadUInt32() { uint value = checked((uint)PeekUnsignedInteger(out int bytesRead)); AdvanceBuffer(bytesRead); AdvanceDataItemCounters(); return value; } /// <summary>Reads the next data item as a signed integer (major types 0,1)</summary> /// <returns>The decoded integer value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="OverflowException">The encoded integer is out of range for <see cref="long" />.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public long ReadInt64() { long value = PeekSignedInteger(out int bytesRead); AdvanceBuffer(bytesRead); AdvanceDataItemCounters(); return value; } /// <summary>Reads the next data item as an unsigned integer (major type 0).</summary> /// <returns>The decoded integer value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="OverflowException">The encoded integer is out of range for <see cref="ulong" />.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> [CLSCompliant(false)] public ulong ReadUInt64() { ulong value = PeekUnsignedInteger(out int bytesRead); AdvanceBuffer(bytesRead); AdvanceDataItemCounters(); return value; } /// <summary>Reads the next data item as a CBOR negative integer representation (major type 1).</summary> /// <returns>An unsigned integer denoting -1 minus the integer.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="OverflowException">The encoded integer is out of range for <see cref="uint" /></exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> /// <remarks> /// This method supports decoding integers between -18446744073709551616 and -1. /// Useful for handling values that do not fit in the <see cref="long" /> type. /// </remarks> [CLSCompliant(false)] public ulong ReadCborNegativeIntegerRepresentation() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.NegativeInteger); ulong value = DecodeUnsignedInteger(header, GetRemainingBytes(), out int bytesRead); AdvanceBuffer(bytesRead); AdvanceDataItemCounters(); return value; } private ulong PeekUnsignedInteger(out int bytesRead) { CborInitialByte header = PeekInitialByte(); switch (header.MajorType) { case CborMajorType.UnsignedInteger: ulong value = DecodeUnsignedInteger(header, GetRemainingBytes(), out bytesRead); return value; case CborMajorType.NegativeInteger: throw new OverflowException(); default: throw new InvalidOperationException(SR.Format(SR.Cbor_Reader_MajorTypeMismatch, (int)header.MajorType)); } } private long PeekSignedInteger(out int bytesRead) { CborInitialByte header = PeekInitialByte(); long value; switch (header.MajorType) { case CborMajorType.UnsignedInteger: value = checked((long)DecodeUnsignedInteger(header, GetRemainingBytes(), out bytesRead)); return value; case CborMajorType.NegativeInteger: value = checked(-1 - (long)DecodeUnsignedInteger(header, GetRemainingBytes(), out bytesRead)); return value; default: throw new InvalidOperationException(SR.Format(SR.Cbor_Reader_MajorTypeMismatch, (int)header.MajorType)); } } // Peek definite length for given data item private int DecodeDefiniteLength(CborInitialByte header, ReadOnlySpan<byte> data, out int bytesRead) { ulong length = DecodeUnsignedInteger(header, data, out bytesRead); // conservative check: ensure the buffer has the minimum required length for declared definite length. if (length > (ulong)(data.Length - bytesRead)) { throw new CborContentException(SR.Cbor_Reader_DefiniteLengthExceedsBufferSize); } return (int)length; } // Unsigned integer decoding https://tools.ietf.org/html/rfc7049#section-2.1 private ulong DecodeUnsignedInteger(CborInitialByte header, ReadOnlySpan<byte> data, out int bytesRead) { ulong result; switch (header.AdditionalInfo) { case CborAdditionalInfo x when (x < CborAdditionalInfo.Additional8BitData): bytesRead = 1; return (ulong)x; case CborAdditionalInfo.Additional8BitData: EnsureReadCapacity(data, 1 + sizeof(byte)); result = data[1]; if (result < (int)CborAdditionalInfo.Additional8BitData) { ValidateIsNonStandardIntegerRepresentationSupported(); } bytesRead = 1 + sizeof(byte); return result; case CborAdditionalInfo.Additional16BitData: EnsureReadCapacity(data, 1 + sizeof(ushort)); result = BinaryPrimitives.ReadUInt16BigEndian(data.Slice(1)); if (result <= byte.MaxValue) { ValidateIsNonStandardIntegerRepresentationSupported(); } bytesRead = 1 + sizeof(ushort); return result; case CborAdditionalInfo.Additional32BitData: EnsureReadCapacity(data, 1 + sizeof(uint)); result = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(1)); if (result <= ushort.MaxValue) { ValidateIsNonStandardIntegerRepresentationSupported(); } bytesRead = 1 + sizeof(uint); return result; case CborAdditionalInfo.Additional64BitData: EnsureReadCapacity(data, 1 + sizeof(ulong)); result = BinaryPrimitives.ReadUInt64BigEndian(data.Slice(1)); if (result <= uint.MaxValue) { ValidateIsNonStandardIntegerRepresentationSupported(); } bytesRead = 1 + sizeof(ulong); return result; default: throw new CborContentException(SR.Cbor_Reader_InvalidCbor_InvalidIntegerEncoding); } void ValidateIsNonStandardIntegerRepresentationSupported() { if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresCanonicalIntegerRepresentation(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_NonCanonicalIntegerRepresentation, ConformanceMode)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; namespace System.Formats.Cbor { public partial class CborReader { // Implements major type 0,1 decoding per https://tools.ietf.org/html/rfc7049#section-2.1 /// <summary>Reads the next data item as a signed integer (major types 0,1)</summary> /// <returns>The decoded integer value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="OverflowException">The encoded integer is out of range for <see cref="int" />.</exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public int ReadInt32() { int value = checked((int)PeekSignedInteger(out int bytesRead)); AdvanceBuffer(bytesRead); AdvanceDataItemCounters(); return value; } /// <summary>Reads the next data item as an unsigned integer (major type 0).</summary> /// <returns>The decoded integer value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="OverflowException">The encoded integer is out of range for <see cref="uint" />.</exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> [CLSCompliant(false)] public uint ReadUInt32() { uint value = checked((uint)PeekUnsignedInteger(out int bytesRead)); AdvanceBuffer(bytesRead); AdvanceDataItemCounters(); return value; } /// <summary>Reads the next data item as a signed integer (major types 0,1)</summary> /// <returns>The decoded integer value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="OverflowException">The encoded integer is out of range for <see cref="long" />.</exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public long ReadInt64() { long value = PeekSignedInteger(out int bytesRead); AdvanceBuffer(bytesRead); AdvanceDataItemCounters(); return value; } /// <summary>Reads the next data item as an unsigned integer (major type 0).</summary> /// <returns>The decoded integer value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="OverflowException">The encoded integer is out of range for <see cref="ulong" />.</exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> [CLSCompliant(false)] public ulong ReadUInt64() { ulong value = PeekUnsignedInteger(out int bytesRead); AdvanceBuffer(bytesRead); AdvanceDataItemCounters(); return value; } /// <summary>Reads the next data item as a CBOR negative integer representation (major type 1).</summary> /// <returns>An unsigned integer denoting -1 minus the integer.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="OverflowException">The encoded integer is out of range for <see cref="uint" /></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> /// <remarks> /// This method supports decoding integers between -18446744073709551616 and -1. /// Useful for handling values that do not fit in the <see cref="long" /> type. /// </remarks> [CLSCompliant(false)] public ulong ReadCborNegativeIntegerRepresentation() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.NegativeInteger); ulong value = DecodeUnsignedInteger(header, GetRemainingBytes(), out int bytesRead); AdvanceBuffer(bytesRead); AdvanceDataItemCounters(); return value; } private ulong PeekUnsignedInteger(out int bytesRead) { CborInitialByte header = PeekInitialByte(); switch (header.MajorType) { case CborMajorType.UnsignedInteger: ulong value = DecodeUnsignedInteger(header, GetRemainingBytes(), out bytesRead); return value; case CborMajorType.NegativeInteger: throw new OverflowException(); default: throw new InvalidOperationException(SR.Format(SR.Cbor_Reader_MajorTypeMismatch, (int)header.MajorType)); } } private long PeekSignedInteger(out int bytesRead) { CborInitialByte header = PeekInitialByte(); long value; switch (header.MajorType) { case CborMajorType.UnsignedInteger: value = checked((long)DecodeUnsignedInteger(header, GetRemainingBytes(), out bytesRead)); return value; case CborMajorType.NegativeInteger: value = checked(-1 - (long)DecodeUnsignedInteger(header, GetRemainingBytes(), out bytesRead)); return value; default: throw new InvalidOperationException(SR.Format(SR.Cbor_Reader_MajorTypeMismatch, (int)header.MajorType)); } } // Peek definite length for given data item private int DecodeDefiniteLength(CborInitialByte header, ReadOnlySpan<byte> data, out int bytesRead) { ulong length = DecodeUnsignedInteger(header, data, out bytesRead); // conservative check: ensure the buffer has the minimum required length for declared definite length. if (length > (ulong)(data.Length - bytesRead)) { throw new CborContentException(SR.Cbor_Reader_DefiniteLengthExceedsBufferSize); } return (int)length; } // Unsigned integer decoding https://tools.ietf.org/html/rfc7049#section-2.1 private ulong DecodeUnsignedInteger(CborInitialByte header, ReadOnlySpan<byte> data, out int bytesRead) { ulong result; switch (header.AdditionalInfo) { case CborAdditionalInfo x when (x < CborAdditionalInfo.Additional8BitData): bytesRead = 1; return (ulong)x; case CborAdditionalInfo.Additional8BitData: EnsureReadCapacity(data, 1 + sizeof(byte)); result = data[1]; if (result < (int)CborAdditionalInfo.Additional8BitData) { ValidateIsNonStandardIntegerRepresentationSupported(); } bytesRead = 1 + sizeof(byte); return result; case CborAdditionalInfo.Additional16BitData: EnsureReadCapacity(data, 1 + sizeof(ushort)); result = BinaryPrimitives.ReadUInt16BigEndian(data.Slice(1)); if (result <= byte.MaxValue) { ValidateIsNonStandardIntegerRepresentationSupported(); } bytesRead = 1 + sizeof(ushort); return result; case CborAdditionalInfo.Additional32BitData: EnsureReadCapacity(data, 1 + sizeof(uint)); result = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(1)); if (result <= ushort.MaxValue) { ValidateIsNonStandardIntegerRepresentationSupported(); } bytesRead = 1 + sizeof(uint); return result; case CborAdditionalInfo.Additional64BitData: EnsureReadCapacity(data, 1 + sizeof(ulong)); result = BinaryPrimitives.ReadUInt64BigEndian(data.Slice(1)); if (result <= uint.MaxValue) { ValidateIsNonStandardIntegerRepresentationSupported(); } bytesRead = 1 + sizeof(ulong); return result; default: throw new CborContentException(SR.Cbor_Reader_InvalidCbor_InvalidIntegerEncoding); } void ValidateIsNonStandardIntegerRepresentationSupported() { if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresCanonicalIntegerRepresentation(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_NonCanonicalIntegerRepresentation, ConformanceMode)); } } } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Reader/CborReader.Map.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; namespace System.Formats.Cbor { public partial class CborReader { private KeyEncodingComparer? _keyEncodingComparer; private Stack<HashSet<(int Offset, int Length)>>? _pooledKeyEncodingRangeAllocations; /// <summary>Reads the next data item as the start of a map (major type 5).</summary> /// <returns>The number of key-value pairs in a definite-length map, or <see langword="null" /> if the map is indefinite-length.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> /// <remarks> /// Map contents are consumed as if they were arrays twice the length of the map's declared size. /// For instance, a map of size 1 containing a key of type <see cref="int" /> with a value of type <see cref="string" /> /// must be consumed by successive calls to <see cref="ReadInt32" /> and <see cref="ReadTextString" />. /// It is up to the caller to keep track of whether the next value is a key or a value. /// Fundamentally, this is a technical restriction stemming from the fact that CBOR allows keys of arbitrary type, /// for instance a map can contain keys that are maps themselves. /// </remarks> public int? ReadStartMap() { int? length; CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Map); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_RequiresDefiniteLengthItems, ConformanceMode)); } AdvanceBuffer(1); PushDataItem(CborMajorType.Map, null); length = null; } else { ReadOnlySpan<byte> buffer = GetRemainingBytes(); int mapSize = DecodeDefiniteLength(header, buffer, out int bytesRead); if (2 * (ulong)mapSize > (ulong)(buffer.Length - bytesRead)) { throw new CborContentException(SR.Cbor_Reader_DefiniteLengthExceedsBufferSize); } AdvanceBuffer(bytesRead); PushDataItem(CborMajorType.Map, 2 * mapSize); length = (int)mapSize; } _currentKeyOffset = _offset; return length; } /// <summary>Reads the end of a map (major type 5).</summary> /// <exception cref="InvalidOperationException">The current context is not a map. /// -or- /// The reader is not at the end of the map.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public void ReadEndMap() { if (_definiteLength is null) { ValidateNextByteIsBreakByte(); if (_itemsRead % 2 != 0) { throw new CborContentException(SR.Cbor_Reader_InvalidCbor_KeyMissingValue); } PopDataItem(expectedType: CborMajorType.Map); AdvanceDataItemCounters(); AdvanceBuffer(1); } else { PopDataItem(expectedType: CborMajorType.Map); AdvanceDataItemCounters(); } } // // Map decoding conformance // // conformance book-keeping after a key data item has been read private void HandleMapKeyRead() { Debug.Assert(_currentKeyOffset != null && _itemsRead % 2 == 0); (int Offset, int Length) currentKeyRange = (_currentKeyOffset.Value, _offset - _currentKeyOffset.Value); if (_isConformanceModeCheckEnabled) { if (CborConformanceModeHelpers.RequiresSortedKeys(ConformanceMode)) { ValidateSortedKeyEncoding(currentKeyRange); } else if (CborConformanceModeHelpers.RequiresUniqueKeys(ConformanceMode)) { // NB uniquess is validated separately in conformance modes requiring sorted keys ValidateKeyUniqueness(currentKeyRange); } } } // conformance book-keeping after a value data item has been read private void HandleMapValueRead() { Debug.Assert(_currentKeyOffset != null && _itemsRead % 2 != 0); _currentKeyOffset = _offset; } private void ValidateSortedKeyEncoding((int Offset, int Length) currentKeyEncodingRange) { Debug.Assert(_currentKeyOffset != null); if (_previousKeyEncodingRange != null) { (int Offset, int Length) previousKeyEncodingRange = _previousKeyEncodingRange.Value; ReadOnlySpan<byte> buffer = _data.Span; ReadOnlySpan<byte> previousKeyEncoding = buffer.Slice(previousKeyEncodingRange.Offset, previousKeyEncodingRange.Length); ReadOnlySpan<byte> currentKeyEncoding = buffer.Slice(currentKeyEncodingRange.Offset, currentKeyEncodingRange.Length); int cmp = CborConformanceModeHelpers.CompareKeyEncodings(previousKeyEncoding, currentKeyEncoding, ConformanceMode); if (cmp > 0) { ResetBuffer(currentKeyEncodingRange.Offset); throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_KeysNotInSortedOrder, ConformanceMode)); } else if (cmp == 0 && CborConformanceModeHelpers.RequiresUniqueKeys(ConformanceMode)) { ResetBuffer(currentKeyEncodingRange.Offset); throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_ContainsDuplicateKeys, ConformanceMode)); } } _previousKeyEncodingRange = currentKeyEncodingRange; } private void ValidateKeyUniqueness((int Offset, int Length) currentKeyEncodingRange) { Debug.Assert(_currentKeyOffset != null); HashSet<(int Offset, int Length)> keyEncodingRanges = GetKeyEncodingRanges(); if (!keyEncodingRanges.Add(currentKeyEncodingRange)) { ResetBuffer(currentKeyEncodingRange.Offset); throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_ContainsDuplicateKeys, ConformanceMode)); } } private HashSet<(int Offset, int Length)> GetKeyEncodingRanges() { if (_keyEncodingRanges != null) { return _keyEncodingRanges; } if (_pooledKeyEncodingRangeAllocations != null && _pooledKeyEncodingRangeAllocations.TryPop(out HashSet<(int Offset, int Length)>? result)) { result.Clear(); return _keyEncodingRanges = result; } _keyEncodingComparer ??= new KeyEncodingComparer(this); return _keyEncodingRanges = new HashSet<(int Offset, int Length)>(_keyEncodingComparer); } private void ReturnKeyEncodingRangeAllocation(HashSet<(int Offset, int Length)>? allocation) { if (allocation != null) { _pooledKeyEncodingRangeAllocations ??= new Stack<HashSet<(int Offset, int Length)>>(); _pooledKeyEncodingRangeAllocations.Push(allocation); } } // Comparing buffer slices up to their binary content private sealed class KeyEncodingComparer : IEqualityComparer<(int Offset, int Length)> { private readonly CborReader _reader; public KeyEncodingComparer(CborReader reader) { _reader = reader; } private ReadOnlySpan<byte> GetKeyEncoding((int Offset, int Length) range) { return _reader._data.Span.Slice(range.Offset, range.Length); } public int GetHashCode((int Offset, int Length) value) { return CborConformanceModeHelpers.GetKeyEncodingHashCode(GetKeyEncoding(value)); } public bool Equals((int Offset, int Length) x, (int Offset, int Length) y) { return CborConformanceModeHelpers.AreEqualKeyEncodings(GetKeyEncoding(x), GetKeyEncoding(y)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; namespace System.Formats.Cbor { public partial class CborReader { private KeyEncodingComparer? _keyEncodingComparer; private Stack<HashSet<(int Offset, int Length)>>? _pooledKeyEncodingRangeAllocations; /// <summary>Reads the next data item as the start of a map (major type 5).</summary> /// <returns>The number of key-value pairs in a definite-length map, or <see langword="null" /> if the map is indefinite-length.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> /// <remarks> /// Map contents are consumed as if they were arrays twice the length of the map's declared size. /// For instance, a map of size 1 containing a key of type <see cref="int" /> with a value of type <see cref="string" /> /// must be consumed by successive calls to <see cref="ReadInt32" /> and <see cref="ReadTextString" />. /// It is up to the caller to keep track of whether the next value is a key or a value. /// Fundamentally, this is a technical restriction stemming from the fact that CBOR allows keys of arbitrary type, /// for instance a map can contain keys that are maps themselves. /// </remarks> public int? ReadStartMap() { int? length; CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Map); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_RequiresDefiniteLengthItems, ConformanceMode)); } AdvanceBuffer(1); PushDataItem(CborMajorType.Map, null); length = null; } else { ReadOnlySpan<byte> buffer = GetRemainingBytes(); int mapSize = DecodeDefiniteLength(header, buffer, out int bytesRead); if (2 * (ulong)mapSize > (ulong)(buffer.Length - bytesRead)) { throw new CborContentException(SR.Cbor_Reader_DefiniteLengthExceedsBufferSize); } AdvanceBuffer(bytesRead); PushDataItem(CborMajorType.Map, 2 * mapSize); length = (int)mapSize; } _currentKeyOffset = _offset; return length; } /// <summary>Reads the end of a map (major type 5).</summary> /// <exception cref="InvalidOperationException"><para>The current context is not a map.</para> /// <para>-or-</para> /// <para>The reader is not at the end of the map.</para></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public void ReadEndMap() { if (_definiteLength is null) { ValidateNextByteIsBreakByte(); if (_itemsRead % 2 != 0) { throw new CborContentException(SR.Cbor_Reader_InvalidCbor_KeyMissingValue); } PopDataItem(expectedType: CborMajorType.Map); AdvanceDataItemCounters(); AdvanceBuffer(1); } else { PopDataItem(expectedType: CborMajorType.Map); AdvanceDataItemCounters(); } } // // Map decoding conformance // // conformance book-keeping after a key data item has been read private void HandleMapKeyRead() { Debug.Assert(_currentKeyOffset != null && _itemsRead % 2 == 0); (int Offset, int Length) currentKeyRange = (_currentKeyOffset.Value, _offset - _currentKeyOffset.Value); if (_isConformanceModeCheckEnabled) { if (CborConformanceModeHelpers.RequiresSortedKeys(ConformanceMode)) { ValidateSortedKeyEncoding(currentKeyRange); } else if (CborConformanceModeHelpers.RequiresUniqueKeys(ConformanceMode)) { // NB uniquess is validated separately in conformance modes requiring sorted keys ValidateKeyUniqueness(currentKeyRange); } } } // conformance book-keeping after a value data item has been read private void HandleMapValueRead() { Debug.Assert(_currentKeyOffset != null && _itemsRead % 2 != 0); _currentKeyOffset = _offset; } private void ValidateSortedKeyEncoding((int Offset, int Length) currentKeyEncodingRange) { Debug.Assert(_currentKeyOffset != null); if (_previousKeyEncodingRange != null) { (int Offset, int Length) previousKeyEncodingRange = _previousKeyEncodingRange.Value; ReadOnlySpan<byte> buffer = _data.Span; ReadOnlySpan<byte> previousKeyEncoding = buffer.Slice(previousKeyEncodingRange.Offset, previousKeyEncodingRange.Length); ReadOnlySpan<byte> currentKeyEncoding = buffer.Slice(currentKeyEncodingRange.Offset, currentKeyEncodingRange.Length); int cmp = CborConformanceModeHelpers.CompareKeyEncodings(previousKeyEncoding, currentKeyEncoding, ConformanceMode); if (cmp > 0) { ResetBuffer(currentKeyEncodingRange.Offset); throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_KeysNotInSortedOrder, ConformanceMode)); } else if (cmp == 0 && CborConformanceModeHelpers.RequiresUniqueKeys(ConformanceMode)) { ResetBuffer(currentKeyEncodingRange.Offset); throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_ContainsDuplicateKeys, ConformanceMode)); } } _previousKeyEncodingRange = currentKeyEncodingRange; } private void ValidateKeyUniqueness((int Offset, int Length) currentKeyEncodingRange) { Debug.Assert(_currentKeyOffset != null); HashSet<(int Offset, int Length)> keyEncodingRanges = GetKeyEncodingRanges(); if (!keyEncodingRanges.Add(currentKeyEncodingRange)) { ResetBuffer(currentKeyEncodingRange.Offset); throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_ContainsDuplicateKeys, ConformanceMode)); } } private HashSet<(int Offset, int Length)> GetKeyEncodingRanges() { if (_keyEncodingRanges != null) { return _keyEncodingRanges; } if (_pooledKeyEncodingRangeAllocations != null && _pooledKeyEncodingRangeAllocations.TryPop(out HashSet<(int Offset, int Length)>? result)) { result.Clear(); return _keyEncodingRanges = result; } _keyEncodingComparer ??= new KeyEncodingComparer(this); return _keyEncodingRanges = new HashSet<(int Offset, int Length)>(_keyEncodingComparer); } private void ReturnKeyEncodingRangeAllocation(HashSet<(int Offset, int Length)>? allocation) { if (allocation != null) { _pooledKeyEncodingRangeAllocations ??= new Stack<HashSet<(int Offset, int Length)>>(); _pooledKeyEncodingRangeAllocations.Push(allocation); } } // Comparing buffer slices up to their binary content private sealed class KeyEncodingComparer : IEqualityComparer<(int Offset, int Length)> { private readonly CborReader _reader; public KeyEncodingComparer(CborReader reader) { _reader = reader; } private ReadOnlySpan<byte> GetKeyEncoding((int Offset, int Length) range) { return _reader._data.Span.Slice(range.Offset, range.Length); } public int GetHashCode((int Offset, int Length) value) { return CborConformanceModeHelpers.GetKeyEncodingHashCode(GetKeyEncoding(value)); } public bool Equals((int Offset, int Length) x, (int Offset, int Length) y) { return CborConformanceModeHelpers.AreEqualKeyEncodings(GetKeyEncoding(x), GetKeyEncoding(y)); } } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Reader/CborReader.Simple.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; namespace System.Formats.Cbor { public partial class CborReader { /// <summary>Reads the next data item as a single-precision floating point number (major type 7).</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type. /// -or- /// The next simple value is not a floating-point number encoding. /// -or- /// The encoded value is a double-precision float</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public float ReadSingle() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Simple); ReadOnlySpan<byte> buffer = GetRemainingBytes(); float result; switch (header.AdditionalInfo) { case CborAdditionalInfo.Additional16BitData: EnsureReadCapacity(buffer, 1 + sizeof(ushort)); result = HalfHelpers.HalfToFloat(CborHelpers.ReadHalfBigEndian(buffer.Slice(1))); AdvanceBuffer(1 + sizeof(ushort)); AdvanceDataItemCounters(); return result; case CborAdditionalInfo.Additional32BitData: EnsureReadCapacity(buffer, 1 + sizeof(float)); result = CborHelpers.ReadSingleBigEndian(buffer.Slice(1)); AdvanceBuffer(1 + sizeof(float)); AdvanceDataItemCounters(); return result; case CborAdditionalInfo.Additional64BitData: throw new InvalidOperationException(SR.Cbor_Reader_ReadingAsLowerPrecision); default: throw new InvalidOperationException(SR.Cbor_Reader_NotAFloatEncoding); } } /// <summary>Reads the next data item as a double-precision floating point number (major type 7).</summary> /// <returns>The decoded <see cref="double" /> value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type. /// -or- /// The next simple value is not a floating-point number encoding</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public double ReadDouble() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Simple); ReadOnlySpan<byte> buffer = GetRemainingBytes(); double result; switch (header.AdditionalInfo) { case CborAdditionalInfo.Additional16BitData: EnsureReadCapacity(buffer, 1 + sizeof(short)); result = HalfHelpers.HalfToDouble(CborHelpers.ReadHalfBigEndian(buffer.Slice(1))); AdvanceBuffer(1 + sizeof(short)); AdvanceDataItemCounters(); return result; case CborAdditionalInfo.Additional32BitData: EnsureReadCapacity(buffer, 1 + sizeof(float)); result = CborHelpers.ReadSingleBigEndian(buffer.Slice(1)); AdvanceBuffer(1 + sizeof(float)); AdvanceDataItemCounters(); return result; case CborAdditionalInfo.Additional64BitData: EnsureReadCapacity(buffer, 1 + sizeof(double)); result = CborHelpers.ReadDoubleBigEndian(buffer.Slice(1)); AdvanceBuffer(1 + sizeof(double)); AdvanceDataItemCounters(); return result; default: throw new InvalidOperationException(SR.Cbor_Reader_NotAFloatEncoding); } } /// <summary>Reads the next data item as a boolean value (major type 7).</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type. /// -or- /// The next simple value is not a boolean encoding</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public bool ReadBoolean() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Simple); bool result = header.AdditionalInfo switch { (CborAdditionalInfo)CborSimpleValue.False => false, (CborAdditionalInfo)CborSimpleValue.True => true, _ => throw new InvalidOperationException(SR.Cbor_Reader_NotABooleanEncoding), }; AdvanceBuffer(1); AdvanceDataItemCounters(); return result; } /// <summary>Reads the next data item as a <see langword="null" /> value (major type 7).</summary> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type. /// -or- /// The next simple value is not a <see langword="null" /> value encoding.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public void ReadNull() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Simple); switch (header.AdditionalInfo) { case (CborAdditionalInfo)CborSimpleValue.Null: AdvanceBuffer(1); AdvanceDataItemCounters(); return; default: throw new InvalidOperationException(SR.Cbor_Reader_NotANullEncoding); } } /// <summary>Reads the next data item as a CBOR simple value (major type 7).</summary> /// <returns>The decoded CBOR simple value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type. /// -or- /// The next simple value is not a simple value encoding.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public CborSimpleValue ReadSimpleValue() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Simple); switch (header.AdditionalInfo) { case CborAdditionalInfo info when info < CborAdditionalInfo.Additional8BitData: AdvanceBuffer(1); AdvanceDataItemCounters(); return (CborSimpleValue)header.AdditionalInfo; case CborAdditionalInfo.Additional8BitData: EnsureReadCapacity(2); byte value = _data.Span[_offset + 1]; if (value <= (byte)CborAdditionalInfo.IndefiniteLength && _isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequireCanonicalSimpleValueEncodings(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_InvalidSimpleValueEncoding, ConformanceMode)); } AdvanceBuffer(2); AdvanceDataItemCounters(); return (CborSimpleValue)value; default: throw new InvalidOperationException(SR.Cbor_Reader_NotASimpleValueEncoding); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; namespace System.Formats.Cbor { public partial class CborReader { /// <summary>Reads the next data item as a single-precision floating point number (major type 7).</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException"><para>The next data item does not have the correct major type.</para> /// <para>-or-</para> /// <para>The next simple value is not a floating-point number encoding.</para> /// <para>-or-</para> /// <para>The encoded value is a double-precision float.</para></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public float ReadSingle() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Simple); ReadOnlySpan<byte> buffer = GetRemainingBytes(); float result; switch (header.AdditionalInfo) { case CborAdditionalInfo.Additional16BitData: EnsureReadCapacity(buffer, 1 + sizeof(ushort)); result = HalfHelpers.HalfToFloat(CborHelpers.ReadHalfBigEndian(buffer.Slice(1))); AdvanceBuffer(1 + sizeof(ushort)); AdvanceDataItemCounters(); return result; case CborAdditionalInfo.Additional32BitData: EnsureReadCapacity(buffer, 1 + sizeof(float)); result = CborHelpers.ReadSingleBigEndian(buffer.Slice(1)); AdvanceBuffer(1 + sizeof(float)); AdvanceDataItemCounters(); return result; case CborAdditionalInfo.Additional64BitData: throw new InvalidOperationException(SR.Cbor_Reader_ReadingAsLowerPrecision); default: throw new InvalidOperationException(SR.Cbor_Reader_NotAFloatEncoding); } } /// <summary>Reads the next data item as a double-precision floating point number (major type 7).</summary> /// <returns>The decoded <see cref="double" /> value.</returns> /// <exception cref="InvalidOperationException"><para>The next data item does not have the correct major type.</para> /// <para>-or-</para> /// <para>The next simple value is not a floating-point number encoding.</para></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public double ReadDouble() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Simple); ReadOnlySpan<byte> buffer = GetRemainingBytes(); double result; switch (header.AdditionalInfo) { case CborAdditionalInfo.Additional16BitData: EnsureReadCapacity(buffer, 1 + sizeof(short)); result = HalfHelpers.HalfToDouble(CborHelpers.ReadHalfBigEndian(buffer.Slice(1))); AdvanceBuffer(1 + sizeof(short)); AdvanceDataItemCounters(); return result; case CborAdditionalInfo.Additional32BitData: EnsureReadCapacity(buffer, 1 + sizeof(float)); result = CborHelpers.ReadSingleBigEndian(buffer.Slice(1)); AdvanceBuffer(1 + sizeof(float)); AdvanceDataItemCounters(); return result; case CborAdditionalInfo.Additional64BitData: EnsureReadCapacity(buffer, 1 + sizeof(double)); result = CborHelpers.ReadDoubleBigEndian(buffer.Slice(1)); AdvanceBuffer(1 + sizeof(double)); AdvanceDataItemCounters(); return result; default: throw new InvalidOperationException(SR.Cbor_Reader_NotAFloatEncoding); } } /// <summary>Reads the next data item as a boolean value (major type 7).</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException"><para>The next data item does not have the correct major type.</para> /// <para>-or-</para> /// <para>The next simple value is not a boolean encoding.</para></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public bool ReadBoolean() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Simple); bool result = header.AdditionalInfo switch { (CborAdditionalInfo)CborSimpleValue.False => false, (CborAdditionalInfo)CborSimpleValue.True => true, _ => throw new InvalidOperationException(SR.Cbor_Reader_NotABooleanEncoding), }; AdvanceBuffer(1); AdvanceDataItemCounters(); return result; } /// <summary>Reads the next data item as a <see langword="null" /> value (major type 7).</summary> /// <exception cref="InvalidOperationException"><para>The next data item does not have the correct major type.</para> /// <para>-or-</para> /// <para>The next simple value is not a <see langword="null" /> value encoding.</para></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public void ReadNull() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Simple); switch (header.AdditionalInfo) { case (CborAdditionalInfo)CborSimpleValue.Null: AdvanceBuffer(1); AdvanceDataItemCounters(); return; default: throw new InvalidOperationException(SR.Cbor_Reader_NotANullEncoding); } } /// <summary>Reads the next data item as a CBOR simple value (major type 7).</summary> /// <returns>The decoded CBOR simple value.</returns> /// <exception cref="InvalidOperationException"><para>The next data item does not have the correct major type.</para> /// <para>-or-</para> /// <para>The next simple value is not a simple value encoding.</para></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public CborSimpleValue ReadSimpleValue() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Simple); switch (header.AdditionalInfo) { case CborAdditionalInfo info when info < CborAdditionalInfo.Additional8BitData: AdvanceBuffer(1); AdvanceDataItemCounters(); return (CborSimpleValue)header.AdditionalInfo; case CborAdditionalInfo.Additional8BitData: EnsureReadCapacity(2); byte value = _data.Span[_offset + 1]; if (value <= (byte)CborAdditionalInfo.IndefiniteLength && _isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequireCanonicalSimpleValueEncodings(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_InvalidSimpleValueEncoding, ConformanceMode)); } AdvanceBuffer(2); AdvanceDataItemCounters(); return (CborSimpleValue)value; default: throw new InvalidOperationException(SR.Cbor_Reader_NotASimpleValueEncoding); } } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Reader/CborReader.Simple.netcoreapp.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; namespace System.Formats.Cbor { public partial class CborReader { /// <summary>Reads the next data item as a half-precision floating point number (major type 7).</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type. /// -or- /// The next simple value is not a floating-point number encoding. /// -or- /// The encoded value is a double-precision float.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public Half ReadHalf() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Simple); ReadOnlySpan<byte> buffer = GetRemainingBytes(); Half result; switch (header.AdditionalInfo) { case CborAdditionalInfo.Additional16BitData: EnsureReadCapacity(buffer, 1 + sizeof(short)); result = BinaryPrimitives.ReadHalfBigEndian(buffer.Slice(1)); AdvanceBuffer(1 + sizeof(short)); AdvanceDataItemCounters(); return result; case CborAdditionalInfo.Additional32BitData: case CborAdditionalInfo.Additional64BitData: throw new InvalidOperationException(SR.Cbor_Reader_ReadingAsLowerPrecision); default: throw new InvalidOperationException(SR.Cbor_Reader_NotAFloatEncoding); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; namespace System.Formats.Cbor { public partial class CborReader { /// <summary>Reads the next data item as a half-precision floating point number (major type 7).</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException"><para>The next data item does not have the correct major type.</para> /// <para>-or-</para> /// <para>The next simple value is not a floating-point number encoding.</para> /// <para>-or-</para> /// <para>The encoded value is a double-precision float.</para></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public Half ReadHalf() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Simple); ReadOnlySpan<byte> buffer = GetRemainingBytes(); Half result; switch (header.AdditionalInfo) { case CborAdditionalInfo.Additional16BitData: EnsureReadCapacity(buffer, 1 + sizeof(short)); result = BinaryPrimitives.ReadHalfBigEndian(buffer.Slice(1)); AdvanceBuffer(1 + sizeof(short)); AdvanceDataItemCounters(); return result; case CborAdditionalInfo.Additional32BitData: case CborAdditionalInfo.Additional64BitData: throw new InvalidOperationException(SR.Cbor_Reader_ReadingAsLowerPrecision); default: throw new InvalidOperationException(SR.Cbor_Reader_NotAFloatEncoding); } } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Reader/CborReader.SkipValue.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.Formats.Cbor { public partial class CborReader { /// <summary>Reads the contents of the next value, discarding the result and advancing the reader.</summary> /// <param name="disableConformanceModeChecks"><see langword="true" /> to disable conformance mode validation for the skipped values, equivalent to using <see cref="CborConformanceMode.Lax" />; otherwise, <see langword="false" />.</param> /// <exception cref="InvalidOperationException">The reader is not at the start of new value.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public void SkipValue(bool disableConformanceModeChecks = false) { SkipToAncestor(0, disableConformanceModeChecks); } /// <summary>Reads the remaining contents of the current value context, discarding results and advancing the reader to the next value in the parent context.</summary> /// <param name="disableConformanceModeChecks"><see langword="true" /> to disable conformance mode validation for the skipped values, equivalent to using <see cref="CborConformanceMode.Lax" />; otherwise, <see langword="false" />.</param> /// <exception cref="InvalidOperationException">The reader is at the root context</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public void SkipToParent(bool disableConformanceModeChecks = false) { if (_currentMajorType is null) { throw new InvalidOperationException(SR.Cbor_Reader_IsAtRootContext); } SkipToAncestor(1, disableConformanceModeChecks); } private void SkipToAncestor(int depth, bool disableConformanceModeChecks) { Debug.Assert(0 <= depth && depth <= CurrentDepth); Checkpoint checkpoint = CreateCheckpoint(); _isConformanceModeCheckEnabled = !disableConformanceModeChecks; try { do { SkipNextNode(ref depth); } while (depth > 0); } catch { RestoreCheckpoint(in checkpoint); throw; } finally { _isConformanceModeCheckEnabled = true; } } private void SkipNextNode(ref int depth) { CborReaderState state; // peek, skipping any tags we might encounter while ((state = PeekStateCore()) == CborReaderState.Tag) { ReadTag(); } switch (state) { case CborReaderState.UnsignedInteger: ReadUInt64(); break; case CborReaderState.NegativeInteger: ReadCborNegativeIntegerRepresentation(); break; case CborReaderState.ByteString: SkipString(type: CborMajorType.ByteString); break; case CborReaderState.TextString: SkipString(type: CborMajorType.TextString); break; case CborReaderState.StartIndefiniteLengthByteString: ReadStartIndefiniteLengthByteString(); depth++; break; case CborReaderState.EndIndefiniteLengthByteString: ValidatePop(state, depth); ReadEndIndefiniteLengthByteString(); depth--; break; case CborReaderState.StartIndefiniteLengthTextString: ReadStartIndefiniteLengthTextString(); depth++; break; case CborReaderState.EndIndefiniteLengthTextString: ValidatePop(state, depth); ReadEndIndefiniteLengthTextString(); depth--; break; case CborReaderState.StartArray: ReadStartArray(); depth++; break; case CborReaderState.EndArray: ValidatePop(state, depth); ReadEndArray(); depth--; break; case CborReaderState.StartMap: ReadStartMap(); depth++; break; case CborReaderState.EndMap: ValidatePop(state, depth); ReadEndMap(); depth--; break; case CborReaderState.HalfPrecisionFloat: case CborReaderState.SinglePrecisionFloat: case CborReaderState.DoublePrecisionFloat: ReadDouble(); break; case CborReaderState.Null: case CborReaderState.Boolean: case CborReaderState.SimpleValue: ReadSimpleValue(); break; default: throw new InvalidOperationException(SR.Format(SR.Cbor_Reader_Skip_InvalidState, state)); } // guards against cases where the caller attempts to skip when reader is not positioned at the start of a value static void ValidatePop(CborReaderState state, int depth) { if (depth == 0) { throw new InvalidOperationException(SR.Format(SR.Cbor_Reader_Skip_InvalidState, state)); } } } } }
// 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.Formats.Cbor { public partial class CborReader { /// <summary>Reads the contents of the next value, discarding the result and advancing the reader.</summary> /// <param name="disableConformanceModeChecks"><see langword="true" /> to disable conformance mode validation for the skipped values, equivalent to using <see cref="CborConformanceMode.Lax" />; otherwise, <see langword="false" />.</param> /// <exception cref="InvalidOperationException">The reader is not at the start of new value.</exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public void SkipValue(bool disableConformanceModeChecks = false) { SkipToAncestor(0, disableConformanceModeChecks); } /// <summary>Reads the remaining contents of the current value context, discarding results and advancing the reader to the next value in the parent context.</summary> /// <param name="disableConformanceModeChecks"><see langword="true" /> to disable conformance mode validation for the skipped values, equivalent to using <see cref="CborConformanceMode.Lax" />; otherwise, <see langword="false" />.</param> /// <exception cref="InvalidOperationException">The reader is at the root context</exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public void SkipToParent(bool disableConformanceModeChecks = false) { if (_currentMajorType is null) { throw new InvalidOperationException(SR.Cbor_Reader_IsAtRootContext); } SkipToAncestor(1, disableConformanceModeChecks); } private void SkipToAncestor(int depth, bool disableConformanceModeChecks) { Debug.Assert(0 <= depth && depth <= CurrentDepth); Checkpoint checkpoint = CreateCheckpoint(); _isConformanceModeCheckEnabled = !disableConformanceModeChecks; try { do { SkipNextNode(ref depth); } while (depth > 0); } catch { RestoreCheckpoint(in checkpoint); throw; } finally { _isConformanceModeCheckEnabled = true; } } private void SkipNextNode(ref int depth) { CborReaderState state; // peek, skipping any tags we might encounter while ((state = PeekStateCore()) == CborReaderState.Tag) { ReadTag(); } switch (state) { case CborReaderState.UnsignedInteger: ReadUInt64(); break; case CborReaderState.NegativeInteger: ReadCborNegativeIntegerRepresentation(); break; case CborReaderState.ByteString: SkipString(type: CborMajorType.ByteString); break; case CborReaderState.TextString: SkipString(type: CborMajorType.TextString); break; case CborReaderState.StartIndefiniteLengthByteString: ReadStartIndefiniteLengthByteString(); depth++; break; case CborReaderState.EndIndefiniteLengthByteString: ValidatePop(state, depth); ReadEndIndefiniteLengthByteString(); depth--; break; case CborReaderState.StartIndefiniteLengthTextString: ReadStartIndefiniteLengthTextString(); depth++; break; case CborReaderState.EndIndefiniteLengthTextString: ValidatePop(state, depth); ReadEndIndefiniteLengthTextString(); depth--; break; case CborReaderState.StartArray: ReadStartArray(); depth++; break; case CborReaderState.EndArray: ValidatePop(state, depth); ReadEndArray(); depth--; break; case CborReaderState.StartMap: ReadStartMap(); depth++; break; case CborReaderState.EndMap: ValidatePop(state, depth); ReadEndMap(); depth--; break; case CborReaderState.HalfPrecisionFloat: case CborReaderState.SinglePrecisionFloat: case CborReaderState.DoublePrecisionFloat: ReadDouble(); break; case CborReaderState.Null: case CborReaderState.Boolean: case CborReaderState.SimpleValue: ReadSimpleValue(); break; default: throw new InvalidOperationException(SR.Format(SR.Cbor_Reader_Skip_InvalidState, state)); } // guards against cases where the caller attempts to skip when reader is not positioned at the start of a value static void ValidatePop(CborReaderState state, int depth) { if (depth == 0) { throw new InvalidOperationException(SR.Format(SR.Cbor_Reader_Skip_InvalidState, state)); } } } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Reader/CborReader.String.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading; namespace System.Formats.Cbor { public partial class CborReader { // Implements major type 2,3 decoding per https://tools.ietf.org/html/rfc7049#section-2.1 // stores a reusable List allocation for storing indefinite length string chunk offsets private List<(int Offset, int Length)>? _indefiniteLengthStringRangeAllocation; /// <summary>Reads the next data item as a byte string (major type 2).</summary> /// <returns>The decoded byte array.</returns> /// <exception cref="InvalidOperationException">The next date item does not have the correct major type.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> /// <remarks>The method accepts indefinite length strings, which it concatenates to a single string.</remarks> public byte[] ReadByteString() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.ByteString); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } return ReadIndefiniteLengthByteStringConcatenated(); } ReadOnlySpan<byte> buffer = GetRemainingBytes(); int length = DecodeDefiniteLength(header, buffer, out int bytesRead); EnsureReadCapacity(bytesRead + length); byte[] result = new byte[length]; buffer.Slice(bytesRead, length).CopyTo(result); AdvanceBuffer(bytesRead + length); AdvanceDataItemCounters(); return result; } /// <summary>Reads the next data item as a byte string (major type 2).</summary> /// <param name="destination">The buffer in which to write the read bytes.</param> /// <param name="bytesWritten">On success, receives the number of bytes written to <paramref name="destination" />.</param> /// <returns><see langword="true" /> if <paramref name="destination" /> had sufficient length to receive the value and the reader advances; otherwise, <see langword="false" />.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> /// <remarks>The method accepts indefinite length strings, which it will concatenate to a single string.</remarks> public bool TryReadByteString(Span<byte> destination, out int bytesWritten) { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.ByteString); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } return TryReadIndefiniteLengthByteStringConcatenated(destination, out bytesWritten); } ReadOnlySpan<byte> buffer = GetRemainingBytes(); int length = DecodeDefiniteLength(header, buffer, out int bytesRead); EnsureReadCapacity(bytesRead + length); if (length > destination.Length) { bytesWritten = 0; return false; } buffer.Slice(bytesRead, length).CopyTo(destination); AdvanceBuffer(bytesRead + length); AdvanceDataItemCounters(); bytesWritten = length; return true; } /// <summary>Reads the next data item as a definite-length byte string (major type 2).</summary> /// <returns>A <see cref="ReadOnlyMemory{T}" /> view of the byte string payload.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type. /// -or- /// The data item is an indefinite-length byte string.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public ReadOnlyMemory<byte> ReadDefiniteLengthByteString() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.ByteString); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { throw new InvalidOperationException(); } ReadOnlySpan<byte> buffer = GetRemainingBytes(); int length = DecodeDefiniteLength(header, buffer, out int bytesRead); EnsureReadCapacity(bytesRead + length); ReadOnlyMemory<byte> byteSlice = _data.Slice(_offset + bytesRead, length); AdvanceBuffer(bytesRead + length); AdvanceDataItemCounters(); return byteSlice; } /// <summary>Reads the next data item as the start of an indefinite-length byte string (major type 2).</summary> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type. /// -or- /// The next data item is a definite-length encoded string.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public void ReadStartIndefiniteLengthByteString() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.ByteString); if (header.AdditionalInfo != CborAdditionalInfo.IndefiniteLength) { throw new InvalidOperationException(SR.Cbor_Reader_NotIndefiniteLengthString); } if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } AdvanceBuffer(1); PushDataItem(CborMajorType.ByteString, definiteLength: null); } /// <summary>Ends reading an indefinite-length byte string (major type 2).</summary> /// <exception cref="InvalidOperationException">The current context is not an indefinite-length string. /// -or- /// The reader is not at the end of the string.</exception> /// <exception cref="CborContentException">There was an unexpected end of CBOR encoding data.</exception> public void ReadEndIndefiniteLengthByteString() { ValidateNextByteIsBreakByte(); PopDataItem(CborMajorType.ByteString); AdvanceDataItemCounters(); AdvanceBuffer(1); } /// <summary>Reads the next data item as a UTF-8 text string (major type 3).</summary> /// <returns>The decoded string.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> /// <remarks>The method accepts indefinite length strings, which it will concatenate to a single string.</remarks> public string ReadTextString() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.TextString); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } return ReadIndefiniteLengthTextStringConcatenated(); } ReadOnlySpan<byte> buffer = GetRemainingBytes(); int length = DecodeDefiniteLength(header, buffer, out int bytesRead); EnsureReadCapacity(bytesRead + length); ReadOnlySpan<byte> encodedString = buffer.Slice(bytesRead, length); Encoding utf8Encoding = CborConformanceModeHelpers.GetUtf8Encoding(ConformanceMode); string result; try { result = CborHelpers.GetString(utf8Encoding, encodedString); } catch (DecoderFallbackException e) { throw new CborContentException(SR.Cbor_Reader_InvalidCbor_InvalidUtf8StringEncoding, e); } AdvanceBuffer(bytesRead + length); AdvanceDataItemCounters(); return result; } /// <summary>Reads the next data item as a UTF-8 text string (major type 3).</summary> /// <param name="destination">The buffer in which to write.</param> /// <param name="charsWritten">On success, receives the number of chars written to <paramref name="destination" />.</param> /// <returns><see langword="true" /> and advances the reader if <paramref name="destination" /> had sufficient length to receive the value, otherwise <see langword="false" /> and the reader does not advance.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> /// <remarks>The method accepts indefinite length strings, which it will concatenate to a single string.</remarks> public bool TryReadTextString(Span<char> destination, out int charsWritten) { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.TextString); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } return TryReadIndefiniteLengthTextStringConcatenated(destination, out charsWritten); } ReadOnlySpan<byte> buffer = GetRemainingBytes(); int byteLength = DecodeDefiniteLength(header, buffer, out int bytesRead); EnsureReadCapacity(bytesRead + byteLength); Encoding utf8Encoding = CborConformanceModeHelpers.GetUtf8Encoding(ConformanceMode); ReadOnlySpan<byte> encodedSlice = buffer.Slice(bytesRead, byteLength); int charLength = ValidateUtf8AndGetCharCount(encodedSlice, utf8Encoding); if (charLength > destination.Length) { charsWritten = 0; return false; } CborHelpers.GetChars(utf8Encoding, encodedSlice, destination); AdvanceBuffer(bytesRead + byteLength); AdvanceDataItemCounters(); charsWritten = charLength; return true; } /// <summary>Reads the next data item as a definite-length UTF-8 text string (major type 3).</summary> /// <returns>A <see cref="ReadOnlyMemory{T}" /> view of the raw UTF-8 payload.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type. /// -or- /// The data item is an indefinite-length text string.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public ReadOnlyMemory<byte> ReadDefiniteLengthTextStringBytes() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.TextString); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { throw new InvalidOperationException(); } ReadOnlySpan<byte> buffer = GetRemainingBytes(); int byteLength = DecodeDefiniteLength(header, buffer, out int bytesRead); EnsureReadCapacity(bytesRead + byteLength); ReadOnlyMemory<byte> encodedSlice = _data.Slice(_offset + bytesRead, byteLength); if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresUtf8Validation(ConformanceMode)) { Encoding encoding = CborConformanceModeHelpers.GetUtf8Encoding(ConformanceMode); ValidateUtf8AndGetCharCount(encodedSlice.Span, encoding); } AdvanceBuffer(bytesRead + byteLength); AdvanceDataItemCounters(); return encodedSlice; } /// <summary>Reads the next data item as the start of an indefinite-length UTF-8 text string (major type 3).</summary> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type. /// -or- /// The next data item is a definite-length encoded string.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public void ReadStartIndefiniteLengthTextString() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.TextString); if (header.AdditionalInfo != CborAdditionalInfo.IndefiniteLength) { throw new InvalidOperationException(SR.Cbor_Reader_NotIndefiniteLengthString); } if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } AdvanceBuffer(1); PushDataItem(CborMajorType.TextString, definiteLength: null); } /// <summary>Ends reading an indefinite-length UTF-8 text string (major type 3).</summary> /// <exception cref="InvalidOperationException">The current context is not an indefinite-length string. /// -or- /// The reader is not at the end of the string.</exception> /// <exception cref="CborContentException">There was an unexpected end of CBOR encoding data.</exception> public void ReadEndIndefiniteLengthTextString() { ValidateNextByteIsBreakByte(); PopDataItem(CborMajorType.TextString); AdvanceDataItemCounters(); AdvanceBuffer(1); } private byte[] ReadIndefiniteLengthByteStringConcatenated() { List<(int Offset, int Length)> ranges = ReadIndefiniteLengthStringChunkRanges(CborMajorType.ByteString, out int encodingLength, out int concatenatedBufferSize); var output = new byte[concatenatedBufferSize]; ReadOnlySpan<byte> source = GetRemainingBytes(); Span<byte> target = output; foreach ((int o, int l) in ranges) { source.Slice(o, l).CopyTo(target); target = target.Slice(l); } Debug.Assert(target.IsEmpty); AdvanceBuffer(encodingLength); AdvanceDataItemCounters(); ReturnIndefiniteLengthStringRangeList(ranges); return output; } private bool TryReadIndefiniteLengthByteStringConcatenated(Span<byte> destination, out int bytesWritten) { List<(int Offset, int Length)> ranges = ReadIndefiniteLengthStringChunkRanges(CborMajorType.ByteString, out int encodingLength, out int concatenatedBufferSize); if (concatenatedBufferSize > destination.Length) { bytesWritten = 0; return false; } ReadOnlySpan<byte> source = GetRemainingBytes(); foreach ((int o, int l) in ranges) { source.Slice(o, l).CopyTo(destination); destination = destination.Slice(l); } bytesWritten = concatenatedBufferSize; AdvanceBuffer(encodingLength); AdvanceDataItemCounters(); ReturnIndefiniteLengthStringRangeList(ranges); return true; } private string ReadIndefiniteLengthTextStringConcatenated() { List<(int Offset, int Length)> ranges = ReadIndefiniteLengthStringChunkRanges(CborMajorType.TextString, out int encodingLength, out int concatenatedBufferSize); Encoding utf8Encoding = CborConformanceModeHelpers.GetUtf8Encoding(ConformanceMode); ReadOnlySpan<byte> buffer = GetRemainingBytes(); // calculate the string character length int concatenatedStringSize = 0; foreach ((int o, int l) in ranges) { concatenatedStringSize += ValidateUtf8AndGetCharCount(buffer.Slice(o, l), utf8Encoding); } // build the string using range data string output = CborHelpers.BuildStringFromIndefiniteLengthTextString(concatenatedStringSize, (ranges, _data.Slice(_offset), utf8Encoding), BuildString); AdvanceBuffer(encodingLength); AdvanceDataItemCounters(); ReturnIndefiniteLengthStringRangeList(ranges); return output; static void BuildString(Span<char> target, (List<(int Offset, int Length)> ranges, ReadOnlyMemory<byte> source, Encoding utf8Encoding) input) { ReadOnlySpan<byte> source = input.source.Span; foreach ((int o, int l) in input.ranges) { int charsWritten = CborHelpers.GetChars(input.utf8Encoding, source.Slice(o, l), target); target = target.Slice(charsWritten); } Debug.Assert(target.IsEmpty); } } private bool TryReadIndefiniteLengthTextStringConcatenated(Span<char> destination, out int charsWritten) { List<(int Offset, int Length)> ranges = ReadIndefiniteLengthStringChunkRanges(CborMajorType.TextString, out int encodingLength, out int _); ReadOnlySpan<byte> buffer = GetRemainingBytes(); Encoding utf8Encoding = CborConformanceModeHelpers.GetUtf8Encoding(ConformanceMode); // calculate the string character length int concatenatedStringSize = 0; foreach ((int o, int l) in ranges) { concatenatedStringSize += ValidateUtf8AndGetCharCount(buffer.Slice(o, l), utf8Encoding); } if (concatenatedStringSize > destination.Length) { charsWritten = 0; return false; } foreach ((int o, int l) in ranges) { CborHelpers.GetChars(utf8Encoding, buffer.Slice(o, l), destination); destination = destination.Slice(l); } charsWritten = concatenatedStringSize; AdvanceBuffer(encodingLength); AdvanceDataItemCounters(); ReturnIndefiniteLengthStringRangeList(ranges); return true; } // Reads a buffer starting with an indefinite-length string, // performing validation and returning a list of ranges // containing the individual chunk payloads private List<(int Offset, int Length)> ReadIndefiniteLengthStringChunkRanges(CborMajorType type, out int encodingLength, out int concatenatedBufferSize) { List<(int Offset, int Length)> ranges = AcquireIndefiniteLengthStringRangeList(); ReadOnlySpan<byte> data = GetRemainingBytes(); concatenatedBufferSize = 0; int i = 1; // skip the indefinite-length initial byte CborInitialByte nextInitialByte = ReadNextInitialByte(data.Slice(i), type); while (nextInitialByte.InitialByte != CborInitialByte.IndefiniteLengthBreakByte) { int chunkLength = DecodeDefiniteLength(nextInitialByte, data.Slice(i), out int bytesRead); ranges.Add((i + bytesRead, chunkLength)); i += bytesRead + chunkLength; concatenatedBufferSize += chunkLength; nextInitialByte = ReadNextInitialByte(data.Slice(i), type); } encodingLength = i + 1; // include the break byte return ranges; static CborInitialByte ReadNextInitialByte(ReadOnlySpan<byte> buffer, CborMajorType expectedType) { EnsureReadCapacity(buffer, 1); var header = new CborInitialByte(buffer[0]); if (header.InitialByte != CborInitialByte.IndefiniteLengthBreakByte && header.MajorType != expectedType) { throw new CborContentException(SR.Cbor_Reader_InvalidCbor_IndefiniteLengthStringContainsInvalidDataItem); } return header; } } // SkipValue() helper: reads a cbor string without allocating or copying to a buffer private void SkipString(CborMajorType type) { Debug.Assert(type == CborMajorType.ByteString || type == CborMajorType.TextString); CborInitialByte header = PeekInitialByte(expectedType: type); ReadOnlySpan<byte> buffer = GetRemainingBytes(); int byteLength = DecodeDefiniteLength(header, buffer, out int bytesRead); EnsureReadCapacity(bytesRead + byteLength); // if conformance mode requires it, validate the utf-8 encoding that is being skipped if (type == CborMajorType.TextString && _isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresUtf8Validation(ConformanceMode)) { ReadOnlySpan<byte> encodedSlice = buffer.Slice(bytesRead, byteLength); Encoding utf8Encoding = CborConformanceModeHelpers.GetUtf8Encoding(ConformanceMode); ValidateUtf8AndGetCharCount(encodedSlice, utf8Encoding); } AdvanceBuffer(bytesRead + byteLength); AdvanceDataItemCounters(); } private int ValidateUtf8AndGetCharCount(ReadOnlySpan<byte> buffer, Encoding utf8Encoding) { try { return CborHelpers.GetCharCount(utf8Encoding, buffer); } catch (DecoderFallbackException e) { throw new CborContentException(SR.Cbor_Reader_InvalidCbor_InvalidUtf8StringEncoding, e); } } private List<(int Offset, int Length)> AcquireIndefiniteLengthStringRangeList() { List<(int Offset, int Length)>? ranges = Interlocked.Exchange(ref _indefiniteLengthStringRangeAllocation, null); if (ranges != null) { ranges.Clear(); return ranges; } return new List<(int Offset, int Length)>(); } private void ReturnIndefiniteLengthStringRangeList(List<(int Offset, int Length)> ranges) { _indefiniteLengthStringRangeAllocation = ranges; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading; namespace System.Formats.Cbor { public partial class CborReader { // Implements major type 2,3 decoding per https://tools.ietf.org/html/rfc7049#section-2.1 // stores a reusable List allocation for storing indefinite length string chunk offsets private List<(int Offset, int Length)>? _indefiniteLengthStringRangeAllocation; /// <summary>Reads the next data item as a byte string (major type 2).</summary> /// <returns>The decoded byte array.</returns> /// <exception cref="InvalidOperationException">The next date item does not have the correct major type.</exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> /// <remarks>The method accepts indefinite length strings, which it concatenates to a single string.</remarks> public byte[] ReadByteString() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.ByteString); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } return ReadIndefiniteLengthByteStringConcatenated(); } ReadOnlySpan<byte> buffer = GetRemainingBytes(); int length = DecodeDefiniteLength(header, buffer, out int bytesRead); EnsureReadCapacity(bytesRead + length); byte[] result = new byte[length]; buffer.Slice(bytesRead, length).CopyTo(result); AdvanceBuffer(bytesRead + length); AdvanceDataItemCounters(); return result; } /// <summary>Reads the next data item as a byte string (major type 2).</summary> /// <param name="destination">The buffer in which to write the read bytes.</param> /// <param name="bytesWritten">On success, receives the number of bytes written to <paramref name="destination" />.</param> /// <returns><see langword="true" /> if <paramref name="destination" /> had sufficient length to receive the value and the reader advances; otherwise, <see langword="false" />.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> /// <remarks>The method accepts indefinite length strings, which it will concatenate to a single string.</remarks> public bool TryReadByteString(Span<byte> destination, out int bytesWritten) { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.ByteString); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } return TryReadIndefiniteLengthByteStringConcatenated(destination, out bytesWritten); } ReadOnlySpan<byte> buffer = GetRemainingBytes(); int length = DecodeDefiniteLength(header, buffer, out int bytesRead); EnsureReadCapacity(bytesRead + length); if (length > destination.Length) { bytesWritten = 0; return false; } buffer.Slice(bytesRead, length).CopyTo(destination); AdvanceBuffer(bytesRead + length); AdvanceDataItemCounters(); bytesWritten = length; return true; } /// <summary>Reads the next data item as a definite-length byte string (major type 2).</summary> /// <returns>A <see cref="ReadOnlyMemory{T}" /> view of the byte string payload.</returns> /// <exception cref="InvalidOperationException"><para>The next data item does not have the correct major type.</para> /// <para>-or-</para> /// <para>The data item is an indefinite-length byte string.</para></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public ReadOnlyMemory<byte> ReadDefiniteLengthByteString() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.ByteString); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { throw new InvalidOperationException(); } ReadOnlySpan<byte> buffer = GetRemainingBytes(); int length = DecodeDefiniteLength(header, buffer, out int bytesRead); EnsureReadCapacity(bytesRead + length); ReadOnlyMemory<byte> byteSlice = _data.Slice(_offset + bytesRead, length); AdvanceBuffer(bytesRead + length); AdvanceDataItemCounters(); return byteSlice; } /// <summary>Reads the next data item as the start of an indefinite-length byte string (major type 2).</summary> /// <exception cref="InvalidOperationException"><para>The next data item does not have the correct major type.</para> /// <para>-or-</para> /// <para>The next data item is a definite-length encoded string.</para></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public void ReadStartIndefiniteLengthByteString() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.ByteString); if (header.AdditionalInfo != CborAdditionalInfo.IndefiniteLength) { throw new InvalidOperationException(SR.Cbor_Reader_NotIndefiniteLengthString); } if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } AdvanceBuffer(1); PushDataItem(CborMajorType.ByteString, definiteLength: null); } /// <summary>Ends reading an indefinite-length byte string (major type 2).</summary> /// <exception cref="InvalidOperationException"><para>The current context is not an indefinite-length string.</para> /// <para>-or-</para> /// <para>The reader is not at the end of the string.</para></exception> /// <exception cref="CborContentException">There was an unexpected end of CBOR encoding data.</exception> public void ReadEndIndefiniteLengthByteString() { ValidateNextByteIsBreakByte(); PopDataItem(CborMajorType.ByteString); AdvanceDataItemCounters(); AdvanceBuffer(1); } /// <summary>Reads the next data item as a UTF-8 text string (major type 3).</summary> /// <returns>The decoded string.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> /// <remarks>The method accepts indefinite length strings, which it will concatenate to a single string.</remarks> public string ReadTextString() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.TextString); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } return ReadIndefiniteLengthTextStringConcatenated(); } ReadOnlySpan<byte> buffer = GetRemainingBytes(); int length = DecodeDefiniteLength(header, buffer, out int bytesRead); EnsureReadCapacity(bytesRead + length); ReadOnlySpan<byte> encodedString = buffer.Slice(bytesRead, length); Encoding utf8Encoding = CborConformanceModeHelpers.GetUtf8Encoding(ConformanceMode); string result; try { result = CborHelpers.GetString(utf8Encoding, encodedString); } catch (DecoderFallbackException e) { throw new CborContentException(SR.Cbor_Reader_InvalidCbor_InvalidUtf8StringEncoding, e); } AdvanceBuffer(bytesRead + length); AdvanceDataItemCounters(); return result; } /// <summary>Reads the next data item as a UTF-8 text string (major type 3).</summary> /// <param name="destination">The buffer in which to write.</param> /// <param name="charsWritten">On success, receives the number of chars written to <paramref name="destination" />.</param> /// <returns><see langword="true" /> and advances the reader if <paramref name="destination" /> had sufficient length to receive the value, otherwise <see langword="false" /> and the reader does not advance.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> /// <remarks>The method accepts indefinite length strings, which it will concatenate to a single string.</remarks> public bool TryReadTextString(Span<char> destination, out int charsWritten) { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.TextString); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } return TryReadIndefiniteLengthTextStringConcatenated(destination, out charsWritten); } ReadOnlySpan<byte> buffer = GetRemainingBytes(); int byteLength = DecodeDefiniteLength(header, buffer, out int bytesRead); EnsureReadCapacity(bytesRead + byteLength); Encoding utf8Encoding = CborConformanceModeHelpers.GetUtf8Encoding(ConformanceMode); ReadOnlySpan<byte> encodedSlice = buffer.Slice(bytesRead, byteLength); int charLength = ValidateUtf8AndGetCharCount(encodedSlice, utf8Encoding); if (charLength > destination.Length) { charsWritten = 0; return false; } CborHelpers.GetChars(utf8Encoding, encodedSlice, destination); AdvanceBuffer(bytesRead + byteLength); AdvanceDataItemCounters(); charsWritten = charLength; return true; } /// <summary>Reads the next data item as a definite-length UTF-8 text string (major type 3).</summary> /// <returns>A <see cref="ReadOnlyMemory{T}" /> view of the raw UTF-8 payload.</returns> /// <exception cref="InvalidOperationException"><para>The next data item does not have the correct major type.</para> /// <para>-or-</para> /// <para>The data item is an indefinite-length text string.</para></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public ReadOnlyMemory<byte> ReadDefiniteLengthTextStringBytes() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.TextString); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { throw new InvalidOperationException(); } ReadOnlySpan<byte> buffer = GetRemainingBytes(); int byteLength = DecodeDefiniteLength(header, buffer, out int bytesRead); EnsureReadCapacity(bytesRead + byteLength); ReadOnlyMemory<byte> encodedSlice = _data.Slice(_offset + bytesRead, byteLength); if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresUtf8Validation(ConformanceMode)) { Encoding encoding = CborConformanceModeHelpers.GetUtf8Encoding(ConformanceMode); ValidateUtf8AndGetCharCount(encodedSlice.Span, encoding); } AdvanceBuffer(bytesRead + byteLength); AdvanceDataItemCounters(); return encodedSlice; } /// <summary>Reads the next data item as the start of an indefinite-length UTF-8 text string (major type 3).</summary> /// <exception cref="InvalidOperationException"><para>The next data item does not have the correct major type.</para> /// <para>-or-</para> /// <para>The next data item is a definite-length encoded string.</para></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public void ReadStartIndefiniteLengthTextString() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.TextString); if (header.AdditionalInfo != CborAdditionalInfo.IndefiniteLength) { throw new InvalidOperationException(SR.Cbor_Reader_NotIndefiniteLengthString); } if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } AdvanceBuffer(1); PushDataItem(CborMajorType.TextString, definiteLength: null); } /// <summary>Ends reading an indefinite-length UTF-8 text string (major type 3).</summary> /// <exception cref="InvalidOperationException"><para>The current context is not an indefinite-length string.</para> /// <para>-or-</para> /// <para>The reader is not at the end of the string.</para></exception> /// <exception cref="CborContentException">There was an unexpected end of CBOR encoding data.</exception> public void ReadEndIndefiniteLengthTextString() { ValidateNextByteIsBreakByte(); PopDataItem(CborMajorType.TextString); AdvanceDataItemCounters(); AdvanceBuffer(1); } private byte[] ReadIndefiniteLengthByteStringConcatenated() { List<(int Offset, int Length)> ranges = ReadIndefiniteLengthStringChunkRanges(CborMajorType.ByteString, out int encodingLength, out int concatenatedBufferSize); var output = new byte[concatenatedBufferSize]; ReadOnlySpan<byte> source = GetRemainingBytes(); Span<byte> target = output; foreach ((int o, int l) in ranges) { source.Slice(o, l).CopyTo(target); target = target.Slice(l); } Debug.Assert(target.IsEmpty); AdvanceBuffer(encodingLength); AdvanceDataItemCounters(); ReturnIndefiniteLengthStringRangeList(ranges); return output; } private bool TryReadIndefiniteLengthByteStringConcatenated(Span<byte> destination, out int bytesWritten) { List<(int Offset, int Length)> ranges = ReadIndefiniteLengthStringChunkRanges(CborMajorType.ByteString, out int encodingLength, out int concatenatedBufferSize); if (concatenatedBufferSize > destination.Length) { bytesWritten = 0; return false; } ReadOnlySpan<byte> source = GetRemainingBytes(); foreach ((int o, int l) in ranges) { source.Slice(o, l).CopyTo(destination); destination = destination.Slice(l); } bytesWritten = concatenatedBufferSize; AdvanceBuffer(encodingLength); AdvanceDataItemCounters(); ReturnIndefiniteLengthStringRangeList(ranges); return true; } private string ReadIndefiniteLengthTextStringConcatenated() { List<(int Offset, int Length)> ranges = ReadIndefiniteLengthStringChunkRanges(CborMajorType.TextString, out int encodingLength, out int concatenatedBufferSize); Encoding utf8Encoding = CborConformanceModeHelpers.GetUtf8Encoding(ConformanceMode); ReadOnlySpan<byte> buffer = GetRemainingBytes(); // calculate the string character length int concatenatedStringSize = 0; foreach ((int o, int l) in ranges) { concatenatedStringSize += ValidateUtf8AndGetCharCount(buffer.Slice(o, l), utf8Encoding); } // build the string using range data string output = CborHelpers.BuildStringFromIndefiniteLengthTextString(concatenatedStringSize, (ranges, _data.Slice(_offset), utf8Encoding), BuildString); AdvanceBuffer(encodingLength); AdvanceDataItemCounters(); ReturnIndefiniteLengthStringRangeList(ranges); return output; static void BuildString(Span<char> target, (List<(int Offset, int Length)> ranges, ReadOnlyMemory<byte> source, Encoding utf8Encoding) input) { ReadOnlySpan<byte> source = input.source.Span; foreach ((int o, int l) in input.ranges) { int charsWritten = CborHelpers.GetChars(input.utf8Encoding, source.Slice(o, l), target); target = target.Slice(charsWritten); } Debug.Assert(target.IsEmpty); } } private bool TryReadIndefiniteLengthTextStringConcatenated(Span<char> destination, out int charsWritten) { List<(int Offset, int Length)> ranges = ReadIndefiniteLengthStringChunkRanges(CborMajorType.TextString, out int encodingLength, out int _); ReadOnlySpan<byte> buffer = GetRemainingBytes(); Encoding utf8Encoding = CborConformanceModeHelpers.GetUtf8Encoding(ConformanceMode); // calculate the string character length int concatenatedStringSize = 0; foreach ((int o, int l) in ranges) { concatenatedStringSize += ValidateUtf8AndGetCharCount(buffer.Slice(o, l), utf8Encoding); } if (concatenatedStringSize > destination.Length) { charsWritten = 0; return false; } foreach ((int o, int l) in ranges) { CborHelpers.GetChars(utf8Encoding, buffer.Slice(o, l), destination); destination = destination.Slice(l); } charsWritten = concatenatedStringSize; AdvanceBuffer(encodingLength); AdvanceDataItemCounters(); ReturnIndefiniteLengthStringRangeList(ranges); return true; } // Reads a buffer starting with an indefinite-length string, // performing validation and returning a list of ranges // containing the individual chunk payloads private List<(int Offset, int Length)> ReadIndefiniteLengthStringChunkRanges(CborMajorType type, out int encodingLength, out int concatenatedBufferSize) { List<(int Offset, int Length)> ranges = AcquireIndefiniteLengthStringRangeList(); ReadOnlySpan<byte> data = GetRemainingBytes(); concatenatedBufferSize = 0; int i = 1; // skip the indefinite-length initial byte CborInitialByte nextInitialByte = ReadNextInitialByte(data.Slice(i), type); while (nextInitialByte.InitialByte != CborInitialByte.IndefiniteLengthBreakByte) { int chunkLength = DecodeDefiniteLength(nextInitialByte, data.Slice(i), out int bytesRead); ranges.Add((i + bytesRead, chunkLength)); i += bytesRead + chunkLength; concatenatedBufferSize += chunkLength; nextInitialByte = ReadNextInitialByte(data.Slice(i), type); } encodingLength = i + 1; // include the break byte return ranges; static CborInitialByte ReadNextInitialByte(ReadOnlySpan<byte> buffer, CborMajorType expectedType) { EnsureReadCapacity(buffer, 1); var header = new CborInitialByte(buffer[0]); if (header.InitialByte != CborInitialByte.IndefiniteLengthBreakByte && header.MajorType != expectedType) { throw new CborContentException(SR.Cbor_Reader_InvalidCbor_IndefiniteLengthStringContainsInvalidDataItem); } return header; } } // SkipValue() helper: reads a cbor string without allocating or copying to a buffer private void SkipString(CborMajorType type) { Debug.Assert(type == CborMajorType.ByteString || type == CborMajorType.TextString); CborInitialByte header = PeekInitialByte(expectedType: type); ReadOnlySpan<byte> buffer = GetRemainingBytes(); int byteLength = DecodeDefiniteLength(header, buffer, out int bytesRead); EnsureReadCapacity(bytesRead + byteLength); // if conformance mode requires it, validate the utf-8 encoding that is being skipped if (type == CborMajorType.TextString && _isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresUtf8Validation(ConformanceMode)) { ReadOnlySpan<byte> encodedSlice = buffer.Slice(bytesRead, byteLength); Encoding utf8Encoding = CborConformanceModeHelpers.GetUtf8Encoding(ConformanceMode); ValidateUtf8AndGetCharCount(encodedSlice, utf8Encoding); } AdvanceBuffer(bytesRead + byteLength); AdvanceDataItemCounters(); } private int ValidateUtf8AndGetCharCount(ReadOnlySpan<byte> buffer, Encoding utf8Encoding) { try { return CborHelpers.GetCharCount(utf8Encoding, buffer); } catch (DecoderFallbackException e) { throw new CborContentException(SR.Cbor_Reader_InvalidCbor_InvalidUtf8StringEncoding, e); } } private List<(int Offset, int Length)> AcquireIndefiniteLengthStringRangeList() { List<(int Offset, int Length)>? ranges = Interlocked.Exchange(ref _indefiniteLengthStringRangeAllocation, null); if (ranges != null) { ranges.Clear(); return ranges; } return new List<(int Offset, int Length)>(); } private void ReturnIndefiniteLengthStringRangeList(List<(int Offset, int Length)> ranges) { _indefiniteLengthStringRangeAllocation = ranges; } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Reader/CborReader.Tag.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.Numerics; namespace System.Formats.Cbor { public partial class CborReader { /// <summary>Reads the next data item as a semantic tag (major type 6).</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> [CLSCompliant(false)] public CborTag ReadTag() { CborTag tag = PeekTagCore(out int bytesRead); AdvanceBuffer(bytesRead); _isTagContext = true; return tag; } /// <summary>Reads the next data item as a semantic tag (major type 6), without advancing the reader.</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> /// <remarks>Useful in scenarios where the semantic value decoder needs to be determined at run time.</remarks> [CLSCompliant(false)] public CborTag PeekTag() => PeekTagCore(out int _); /// <summary>Reads the next data item as a tagged date/time string, as described in RFC7049 section 2.4.1.</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type. /// -or- /// The next date item does not have the correct semantic tag.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// Invalid semantic date/time encoding. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public DateTimeOffset ReadDateTimeOffset() { // implements https://tools.ietf.org/html/rfc7049#section-2.4.1 Checkpoint checkpoint = CreateCheckpoint(); try { ReadExpectedTag(expectedTag: CborTag.DateTimeString); switch (PeekState()) { case CborReaderState.TextString: case CborReaderState.StartIndefiniteLengthTextString: break; default: throw new CborContentException(SR.Cbor_Reader_InvalidDateTimeEncoding); } string dateString = ReadTextString(); // TODO determine if conformance modes should allow inexact date sting parsing if (!DateTimeOffset.TryParseExact(dateString, CborWriter.Rfc3339FormatString, null, DateTimeStyles.RoundtripKind, out DateTimeOffset result)) { throw new CborContentException(SR.Cbor_Reader_InvalidDateTimeEncoding); } return result; } catch { RestoreCheckpoint(in checkpoint); throw; } } /// <summary>Reads the next data item as a tagged unix time in seconds, as described in RFC7049 section 2.4.1.</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type. /// -or- /// The next date item does not have the correct semantic tag.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// invalid semantic date/time encoding. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public DateTimeOffset ReadUnixTimeSeconds() { // implements https://tools.ietf.org/html/rfc7049#section-2.4.1 Checkpoint checkpoint = CreateCheckpoint(); try { ReadExpectedTag(expectedTag: CborTag.UnixTimeSeconds); switch (PeekState()) { case CborReaderState.UnsignedInteger: case CborReaderState.NegativeInteger: return DateTimeOffset.FromUnixTimeSeconds(ReadInt64()); case CborReaderState.HalfPrecisionFloat: case CborReaderState.SinglePrecisionFloat: case CborReaderState.DoublePrecisionFloat: double seconds = ReadDouble(); if (double.IsNaN(seconds) || double.IsInfinity(seconds)) { throw new CborContentException(SR.Cbor_Reader_InvalidUnixTimeEncoding); } TimeSpan timespan = TimeSpan.FromSeconds(seconds); return CborHelpers.UnixEpoch + timespan; default: throw new CborContentException(SR.Cbor_Reader_InvalidUnixTimeEncoding); } } catch { RestoreCheckpoint(in checkpoint); throw; } } /// <summary>Reads the next data item as a tagged bignum encoding, as described in RFC7049 section 2.4.2.</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type. /// -or- /// The next date item does not have the correct semantic tag.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// Invalid semantic bignum encoding. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public BigInteger ReadBigInteger() { // implements https://tools.ietf.org/html/rfc7049#section-2.4.2 Checkpoint checkpoint = CreateCheckpoint(); try { bool isNegative = ReadTag() switch { CborTag.UnsignedBigNum => false, CborTag.NegativeBigNum => true, _ => throw new InvalidOperationException(SR.Cbor_Reader_InvalidBigNumEncoding), }; switch (PeekState()) { case CborReaderState.ByteString: case CborReaderState.StartIndefiniteLengthByteString: break; default: throw new CborContentException(SR.Cbor_Reader_InvalidBigNumEncoding); } byte[] unsignedBigEndianEncoding = ReadByteString(); BigInteger unsignedValue = CborHelpers.CreateBigIntegerFromUnsignedBigEndianBytes(unsignedBigEndianEncoding); return isNegative ? -1 - unsignedValue : unsignedValue; } catch { RestoreCheckpoint(in checkpoint); throw; } } /// <summary>Reads the next data item as a tagged decimal fraction encoding, as described in RFC7049 section 2.4.3.</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type. /// -or- /// The next date item does not have the correct semantic tag.</exception> /// <exception cref="OverflowException">Decoded decimal fraction is either too large or too small for a <see cref="decimal" /> value.</exception> /// <exception cref="CborContentException">The next value has an invalid CBOR encoding. /// -or- /// There was an unexpected end of CBOR encoding data. /// -or- /// Invalid semantic decimal fraction encoding. /// -or- /// The next value uses a CBOR encoding that is not valid under the current conformance mode.</exception> public decimal ReadDecimal() { // implements https://tools.ietf.org/html/rfc7049#section-2.4.3 Checkpoint checkpoint = CreateCheckpoint(); try { ReadExpectedTag(expectedTag: CborTag.DecimalFraction); if (PeekState() != CborReaderState.StartArray || ReadStartArray() != 2) { throw new CborContentException(SR.Cbor_Reader_InvalidDecimalEncoding); } decimal mantissa; // signed integral component of the decimal value long exponent; // base-10 exponent switch (PeekState()) { case CborReaderState.UnsignedInteger: case CborReaderState.NegativeInteger: exponent = ReadInt64(); break; default: throw new CborContentException(SR.Cbor_Reader_InvalidDecimalEncoding); } switch (PeekState()) { case CborReaderState.UnsignedInteger: mantissa = ReadUInt64(); break; case CborReaderState.NegativeInteger: mantissa = -1m - ReadCborNegativeIntegerRepresentation(); break; case CborReaderState.Tag: switch (PeekTag()) { case CborTag.UnsignedBigNum: case CborTag.NegativeBigNum: mantissa = (decimal)ReadBigInteger(); break; default: throw new CborContentException(SR.Cbor_Reader_InvalidDecimalEncoding); } break; default: throw new CborContentException(SR.Cbor_Reader_InvalidDecimalEncoding); } ReadEndArray(); return CborWriter.DecimalHelpers.Reconstruct(mantissa, exponent); } catch { RestoreCheckpoint(in checkpoint); throw; } } private void ReadExpectedTag(CborTag expectedTag) { CborTag tag = PeekTagCore(out int bytesRead); if (expectedTag != tag) { throw new InvalidOperationException(SR.Cbor_Reader_TagMismatch); } AdvanceBuffer(bytesRead); _isTagContext = true; } private CborTag PeekTagCore(out int bytesRead) { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Tag); CborTag result = (CborTag)DecodeUnsignedInteger(header, GetRemainingBytes(), out bytesRead); if (_isConformanceModeCheckEnabled && !CborConformanceModeHelpers.AllowsTags(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_TagsNotSupported, ConformanceMode)); } return 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.Numerics; namespace System.Formats.Cbor { public partial class CborReader { /// <summary>Reads the next data item as a semantic tag (major type 6).</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> [CLSCompliant(false)] public CborTag ReadTag() { CborTag tag = PeekTagCore(out int bytesRead); AdvanceBuffer(bytesRead); _isTagContext = true; return tag; } /// <summary>Reads the next data item as a semantic tag (major type 6), without advancing the reader.</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> /// <remarks>Useful in scenarios where the semantic value decoder needs to be determined at run time.</remarks> [CLSCompliant(false)] public CborTag PeekTag() => PeekTagCore(out int _); /// <summary>Reads the next data item as a tagged date/time string, as described in RFC7049 section 2.4.1.</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException"><para>The next data item does not have the correct major type.</para> /// <para>-or-</para> /// <para>The next date item does not have the correct semantic tag.</para></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The semantic date/time encoding is invalid.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public DateTimeOffset ReadDateTimeOffset() { // implements https://tools.ietf.org/html/rfc7049#section-2.4.1 Checkpoint checkpoint = CreateCheckpoint(); try { ReadExpectedTag(expectedTag: CborTag.DateTimeString); switch (PeekState()) { case CborReaderState.TextString: case CborReaderState.StartIndefiniteLengthTextString: break; default: throw new CborContentException(SR.Cbor_Reader_InvalidDateTimeEncoding); } string dateString = ReadTextString(); // TODO determine if conformance modes should allow inexact date sting parsing if (!DateTimeOffset.TryParseExact(dateString, CborWriter.Rfc3339FormatString, null, DateTimeStyles.RoundtripKind, out DateTimeOffset result)) { throw new CborContentException(SR.Cbor_Reader_InvalidDateTimeEncoding); } return result; } catch { RestoreCheckpoint(in checkpoint); throw; } } /// <summary>Reads the next data item as a tagged unix time in seconds, as described in RFC7049 section 2.4.1.</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException"><para>The next data item does not have the correct major type.</para> /// <para>-or-</para> /// <para>The next date item does not have the correct semantic tag.</para></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The semantic date/time encoding is invalid.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public DateTimeOffset ReadUnixTimeSeconds() { // implements https://tools.ietf.org/html/rfc7049#section-2.4.1 Checkpoint checkpoint = CreateCheckpoint(); try { ReadExpectedTag(expectedTag: CborTag.UnixTimeSeconds); switch (PeekState()) { case CborReaderState.UnsignedInteger: case CborReaderState.NegativeInteger: return DateTimeOffset.FromUnixTimeSeconds(ReadInt64()); case CborReaderState.HalfPrecisionFloat: case CborReaderState.SinglePrecisionFloat: case CborReaderState.DoublePrecisionFloat: double seconds = ReadDouble(); if (double.IsNaN(seconds) || double.IsInfinity(seconds)) { throw new CborContentException(SR.Cbor_Reader_InvalidUnixTimeEncoding); } TimeSpan timespan = TimeSpan.FromSeconds(seconds); return CborHelpers.UnixEpoch + timespan; default: throw new CborContentException(SR.Cbor_Reader_InvalidUnixTimeEncoding); } } catch { RestoreCheckpoint(in checkpoint); throw; } } /// <summary>Reads the next data item as a tagged bignum encoding, as described in RFC7049 section 2.4.2.</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException"><para>The next data item does not have the correct major type.</para> /// <para>-or-</para> /// <para>The next date item does not have the correct semantic tag.</para></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The semantic bignum encoding is invalid.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public BigInteger ReadBigInteger() { // implements https://tools.ietf.org/html/rfc7049#section-2.4.2 Checkpoint checkpoint = CreateCheckpoint(); try { bool isNegative = ReadTag() switch { CborTag.UnsignedBigNum => false, CborTag.NegativeBigNum => true, _ => throw new InvalidOperationException(SR.Cbor_Reader_InvalidBigNumEncoding), }; switch (PeekState()) { case CborReaderState.ByteString: case CborReaderState.StartIndefiniteLengthByteString: break; default: throw new CborContentException(SR.Cbor_Reader_InvalidBigNumEncoding); } byte[] unsignedBigEndianEncoding = ReadByteString(); BigInteger unsignedValue = CborHelpers.CreateBigIntegerFromUnsignedBigEndianBytes(unsignedBigEndianEncoding); return isNegative ? -1 - unsignedValue : unsignedValue; } catch { RestoreCheckpoint(in checkpoint); throw; } } /// <summary>Reads the next data item as a tagged decimal fraction encoding, as described in RFC7049 section 2.4.3.</summary> /// <returns>The decoded value.</returns> /// <exception cref="InvalidOperationException"><para>The next data item does not have the correct major type.</para> /// <para>-or-</para> /// <para>The next date item does not have the correct semantic tag.</para></exception> /// <exception cref="OverflowException">The decoded decimal fraction is either too large or too small for a <see cref="decimal" /> value.</exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The semantic decimal fraction encoding is invalid.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public decimal ReadDecimal() { // implements https://tools.ietf.org/html/rfc7049#section-2.4.3 Checkpoint checkpoint = CreateCheckpoint(); try { ReadExpectedTag(expectedTag: CborTag.DecimalFraction); if (PeekState() != CborReaderState.StartArray || ReadStartArray() != 2) { throw new CborContentException(SR.Cbor_Reader_InvalidDecimalEncoding); } decimal mantissa; // signed integral component of the decimal value long exponent; // base-10 exponent switch (PeekState()) { case CborReaderState.UnsignedInteger: case CborReaderState.NegativeInteger: exponent = ReadInt64(); break; default: throw new CborContentException(SR.Cbor_Reader_InvalidDecimalEncoding); } switch (PeekState()) { case CborReaderState.UnsignedInteger: mantissa = ReadUInt64(); break; case CborReaderState.NegativeInteger: mantissa = -1m - ReadCborNegativeIntegerRepresentation(); break; case CborReaderState.Tag: switch (PeekTag()) { case CborTag.UnsignedBigNum: case CborTag.NegativeBigNum: mantissa = (decimal)ReadBigInteger(); break; default: throw new CborContentException(SR.Cbor_Reader_InvalidDecimalEncoding); } break; default: throw new CborContentException(SR.Cbor_Reader_InvalidDecimalEncoding); } ReadEndArray(); return CborWriter.DecimalHelpers.Reconstruct(mantissa, exponent); } catch { RestoreCheckpoint(in checkpoint); throw; } } private void ReadExpectedTag(CborTag expectedTag) { CborTag tag = PeekTagCore(out int bytesRead); if (expectedTag != tag) { throw new InvalidOperationException(SR.Cbor_Reader_TagMismatch); } AdvanceBuffer(bytesRead); _isTagContext = true; } private CborTag PeekTagCore(out int bytesRead) { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Tag); CborTag result = (CborTag)DecodeUnsignedInteger(header, GetRemainingBytes(), out bytesRead); if (_isConformanceModeCheckEnabled && !CborConformanceModeHelpers.AllowsTags(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_TagsNotSupported, ConformanceMode)); } return result; } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Reader/CborReader.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; namespace System.Formats.Cbor { /// <summary>A stateful, forward-only reader for Concise Binary Object Representation (CBOR) encoded data.</summary> public partial class CborReader { private readonly ReadOnlyMemory<byte> _data; private int _offset; private Stack<StackFrame>? _nestedDataItems; private CborMajorType? _currentMajorType; // major type of the currently written data item. Null iff at the root context private int? _definiteLength; // predetermined definite-length of current data item context private int _itemsRead; // number of items read in the current context private int _frameOffset; // buffer offset particular to the current data item context private bool _isTagContext; // true if reader is expecting a tagged value // Map-specific book-keeping private int? _currentKeyOffset; // offset for the current key encoding private (int Offset, int Length)? _previousKeyEncodingRange; // previous key encoding range private HashSet<(int Offset, int Length)>? _keyEncodingRanges; // all key encoding ranges up to encoding equality // flag used to temporarily disable conformance mode checks, // e.g. during a skip operation over nonconforming encodings. private bool _isConformanceModeCheckEnabled = true; // keeps a cached copy of the reader state; 'None' denotes uncomputed state private CborReaderState _cachedState = CborReaderState.Undefined; /// <summary>Gets the conformance mode used by this reader.</summary> /// <value>One of the enumeration values that represents the conformance mode used by this reader.</value> public CborConformanceMode ConformanceMode { get; } /// <summary>Gets a value that indicates whether this reader allows multiple root-level CBOR data items.</summary> /// <value><see langword="true" /> if this reader allows multiple root-level CBOR data items; <see langword="false" /> otherwise.</value> public bool AllowMultipleRootLevelValues { get; } /// <summary>Gets the reader's current level of nestedness in the CBOR document.</summary> /// <value>A number that represents the current level of nestedness in the CBOR document.</value> public int CurrentDepth => _nestedDataItems is null ? 0 : _nestedDataItems.Count; /// <summary>Gets the total number of unread bytes in the buffer.</summary> /// <value>The total number of unread bytes in the buffer.</value> public int BytesRemaining => _data.Length - _offset; /// <summary>Initializes a <see cref="CborReader" /> instance over the specified <paramref name="data" /> with the given configuration.</summary> /// <param name="data">The CBOR encoded data to read.</param> /// <param name="conformanceMode">One of the enumeration values to specify a conformance mode guiding the checks performed on the encoded data. /// Defaults to <see cref="CborConformanceMode.Strict" /> conformance mode.</param> /// <param name="allowMultipleRootLevelValues"><see langword="true" /> to indicate that multiple root-level values are supported by the reader; otherwise, <see langword="false" />.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="conformanceMode" /> is not defined.</exception> public CborReader(ReadOnlyMemory<byte> data, CborConformanceMode conformanceMode = CborConformanceMode.Strict, bool allowMultipleRootLevelValues = false) { CborConformanceModeHelpers.Validate(conformanceMode); _data = data; ConformanceMode = conformanceMode; AllowMultipleRootLevelValues = allowMultipleRootLevelValues; _definiteLength = allowMultipleRootLevelValues ? null : (int?)1; } /// <summary>Reads the next CBOR data item, returning a <see cref="ReadOnlyMemory{T}" /> view of the encoded value. For indefinite length encodings this includes the break byte.</summary> /// <param name="disableConformanceModeChecks"><see langword="true" /> to disable conformance mode validation for the read value, equivalent to using <see cref="CborConformanceMode.Lax" />; otherwise, <see langword="false" />.</param> /// <returns>A view of the encoded value as a contiguous region of memory.</returns> /// <exception cref="CborContentException">The data item is not a valid CBOR data item encoding. /// -or- /// The CBOR encoding is not valid under the current conformance mode.</exception> public ReadOnlyMemory<byte> ReadEncodedValue(bool disableConformanceModeChecks = false) { // keep a snapshot of the current offset int initialOffset = _offset; // call skip to read and validate the next value SkipValue(disableConformanceModeChecks); // return the slice corresponding to the consumed value return _data.Slice(initialOffset, _offset - initialOffset); } private CborInitialByte PeekInitialByte() { if (_definiteLength - _itemsRead == 0) { throw new InvalidOperationException(SR.Cbor_Reader_NoMoreDataItemsToRead); } if (_offset == _data.Length) { if (_currentMajorType is null && _definiteLength is null && _offset > 0) { // we are at the end of a well-formed sequence of root-level CBOR values throw new InvalidOperationException(SR.Cbor_Reader_NoMoreDataItemsToRead); } throw new CborContentException(SR.Cbor_Reader_InvalidCbor_UnexpectedEndOfBuffer); } var nextByte = new CborInitialByte(_data.Span[_offset]); switch (_currentMajorType) { case CborMajorType.ByteString: case CborMajorType.TextString: // Indefinite-length string contexts allow two possible data items: // 1) Definite-length string chunks of the same major type OR // 2) a break byte denoting the end of the indefinite-length string context. if (nextByte.InitialByte == CborInitialByte.IndefiniteLengthBreakByte || nextByte.MajorType == _currentMajorType.Value && nextByte.AdditionalInfo != CborAdditionalInfo.IndefiniteLength) { break; } throw new CborContentException(SR.Format(SR.Cbor_Reader_InvalidCbor_IndefiniteLengthStringContainsInvalidDataItem, (int)nextByte.MajorType)); } return nextByte; } private CborInitialByte PeekInitialByte(CborMajorType expectedType) { CborInitialByte result = PeekInitialByte(); if (expectedType != result.MajorType) { throw new InvalidOperationException(SR.Format(SR.Cbor_Reader_MajorTypeMismatch, (int)result.MajorType)); } return result; } private void ValidateNextByteIsBreakByte() { CborInitialByte result = PeekInitialByte(); if (result.InitialByte != CborInitialByte.IndefiniteLengthBreakByte) { throw new InvalidOperationException(SR.Cbor_NotAtEndOfIndefiniteLengthDataItem); } } private void PushDataItem(CborMajorType majorType, int? definiteLength) { _nestedDataItems ??= new Stack<StackFrame>(); var frame = new StackFrame( type: _currentMajorType, frameOffset: _frameOffset, definiteLength: _definiteLength, itemsRead: _itemsRead, currentKeyOffset: _currentKeyOffset, previousKeyEncodingRange: _previousKeyEncodingRange, keyEncodingRanges: _keyEncodingRanges ); _nestedDataItems.Push(frame); _currentMajorType = majorType; _definiteLength = definiteLength; _itemsRead = 0; _frameOffset = _offset; _isTagContext = false; _currentKeyOffset = null; _previousKeyEncodingRange = null; _keyEncodingRanges = null; } private void PopDataItem(CborMajorType expectedType) { if (_currentMajorType is null) { throw new InvalidOperationException(SR.Cbor_Reader_IsAtRootContext); } Debug.Assert(_nestedDataItems?.Count > 0); if (expectedType != _currentMajorType) { throw new InvalidOperationException(SR.Format(SR.Cbor_PopMajorTypeMismatch, (int)_currentMajorType.Value)); } if (_definiteLength - _itemsRead > 0) { throw new InvalidOperationException(SR.Cbor_NotAtEndOfDefiniteLengthDataItem); } if (_isTagContext) { throw new CborContentException(SR.Cbor_Reader_InvalidCbor_TagNotFollowedByValue); } if (_currentMajorType == CborMajorType.Map) { ReturnKeyEncodingRangeAllocation(_keyEncodingRanges); } StackFrame frame = _nestedDataItems.Pop(); RestoreStackFrame(in frame); } private void AdvanceDataItemCounters() { Debug.Assert(_definiteLength is null || _definiteLength - _itemsRead > 0); if (_currentMajorType == CborMajorType.Map) { if (_itemsRead % 2 == 0) { HandleMapKeyRead(); } else { HandleMapValueRead(); } } _itemsRead++; _isTagContext = false; } private ReadOnlySpan<byte> GetRemainingBytes() => _data.Span.Slice(_offset); private void AdvanceBuffer(int length) { Debug.Assert(_offset + length <= _data.Length); _offset += length; // invalidate the state cache _cachedState = CborReaderState.Undefined; } private void ResetBuffer(int position) { Debug.Assert(position <= _data.Length); _offset = position; // invalidate the state cache _cachedState = CborReaderState.Undefined; } private void EnsureReadCapacity(int length) { if (_data.Length - _offset < length) { throw new CborContentException(SR.Cbor_Reader_InvalidCbor_UnexpectedEndOfBuffer); } } private static void EnsureReadCapacity(ReadOnlySpan<byte> buffer, int requiredLength) { if (buffer.Length < requiredLength) { throw new CborContentException(SR.Cbor_Reader_InvalidCbor_UnexpectedEndOfBuffer); } } private readonly struct StackFrame { public StackFrame( CborMajorType? type, int frameOffset, int? definiteLength, int itemsRead, int? currentKeyOffset, (int Offset, int Length)? previousKeyEncodingRange, HashSet<(int Offset, int Length)>? keyEncodingRanges) { MajorType = type; FrameOffset = frameOffset; DefiniteLength = definiteLength; ItemsRead = itemsRead; CurrentKeyOffset = currentKeyOffset; PreviousKeyEncodingRange = previousKeyEncodingRange; KeyEncodingRanges = keyEncodingRanges; } public CborMajorType? MajorType { get; } public int FrameOffset { get; } public int? DefiniteLength { get; } public int ItemsRead { get; } public int? CurrentKeyOffset { get; } public (int Offset, int Length)? PreviousKeyEncodingRange { get; } public HashSet<(int Offset, int Length)>? KeyEncodingRanges { get; } } private void RestoreStackFrame(in StackFrame frame) { _currentMajorType = frame.MajorType; _frameOffset = frame.FrameOffset; _definiteLength = frame.DefiniteLength; _itemsRead = frame.ItemsRead; _currentKeyOffset = frame.CurrentKeyOffset; _previousKeyEncodingRange = frame.PreviousKeyEncodingRange; _keyEncodingRanges = frame.KeyEncodingRanges; // Popping items from the stack can change the reader state // without necessarily needing to advance the buffer // (e.g. we're at the end of a definite-length collection). // We therefore need to invalidate the cache here. _cachedState = CborReaderState.Undefined; } // Struct containing checkpoint data for rolling back reader state in the event of a failure // NB checkpoints do not contain stack information, so we can only roll back provided that the // reader is within the original context in which the checkpoint was created private readonly struct Checkpoint { public Checkpoint( int depth, int offset, int frameOffset, int itemsRead, int? currentKeyOffset, (int Offset, int Length)? previousKeyEncodingRange) { Depth = depth; Offset = offset; FrameOffset = frameOffset; ItemsRead = itemsRead; CurrentKeyOffset = currentKeyOffset; PreviousKeyEncodingRange = previousKeyEncodingRange; } public int Depth { get; } public int Offset { get; } public int FrameOffset { get; } public int ItemsRead { get; } public int? CurrentKeyOffset { get; } public (int Offset, int Length)? PreviousKeyEncodingRange { get; } } private Checkpoint CreateCheckpoint() { return new Checkpoint( depth: CurrentDepth, offset: _offset, frameOffset: _frameOffset, itemsRead: _itemsRead, currentKeyOffset: _currentKeyOffset, previousKeyEncodingRange: _previousKeyEncodingRange); } private void RestoreCheckpoint(in Checkpoint checkpoint) { int restoreHeight = CurrentDepth - checkpoint.Depth; Debug.Assert(restoreHeight >= 0, "Attempting to restore checkpoint outside of its original context."); if (restoreHeight > 0) { // pop any nested contexts added after the checkpoint Debug.Assert(_nestedDataItems != null); Debug.Assert(_nestedDataItems.ToArray()[restoreHeight - 1].FrameOffset == checkpoint.FrameOffset, "Attempting to restore checkpoint outside of its original context."); StackFrame frame; for (int i = 0; i < restoreHeight - 1; i++) { frame = _nestedDataItems.Pop(); ReturnKeyEncodingRangeAllocation(frame.KeyEncodingRanges); } frame = _nestedDataItems.Pop(); RestoreStackFrame(in frame); } else { Debug.Assert(checkpoint.FrameOffset == _frameOffset, "Attempting to restore checkpoint outside of its original context."); } // Remove any key encodings added after the current checkpoint. // This is only needed when rolling back key reads in the Strict conformance mode. if (_keyEncodingRanges != null && _itemsRead > checkpoint.ItemsRead) { int checkpointOffset = checkpoint.Offset; _keyEncodingRanges.RemoveWhere(key => key.Offset >= checkpointOffset); } _offset = checkpoint.Offset; _itemsRead = checkpoint.ItemsRead; _previousKeyEncodingRange = checkpoint.PreviousKeyEncodingRange; _currentKeyOffset = checkpoint.CurrentKeyOffset; _cachedState = CborReaderState.Undefined; Debug.Assert(CurrentDepth == checkpoint.Depth); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; namespace System.Formats.Cbor { /// <summary>A stateful, forward-only reader for Concise Binary Object Representation (CBOR) encoded data.</summary> public partial class CborReader { private readonly ReadOnlyMemory<byte> _data; private int _offset; private Stack<StackFrame>? _nestedDataItems; private CborMajorType? _currentMajorType; // major type of the currently written data item. Null iff at the root context private int? _definiteLength; // predetermined definite-length of current data item context private int _itemsRead; // number of items read in the current context private int _frameOffset; // buffer offset particular to the current data item context private bool _isTagContext; // true if reader is expecting a tagged value // Map-specific book-keeping private int? _currentKeyOffset; // offset for the current key encoding private (int Offset, int Length)? _previousKeyEncodingRange; // previous key encoding range private HashSet<(int Offset, int Length)>? _keyEncodingRanges; // all key encoding ranges up to encoding equality // flag used to temporarily disable conformance mode checks, // e.g. during a skip operation over nonconforming encodings. private bool _isConformanceModeCheckEnabled = true; // keeps a cached copy of the reader state; 'None' denotes uncomputed state private CborReaderState _cachedState = CborReaderState.Undefined; /// <summary>Gets the conformance mode used by this reader.</summary> /// <value>One of the enumeration values that represents the conformance mode used by this reader.</value> public CborConformanceMode ConformanceMode { get; } /// <summary>Gets a value that indicates whether this reader allows multiple root-level CBOR data items.</summary> /// <value><see langword="true" /> if this reader allows multiple root-level CBOR data items; <see langword="false" /> otherwise.</value> public bool AllowMultipleRootLevelValues { get; } /// <summary>Gets the reader's current level of nestedness in the CBOR document.</summary> /// <value>A number that represents the current level of nestedness in the CBOR document.</value> public int CurrentDepth => _nestedDataItems is null ? 0 : _nestedDataItems.Count; /// <summary>Gets the total number of unread bytes in the buffer.</summary> /// <value>The total number of unread bytes in the buffer.</value> public int BytesRemaining => _data.Length - _offset; /// <summary>Initializes a <see cref="CborReader" /> instance over the specified <paramref name="data" /> with the given configuration.</summary> /// <param name="data">The CBOR encoded data to read.</param> /// <param name="conformanceMode">One of the enumeration values to specify a conformance mode guiding the checks performed on the encoded data. /// Defaults to <see cref="CborConformanceMode.Strict" /> conformance mode.</param> /// <param name="allowMultipleRootLevelValues"><see langword="true" /> to indicate that multiple root-level values are supported by the reader; otherwise, <see langword="false" />.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="conformanceMode" /> is not defined.</exception> public CborReader(ReadOnlyMemory<byte> data, CborConformanceMode conformanceMode = CborConformanceMode.Strict, bool allowMultipleRootLevelValues = false) { CborConformanceModeHelpers.Validate(conformanceMode); _data = data; ConformanceMode = conformanceMode; AllowMultipleRootLevelValues = allowMultipleRootLevelValues; _definiteLength = allowMultipleRootLevelValues ? null : (int?)1; } /// <summary>Reads the next CBOR data item, returning a <see cref="ReadOnlyMemory{T}" /> view of the encoded value. For indefinite length encodings this includes the break byte.</summary> /// <param name="disableConformanceModeChecks"><see langword="true" /> to disable conformance mode validation for the read value, equivalent to using <see cref="CborConformanceMode.Lax" />; otherwise, <see langword="false" />.</param> /// <returns>A view of the encoded value as a contiguous region of memory.</returns> /// <exception cref="CborContentException"><para>The data item is not a valid CBOR data item encoding.</para> /// <para>-or-</para> /// <para>The CBOR encoding is not valid under the current conformance mode.</para></exception> public ReadOnlyMemory<byte> ReadEncodedValue(bool disableConformanceModeChecks = false) { // keep a snapshot of the current offset int initialOffset = _offset; // call skip to read and validate the next value SkipValue(disableConformanceModeChecks); // return the slice corresponding to the consumed value return _data.Slice(initialOffset, _offset - initialOffset); } private CborInitialByte PeekInitialByte() { if (_definiteLength - _itemsRead == 0) { throw new InvalidOperationException(SR.Cbor_Reader_NoMoreDataItemsToRead); } if (_offset == _data.Length) { if (_currentMajorType is null && _definiteLength is null && _offset > 0) { // we are at the end of a well-formed sequence of root-level CBOR values throw new InvalidOperationException(SR.Cbor_Reader_NoMoreDataItemsToRead); } throw new CborContentException(SR.Cbor_Reader_InvalidCbor_UnexpectedEndOfBuffer); } var nextByte = new CborInitialByte(_data.Span[_offset]); switch (_currentMajorType) { case CborMajorType.ByteString: case CborMajorType.TextString: // Indefinite-length string contexts allow two possible data items: // 1) Definite-length string chunks of the same major type OR // 2) a break byte denoting the end of the indefinite-length string context. if (nextByte.InitialByte == CborInitialByte.IndefiniteLengthBreakByte || nextByte.MajorType == _currentMajorType.Value && nextByte.AdditionalInfo != CborAdditionalInfo.IndefiniteLength) { break; } throw new CborContentException(SR.Format(SR.Cbor_Reader_InvalidCbor_IndefiniteLengthStringContainsInvalidDataItem, (int)nextByte.MajorType)); } return nextByte; } private CborInitialByte PeekInitialByte(CborMajorType expectedType) { CborInitialByte result = PeekInitialByte(); if (expectedType != result.MajorType) { throw new InvalidOperationException(SR.Format(SR.Cbor_Reader_MajorTypeMismatch, (int)result.MajorType)); } return result; } private void ValidateNextByteIsBreakByte() { CborInitialByte result = PeekInitialByte(); if (result.InitialByte != CborInitialByte.IndefiniteLengthBreakByte) { throw new InvalidOperationException(SR.Cbor_NotAtEndOfIndefiniteLengthDataItem); } } private void PushDataItem(CborMajorType majorType, int? definiteLength) { _nestedDataItems ??= new Stack<StackFrame>(); var frame = new StackFrame( type: _currentMajorType, frameOffset: _frameOffset, definiteLength: _definiteLength, itemsRead: _itemsRead, currentKeyOffset: _currentKeyOffset, previousKeyEncodingRange: _previousKeyEncodingRange, keyEncodingRanges: _keyEncodingRanges ); _nestedDataItems.Push(frame); _currentMajorType = majorType; _definiteLength = definiteLength; _itemsRead = 0; _frameOffset = _offset; _isTagContext = false; _currentKeyOffset = null; _previousKeyEncodingRange = null; _keyEncodingRanges = null; } private void PopDataItem(CborMajorType expectedType) { if (_currentMajorType is null) { throw new InvalidOperationException(SR.Cbor_Reader_IsAtRootContext); } Debug.Assert(_nestedDataItems?.Count > 0); if (expectedType != _currentMajorType) { throw new InvalidOperationException(SR.Format(SR.Cbor_PopMajorTypeMismatch, (int)_currentMajorType.Value)); } if (_definiteLength - _itemsRead > 0) { throw new InvalidOperationException(SR.Cbor_NotAtEndOfDefiniteLengthDataItem); } if (_isTagContext) { throw new CborContentException(SR.Cbor_Reader_InvalidCbor_TagNotFollowedByValue); } if (_currentMajorType == CborMajorType.Map) { ReturnKeyEncodingRangeAllocation(_keyEncodingRanges); } StackFrame frame = _nestedDataItems.Pop(); RestoreStackFrame(in frame); } private void AdvanceDataItemCounters() { Debug.Assert(_definiteLength is null || _definiteLength - _itemsRead > 0); if (_currentMajorType == CborMajorType.Map) { if (_itemsRead % 2 == 0) { HandleMapKeyRead(); } else { HandleMapValueRead(); } } _itemsRead++; _isTagContext = false; } private ReadOnlySpan<byte> GetRemainingBytes() => _data.Span.Slice(_offset); private void AdvanceBuffer(int length) { Debug.Assert(_offset + length <= _data.Length); _offset += length; // invalidate the state cache _cachedState = CborReaderState.Undefined; } private void ResetBuffer(int position) { Debug.Assert(position <= _data.Length); _offset = position; // invalidate the state cache _cachedState = CborReaderState.Undefined; } private void EnsureReadCapacity(int length) { if (_data.Length - _offset < length) { throw new CborContentException(SR.Cbor_Reader_InvalidCbor_UnexpectedEndOfBuffer); } } private static void EnsureReadCapacity(ReadOnlySpan<byte> buffer, int requiredLength) { if (buffer.Length < requiredLength) { throw new CborContentException(SR.Cbor_Reader_InvalidCbor_UnexpectedEndOfBuffer); } } private readonly struct StackFrame { public StackFrame( CborMajorType? type, int frameOffset, int? definiteLength, int itemsRead, int? currentKeyOffset, (int Offset, int Length)? previousKeyEncodingRange, HashSet<(int Offset, int Length)>? keyEncodingRanges) { MajorType = type; FrameOffset = frameOffset; DefiniteLength = definiteLength; ItemsRead = itemsRead; CurrentKeyOffset = currentKeyOffset; PreviousKeyEncodingRange = previousKeyEncodingRange; KeyEncodingRanges = keyEncodingRanges; } public CborMajorType? MajorType { get; } public int FrameOffset { get; } public int? DefiniteLength { get; } public int ItemsRead { get; } public int? CurrentKeyOffset { get; } public (int Offset, int Length)? PreviousKeyEncodingRange { get; } public HashSet<(int Offset, int Length)>? KeyEncodingRanges { get; } } private void RestoreStackFrame(in StackFrame frame) { _currentMajorType = frame.MajorType; _frameOffset = frame.FrameOffset; _definiteLength = frame.DefiniteLength; _itemsRead = frame.ItemsRead; _currentKeyOffset = frame.CurrentKeyOffset; _previousKeyEncodingRange = frame.PreviousKeyEncodingRange; _keyEncodingRanges = frame.KeyEncodingRanges; // Popping items from the stack can change the reader state // without necessarily needing to advance the buffer // (e.g. we're at the end of a definite-length collection). // We therefore need to invalidate the cache here. _cachedState = CborReaderState.Undefined; } // Struct containing checkpoint data for rolling back reader state in the event of a failure // NB checkpoints do not contain stack information, so we can only roll back provided that the // reader is within the original context in which the checkpoint was created private readonly struct Checkpoint { public Checkpoint( int depth, int offset, int frameOffset, int itemsRead, int? currentKeyOffset, (int Offset, int Length)? previousKeyEncodingRange) { Depth = depth; Offset = offset; FrameOffset = frameOffset; ItemsRead = itemsRead; CurrentKeyOffset = currentKeyOffset; PreviousKeyEncodingRange = previousKeyEncodingRange; } public int Depth { get; } public int Offset { get; } public int FrameOffset { get; } public int ItemsRead { get; } public int? CurrentKeyOffset { get; } public (int Offset, int Length)? PreviousKeyEncodingRange { get; } } private Checkpoint CreateCheckpoint() { return new Checkpoint( depth: CurrentDepth, offset: _offset, frameOffset: _frameOffset, itemsRead: _itemsRead, currentKeyOffset: _currentKeyOffset, previousKeyEncodingRange: _previousKeyEncodingRange); } private void RestoreCheckpoint(in Checkpoint checkpoint) { int restoreHeight = CurrentDepth - checkpoint.Depth; Debug.Assert(restoreHeight >= 0, "Attempting to restore checkpoint outside of its original context."); if (restoreHeight > 0) { // pop any nested contexts added after the checkpoint Debug.Assert(_nestedDataItems != null); Debug.Assert(_nestedDataItems.ToArray()[restoreHeight - 1].FrameOffset == checkpoint.FrameOffset, "Attempting to restore checkpoint outside of its original context."); StackFrame frame; for (int i = 0; i < restoreHeight - 1; i++) { frame = _nestedDataItems.Pop(); ReturnKeyEncodingRangeAllocation(frame.KeyEncodingRanges); } frame = _nestedDataItems.Pop(); RestoreStackFrame(in frame); } else { Debug.Assert(checkpoint.FrameOffset == _frameOffset, "Attempting to restore checkpoint outside of its original context."); } // Remove any key encodings added after the current checkpoint. // This is only needed when rolling back key reads in the Strict conformance mode. if (_keyEncodingRanges != null && _itemsRead > checkpoint.ItemsRead) { int checkpointOffset = checkpoint.Offset; _keyEncodingRanges.RemoveWhere(key => key.Offset >= checkpointOffset); } _offset = checkpoint.Offset; _itemsRead = checkpoint.ItemsRead; _previousKeyEncodingRange = checkpoint.PreviousKeyEncodingRange; _currentKeyOffset = checkpoint.CurrentKeyOffset; _cachedState = CborReaderState.Undefined; Debug.Assert(CurrentDepth == checkpoint.Depth); } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.Array.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.Formats.Cbor { public partial class CborWriter { // Implements major type 4 encoding per https://tools.ietf.org/html/rfc7049#section-2.1 /// <summary>Writes the start of a definite or indefinite-length array (major type 4).</summary> /// <param name="definiteLength">The length of the definite-length array, or <see langword="null" /> for an indefinite-length array.</param> /// <exception cref="ArgumentOutOfRangeException">The <paramref name="definiteLength" /> parameter cannot be negative.</exception> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> /// <remarks> /// In canonical conformance modes, the writer will reject indefinite-length writes unless /// the <see cref="ConvertIndefiniteLengthEncodings" /> flag is enabled. /// </remarks> public void WriteStartArray(int? definiteLength) { if (definiteLength is null) { WriteStartArrayIndefiniteLength(); } else { WriteStartArrayDefiniteLength(definiteLength.Value); } } /// <summary>Writes the end of an array (major type 4).</summary> /// <exception cref="InvalidOperationException">The written data is not accepted under the current conformance mode. /// -or- /// The definite-length array anticipates more data items.</exception> public void WriteEndArray() { PopDataItem(CborMajorType.Array); AdvanceDataItemCounters(); } private void WriteStartArrayDefiniteLength(int definiteLength) { if (definiteLength < 0) { throw new ArgumentOutOfRangeException(nameof(definiteLength)); } WriteUnsignedInteger(CborMajorType.Array, (ulong)definiteLength); PushDataItem(CborMajorType.Array, definiteLength); } private void WriteStartArrayIndefiniteLength() { if (!ConvertIndefiniteLengthEncodings && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new InvalidOperationException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } EnsureWriteCapacity(1); WriteInitialByte(new CborInitialByte(CborMajorType.Array, CborAdditionalInfo.IndefiniteLength)); PushDataItem(CborMajorType.Array, definiteLength: null); } // perform an in-place conversion of an indefinite-length encoding into an equivalent definite-length private void PatchIndefiniteLengthCollection(CborMajorType majorType, int count) { Debug.Assert(majorType == CborMajorType.Array || majorType == CborMajorType.Map); int currentOffset = _offset; int bytesToShift = GetIntegerEncodingLength((ulong)count) - 1; if (bytesToShift > 0) { // length encoding requires more than 1 byte, need to shift encoded elements to the right EnsureWriteCapacity(bytesToShift); ReadOnlySpan<byte> elementEncoding = _buffer.AsSpan(_frameOffset, currentOffset - _frameOffset); Span<byte> target = _buffer.AsSpan(_frameOffset + bytesToShift, currentOffset - _frameOffset); elementEncoding.CopyTo(target); } // rewind to the start of the collection and write a new initial byte _offset = _frameOffset - 1; WriteUnsignedInteger(majorType, (ulong)count); _offset = currentOffset + bytesToShift; } } }
// 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.Formats.Cbor { public partial class CborWriter { // Implements major type 4 encoding per https://tools.ietf.org/html/rfc7049#section-2.1 /// <summary>Writes the start of a definite or indefinite-length array (major type 4).</summary> /// <param name="definiteLength">The length of the definite-length array, or <see langword="null" /> for an indefinite-length array.</param> /// <exception cref="ArgumentOutOfRangeException">The <paramref name="definiteLength" /> parameter cannot be negative.</exception> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> /// <remarks> /// In canonical conformance modes, the writer will reject indefinite-length writes unless /// the <see cref="ConvertIndefiniteLengthEncodings" /> flag is enabled. /// </remarks> public void WriteStartArray(int? definiteLength) { if (definiteLength is null) { WriteStartArrayIndefiniteLength(); } else { WriteStartArrayDefiniteLength(definiteLength.Value); } } /// <summary>Writes the end of an array (major type 4).</summary> /// <exception cref="InvalidOperationException"><para>The written data is not accepted under the current conformance mode.</para> /// <para>-or-</para> /// <para>The definite-length array anticipates more data items.</para></exception> public void WriteEndArray() { PopDataItem(CborMajorType.Array); AdvanceDataItemCounters(); } private void WriteStartArrayDefiniteLength(int definiteLength) { if (definiteLength < 0) { throw new ArgumentOutOfRangeException(nameof(definiteLength)); } WriteUnsignedInteger(CborMajorType.Array, (ulong)definiteLength); PushDataItem(CborMajorType.Array, definiteLength); } private void WriteStartArrayIndefiniteLength() { if (!ConvertIndefiniteLengthEncodings && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new InvalidOperationException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } EnsureWriteCapacity(1); WriteInitialByte(new CborInitialByte(CborMajorType.Array, CborAdditionalInfo.IndefiniteLength)); PushDataItem(CborMajorType.Array, definiteLength: null); } // perform an in-place conversion of an indefinite-length encoding into an equivalent definite-length private void PatchIndefiniteLengthCollection(CborMajorType majorType, int count) { Debug.Assert(majorType == CborMajorType.Array || majorType == CborMajorType.Map); int currentOffset = _offset; int bytesToShift = GetIntegerEncodingLength((ulong)count) - 1; if (bytesToShift > 0) { // length encoding requires more than 1 byte, need to shift encoded elements to the right EnsureWriteCapacity(bytesToShift); ReadOnlySpan<byte> elementEncoding = _buffer.AsSpan(_frameOffset, currentOffset - _frameOffset); Span<byte> target = _buffer.AsSpan(_frameOffset + bytesToShift, currentOffset - _frameOffset); elementEncoding.CopyTo(target); } // rewind to the start of the collection and write a new initial byte _offset = _frameOffset - 1; WriteUnsignedInteger(majorType, (ulong)count); _offset = currentOffset + bytesToShift; } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.Integer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; namespace System.Formats.Cbor { public partial class CborWriter { // Implements major type 0,1 encoding per https://tools.ietf.org/html/rfc7049#section-2.1 /// <summary>Writes a value as a signed integer encoding (major types 0,1)</summary> /// <param name="value">The value to write</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteInt32(int value) => WriteInt64(value); /// <summary>Writes the provided value as a signed integer encoding (major types 0,1)</summary> /// <param name="value">The value to write</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteInt64(long value) { if (value < 0) { ulong unsignedRepresentation = (value == long.MinValue) ? (ulong)long.MaxValue : (ulong)(-value) - 1; WriteUnsignedInteger(CborMajorType.NegativeInteger, unsignedRepresentation); } else { WriteUnsignedInteger(CborMajorType.UnsignedInteger, (ulong)value); } AdvanceDataItemCounters(); } /// <summary>Writes a value as an unsigned integer encoding (major type 0).</summary> /// <param name="value">The value to write</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> [CLSCompliant(false)] public void WriteUInt32(uint value) => WriteUInt64(value); /// <summary>Writes a value as an unsigned integer encoding (major type 0).</summary> /// <param name="value">The value to write</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> [CLSCompliant(false)] public void WriteUInt64(ulong value) { WriteUnsignedInteger(CborMajorType.UnsignedInteger, value); AdvanceDataItemCounters(); } /// <summary>Writes the provided value as a CBOR negative integer representation (major type 1).</summary> /// <param name="value">An unsigned integer denoting -1 minus the integer.</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> /// <remarks> /// This method supports encoding integers between -18446744073709551616 and -1. /// Useful for handling values that do not fit in the <see cref="long" /> type. /// </remarks> [CLSCompliant(false)] public void WriteCborNegativeIntegerRepresentation(ulong value) { WriteUnsignedInteger(CborMajorType.NegativeInteger, value); AdvanceDataItemCounters(); } private void WriteUnsignedInteger(CborMajorType type, ulong value) { if (value < (byte)CborAdditionalInfo.Additional8BitData) { EnsureWriteCapacity(1); WriteInitialByte(new CborInitialByte(type, (CborAdditionalInfo)value)); } else if (value <= byte.MaxValue) { EnsureWriteCapacity(1 + sizeof(byte)); WriteInitialByte(new CborInitialByte(type, CborAdditionalInfo.Additional8BitData)); _buffer[_offset++] = (byte)value; } else if (value <= ushort.MaxValue) { EnsureWriteCapacity(1 + sizeof(ushort)); WriteInitialByte(new CborInitialByte(type, CborAdditionalInfo.Additional16BitData)); BinaryPrimitives.WriteUInt16BigEndian(_buffer.AsSpan(_offset), (ushort)value); _offset += sizeof(ushort); } else if (value <= uint.MaxValue) { EnsureWriteCapacity(1 + sizeof(uint)); WriteInitialByte(new CborInitialByte(type, CborAdditionalInfo.Additional32BitData)); BinaryPrimitives.WriteUInt32BigEndian(_buffer.AsSpan(_offset), (uint)value); _offset += sizeof(uint); } else { EnsureWriteCapacity(1 + sizeof(ulong)); WriteInitialByte(new CborInitialByte(type, CborAdditionalInfo.Additional64BitData)); BinaryPrimitives.WriteUInt64BigEndian(_buffer.AsSpan(_offset), value); _offset += sizeof(ulong); } } private int GetIntegerEncodingLength(ulong value) { if (value < (byte)CborAdditionalInfo.Additional8BitData) { return 1; } else if (value <= byte.MaxValue) { return 1 + sizeof(byte); } else if (value <= ushort.MaxValue) { return 1 + sizeof(ushort); } else if (value <= uint.MaxValue) { return 1 + sizeof(uint); } else { return 1 + sizeof(ulong); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; namespace System.Formats.Cbor { public partial class CborWriter { // Implements major type 0,1 encoding per https://tools.ietf.org/html/rfc7049#section-2.1 /// <summary>Writes a value as a signed integer encoding (major types 0,1)</summary> /// <param name="value">The value to write</param> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> public void WriteInt32(int value) => WriteInt64(value); /// <summary>Writes the provided value as a signed integer encoding (major types 0,1)</summary> /// <param name="value">The value to write</param> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> public void WriteInt64(long value) { if (value < 0) { ulong unsignedRepresentation = (value == long.MinValue) ? (ulong)long.MaxValue : (ulong)(-value) - 1; WriteUnsignedInteger(CborMajorType.NegativeInteger, unsignedRepresentation); } else { WriteUnsignedInteger(CborMajorType.UnsignedInteger, (ulong)value); } AdvanceDataItemCounters(); } /// <summary>Writes a value as an unsigned integer encoding (major type 0).</summary> /// <param name="value">The value to write</param> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> [CLSCompliant(false)] public void WriteUInt32(uint value) => WriteUInt64(value); /// <summary>Writes a value as an unsigned integer encoding (major type 0).</summary> /// <param name="value">The value to write</param> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> [CLSCompliant(false)] public void WriteUInt64(ulong value) { WriteUnsignedInteger(CborMajorType.UnsignedInteger, value); AdvanceDataItemCounters(); } /// <summary>Writes the provided value as a CBOR negative integer representation (major type 1).</summary> /// <param name="value">An unsigned integer denoting -1 minus the integer.</param> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> /// <remarks> /// This method supports encoding integers between -18446744073709551616 and -1. /// Useful for handling values that do not fit in the <see cref="long" /> type. /// </remarks> [CLSCompliant(false)] public void WriteCborNegativeIntegerRepresentation(ulong value) { WriteUnsignedInteger(CborMajorType.NegativeInteger, value); AdvanceDataItemCounters(); } private void WriteUnsignedInteger(CborMajorType type, ulong value) { if (value < (byte)CborAdditionalInfo.Additional8BitData) { EnsureWriteCapacity(1); WriteInitialByte(new CborInitialByte(type, (CborAdditionalInfo)value)); } else if (value <= byte.MaxValue) { EnsureWriteCapacity(1 + sizeof(byte)); WriteInitialByte(new CborInitialByte(type, CborAdditionalInfo.Additional8BitData)); _buffer[_offset++] = (byte)value; } else if (value <= ushort.MaxValue) { EnsureWriteCapacity(1 + sizeof(ushort)); WriteInitialByte(new CborInitialByte(type, CborAdditionalInfo.Additional16BitData)); BinaryPrimitives.WriteUInt16BigEndian(_buffer.AsSpan(_offset), (ushort)value); _offset += sizeof(ushort); } else if (value <= uint.MaxValue) { EnsureWriteCapacity(1 + sizeof(uint)); WriteInitialByte(new CborInitialByte(type, CborAdditionalInfo.Additional32BitData)); BinaryPrimitives.WriteUInt32BigEndian(_buffer.AsSpan(_offset), (uint)value); _offset += sizeof(uint); } else { EnsureWriteCapacity(1 + sizeof(ulong)); WriteInitialByte(new CborInitialByte(type, CborAdditionalInfo.Additional64BitData)); BinaryPrimitives.WriteUInt64BigEndian(_buffer.AsSpan(_offset), value); _offset += sizeof(ulong); } } private int GetIntegerEncodingLength(ulong value) { if (value < (byte)CborAdditionalInfo.Additional8BitData) { return 1; } else if (value <= byte.MaxValue) { return 1 + sizeof(byte); } else if (value <= ushort.MaxValue) { return 1 + sizeof(ushort); } else if (value <= uint.MaxValue) { return 1 + sizeof(uint); } else { return 1 + sizeof(ulong); } } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.Map.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; namespace System.Formats.Cbor { public partial class CborWriter { // Implements major type 5 encoding per https://tools.ietf.org/html/rfc7049#section-2.1 private KeyEncodingComparer? _keyEncodingComparer; private Stack<HashSet<(int Offset, int Length)>>? _pooledKeyEncodingRangeSets; private Stack<List<KeyValuePairEncodingRange>>? _pooledKeyValuePairEncodingRangeLists; /// <summary>Writes the start of a definite or indefinite-length map (major type 5).</summary> /// <param name="definiteLength">The length of the definite-length map, or <see langword="null" /> for an indefinite-length map.</param> /// <exception cref="ArgumentOutOfRangeException">The <paramref name="definiteLength" /> parameter cannot be negative.</exception> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> /// <remarks> /// In canonical conformance modes, the writer will reject indefinite-length writes unless /// the <see cref="ConvertIndefiniteLengthEncodings" /> flag is enabled. /// Map contents are written as if arrays twice the length of the map's declared size. /// For instance, a map of size 1 containing a key of type <see cref="int" /> with a value of type string must be written /// by successive calls to <see cref="WriteInt32(int)" /> and <see cref="WriteTextString(System.ReadOnlySpan{char})" />. /// It is up to the caller to keep track of whether the next call is a key or a value. /// Fundamentally, this is a technical restriction stemming from the fact that CBOR allows keys of any type, /// for instance a map can contain keys that are maps themselves. /// </remarks> public void WriteStartMap(int? definiteLength) { if (definiteLength is null) { WriteStartMapIndefiniteLength(); } else { WriteStartMapDefiniteLength(definiteLength.Value); } } /// <summary>Writes the end of a map (major type 5).</summary> /// <exception cref="InvalidOperationException">The written data is not accepted under the current conformance mode. /// -or- /// The definite-length map anticipates more data items. /// -or- /// The latest key/value pair is lacking a value.</exception> public void WriteEndMap() { if (_itemsWritten % 2 == 1) { throw new InvalidOperationException(SR.Cbor_Writer_MapIncompleteKeyValuePair); } PopDataItem(CborMajorType.Map); AdvanceDataItemCounters(); } private void WriteStartMapDefiniteLength(int definiteLength) { if (definiteLength < 0 || definiteLength > int.MaxValue / 2) { throw new ArgumentOutOfRangeException(nameof(definiteLength)); } WriteUnsignedInteger(CborMajorType.Map, (ulong)definiteLength); PushDataItem(CborMajorType.Map, definiteLength: 2 * definiteLength); _currentKeyOffset = _offset; } private void WriteStartMapIndefiniteLength() { if (!ConvertIndefiniteLengthEncodings && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new InvalidOperationException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } EnsureWriteCapacity(1); WriteInitialByte(new CborInitialByte(CborMajorType.Map, CborAdditionalInfo.IndefiniteLength)); PushDataItem(CborMajorType.Map, definiteLength: null); _currentKeyOffset = _offset; } // // Map encoding conformance // private void HandleMapKeyWritten() { Debug.Assert(_currentKeyOffset != null && _currentValueOffset == null); if (CborConformanceModeHelpers.RequiresUniqueKeys(ConformanceMode)) { HashSet<(int Offset, int Length)> keyEncodingRanges = GetKeyEncodingRanges(); (int Offset, int Length) currentKey = (_currentKeyOffset.Value, _offset - _currentKeyOffset.Value); if (!keyEncodingRanges.Add(currentKey)) { // reset writer state to right before the offending key write _buffer.AsSpan(currentKey.Offset, _offset).Clear(); _offset = currentKey.Offset; throw new InvalidOperationException(SR.Format(SR.Cbor_ConformanceMode_ContainsDuplicateKeys, ConformanceMode)); } } // record the value buffer offset _currentValueOffset = _offset; } private void HandleMapValueWritten() { Debug.Assert(_currentKeyOffset != null && _currentValueOffset != null); if (CborConformanceModeHelpers.RequiresSortedKeys(ConformanceMode)) { List<KeyValuePairEncodingRange> keyValuePairEncodingRanges = GetKeyValueEncodingRanges(); var currentKeyValueRange = new KeyValuePairEncodingRange( offset: _currentKeyOffset.Value, keyLength: _currentValueOffset.Value - _currentKeyOffset.Value, totalLength: _offset - _currentKeyOffset.Value); // Check that the keys are written in sorted order. // Once invalidated, declare that the map requires sorting, // which will prompt a sorting of the encodings once map writes have completed. if (!_keysRequireSorting && keyValuePairEncodingRanges.Count > 0) { KeyEncodingComparer comparer = GetKeyEncodingComparer(); KeyValuePairEncodingRange previousKeyValueRange = keyValuePairEncodingRanges[keyValuePairEncodingRanges.Count - 1]; _keysRequireSorting = comparer.Compare(previousKeyValueRange, currentKeyValueRange) > 0; } keyValuePairEncodingRanges.Add(currentKeyValueRange); } // update offset state to the next key _currentKeyOffset = _offset; _currentValueOffset = null; } private void CompleteMapWrite() { if (_keysRequireSorting) { Debug.Assert(_keyValuePairEncodingRanges != null); // sort the key/value ranges in-place _keyValuePairEncodingRanges.Sort(GetKeyEncodingComparer()); // copy sorted ranges to temporary buffer int totalMapPayloadEncodingLength = _offset - _frameOffset; Span<byte> source = _buffer.AsSpan(); byte[] tempBuffer = s_bufferPool.Rent(totalMapPayloadEncodingLength); Span<byte> tmpSpan = tempBuffer.AsSpan(0, totalMapPayloadEncodingLength); Span<byte> s = tmpSpan; foreach (KeyValuePairEncodingRange range in _keyValuePairEncodingRanges) { ReadOnlySpan<byte> keyValuePairEncoding = source.Slice(range.Offset, range.TotalLength); keyValuePairEncoding.CopyTo(s); s = s.Slice(keyValuePairEncoding.Length); } Debug.Assert(s.IsEmpty); // now copy back to the original buffer segment & clean up tmpSpan.CopyTo(source.Slice(_frameOffset, totalMapPayloadEncodingLength)); s_bufferPool.Return(tempBuffer); } ReturnKeyEncodingRangeAllocation(); ReturnKeyValuePairEncodingRangeAllocation(); } // Gets or initializes a hashset containing all key encoding ranges for the current CBOR map context // Equality of the HashSet is determined up to key encoding equality. private HashSet<(int Offset, int Length)> GetKeyEncodingRanges() { if (_keyEncodingRanges != null) { return _keyEncodingRanges; } if (_pooledKeyEncodingRangeSets != null && _pooledKeyEncodingRangeSets.TryPop(out HashSet<(int Offset, int Length)>? result)) { result.Clear(); return _keyEncodingRanges = result; } return _keyEncodingRanges = new HashSet<(int Offset, int Length)>(GetKeyEncodingComparer()); } // Gets or initializes a list containing all key/value encoding ranges for the current CBOR map context private void ReturnKeyEncodingRangeAllocation() { if (_keyEncodingRanges != null) { _pooledKeyEncodingRangeSets ??= new Stack<HashSet<(int Offset, int Length)>>(); _pooledKeyEncodingRangeSets.Push(_keyEncodingRanges); _keyEncodingRanges = null; } } private List<KeyValuePairEncodingRange> GetKeyValueEncodingRanges() { if (_keyValuePairEncodingRanges != null) { return _keyValuePairEncodingRanges; } if (_pooledKeyValuePairEncodingRangeLists != null && _pooledKeyValuePairEncodingRangeLists.TryPop(out List<KeyValuePairEncodingRange>? result)) { result.Clear(); return _keyValuePairEncodingRanges = result; } return _keyValuePairEncodingRanges = new List<KeyValuePairEncodingRange>(); } private void ReturnKeyValuePairEncodingRangeAllocation() { if (_keyValuePairEncodingRanges != null) { _pooledKeyValuePairEncodingRangeLists ??= new Stack<List<KeyValuePairEncodingRange>>(); _pooledKeyValuePairEncodingRangeLists.Push(_keyValuePairEncodingRanges); _keyValuePairEncodingRanges = null; } } private KeyEncodingComparer GetKeyEncodingComparer() { return _keyEncodingComparer ??= new KeyEncodingComparer(this); } private readonly struct KeyValuePairEncodingRange { public KeyValuePairEncodingRange(int offset, int keyLength, int totalLength) { Offset = offset; KeyLength = keyLength; TotalLength = totalLength; } public int Offset { get; } public int KeyLength { get; } public int TotalLength { get; } } // Defines order and equality semantics for a key/value encoding range pair up to key encoding private sealed class KeyEncodingComparer : IComparer<KeyValuePairEncodingRange>, IEqualityComparer<(int Offset, int Length)> { private readonly CborWriter _writer; public KeyEncodingComparer(CborWriter writer) { _writer = writer; } private Span<byte> GetKeyEncoding((int Offset, int Length) range) { return _writer._buffer.AsSpan(range.Offset, range.Length); } private Span<byte> GetKeyEncoding(in KeyValuePairEncodingRange range) { return _writer._buffer.AsSpan(range.Offset, range.KeyLength); } public int GetHashCode((int Offset, int Length) range) { return CborConformanceModeHelpers.GetKeyEncodingHashCode(GetKeyEncoding(range)); } public bool Equals((int Offset, int Length) x, (int Offset, int Length) y) { return CborConformanceModeHelpers.AreEqualKeyEncodings(GetKeyEncoding(x), GetKeyEncoding(y)); } public int Compare(KeyValuePairEncodingRange x, KeyValuePairEncodingRange y) { return CborConformanceModeHelpers.CompareKeyEncodings(GetKeyEncoding(in x), GetKeyEncoding(in y), _writer.ConformanceMode); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; namespace System.Formats.Cbor { public partial class CborWriter { // Implements major type 5 encoding per https://tools.ietf.org/html/rfc7049#section-2.1 private KeyEncodingComparer? _keyEncodingComparer; private Stack<HashSet<(int Offset, int Length)>>? _pooledKeyEncodingRangeSets; private Stack<List<KeyValuePairEncodingRange>>? _pooledKeyValuePairEncodingRangeLists; /// <summary>Writes the start of a definite or indefinite-length map (major type 5).</summary> /// <param name="definiteLength">The length of the definite-length map, or <see langword="null" /> for an indefinite-length map.</param> /// <exception cref="ArgumentOutOfRangeException">The <paramref name="definiteLength" /> parameter cannot be negative.</exception> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> /// <remarks> /// In canonical conformance modes, the writer will reject indefinite-length writes unless /// the <see cref="ConvertIndefiniteLengthEncodings" /> flag is enabled. /// Map contents are written as if arrays twice the length of the map's declared size. /// For example, a map of size 1 containing a key of type <see cref="int" /> with a value of type string must be written /// by successive calls to <see cref="WriteInt32(int)" /> and <see cref="WriteTextString(System.ReadOnlySpan{char})" />. /// It is up to the caller to keep track of whether the next call is a key or a value. /// Fundamentally, this is a technical restriction stemming from the fact that CBOR allows keys of any type, /// for example, a map can contain keys that are maps themselves. /// </remarks> public void WriteStartMap(int? definiteLength) { if (definiteLength is null) { WriteStartMapIndefiniteLength(); } else { WriteStartMapDefiniteLength(definiteLength.Value); } } /// <summary>Writes the end of a map (major type 5).</summary> /// <exception cref="InvalidOperationException"><para>The written data is not accepted under the current conformance mode.</para> /// <para>-or-</para> /// <para>The definite-length map anticipates more data items.</para> /// <para>-or-</para> /// <para>The latest key/value pair is lacking a value.</para></exception> public void WriteEndMap() { if (_itemsWritten % 2 == 1) { throw new InvalidOperationException(SR.Cbor_Writer_MapIncompleteKeyValuePair); } PopDataItem(CborMajorType.Map); AdvanceDataItemCounters(); } private void WriteStartMapDefiniteLength(int definiteLength) { if (definiteLength < 0 || definiteLength > int.MaxValue / 2) { throw new ArgumentOutOfRangeException(nameof(definiteLength)); } WriteUnsignedInteger(CborMajorType.Map, (ulong)definiteLength); PushDataItem(CborMajorType.Map, definiteLength: 2 * definiteLength); _currentKeyOffset = _offset; } private void WriteStartMapIndefiniteLength() { if (!ConvertIndefiniteLengthEncodings && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new InvalidOperationException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } EnsureWriteCapacity(1); WriteInitialByte(new CborInitialByte(CborMajorType.Map, CborAdditionalInfo.IndefiniteLength)); PushDataItem(CborMajorType.Map, definiteLength: null); _currentKeyOffset = _offset; } // // Map encoding conformance // private void HandleMapKeyWritten() { Debug.Assert(_currentKeyOffset != null && _currentValueOffset == null); if (CborConformanceModeHelpers.RequiresUniqueKeys(ConformanceMode)) { HashSet<(int Offset, int Length)> keyEncodingRanges = GetKeyEncodingRanges(); (int Offset, int Length) currentKey = (_currentKeyOffset.Value, _offset - _currentKeyOffset.Value); if (!keyEncodingRanges.Add(currentKey)) { // reset writer state to right before the offending key write _buffer.AsSpan(currentKey.Offset, _offset).Clear(); _offset = currentKey.Offset; throw new InvalidOperationException(SR.Format(SR.Cbor_ConformanceMode_ContainsDuplicateKeys, ConformanceMode)); } } // record the value buffer offset _currentValueOffset = _offset; } private void HandleMapValueWritten() { Debug.Assert(_currentKeyOffset != null && _currentValueOffset != null); if (CborConformanceModeHelpers.RequiresSortedKeys(ConformanceMode)) { List<KeyValuePairEncodingRange> keyValuePairEncodingRanges = GetKeyValueEncodingRanges(); var currentKeyValueRange = new KeyValuePairEncodingRange( offset: _currentKeyOffset.Value, keyLength: _currentValueOffset.Value - _currentKeyOffset.Value, totalLength: _offset - _currentKeyOffset.Value); // Check that the keys are written in sorted order. // Once invalidated, declare that the map requires sorting, // which will prompt a sorting of the encodings once map writes have completed. if (!_keysRequireSorting && keyValuePairEncodingRanges.Count > 0) { KeyEncodingComparer comparer = GetKeyEncodingComparer(); KeyValuePairEncodingRange previousKeyValueRange = keyValuePairEncodingRanges[keyValuePairEncodingRanges.Count - 1]; _keysRequireSorting = comparer.Compare(previousKeyValueRange, currentKeyValueRange) > 0; } keyValuePairEncodingRanges.Add(currentKeyValueRange); } // update offset state to the next key _currentKeyOffset = _offset; _currentValueOffset = null; } private void CompleteMapWrite() { if (_keysRequireSorting) { Debug.Assert(_keyValuePairEncodingRanges != null); // sort the key/value ranges in-place _keyValuePairEncodingRanges.Sort(GetKeyEncodingComparer()); // copy sorted ranges to temporary buffer int totalMapPayloadEncodingLength = _offset - _frameOffset; Span<byte> source = _buffer.AsSpan(); byte[] tempBuffer = s_bufferPool.Rent(totalMapPayloadEncodingLength); Span<byte> tmpSpan = tempBuffer.AsSpan(0, totalMapPayloadEncodingLength); Span<byte> s = tmpSpan; foreach (KeyValuePairEncodingRange range in _keyValuePairEncodingRanges) { ReadOnlySpan<byte> keyValuePairEncoding = source.Slice(range.Offset, range.TotalLength); keyValuePairEncoding.CopyTo(s); s = s.Slice(keyValuePairEncoding.Length); } Debug.Assert(s.IsEmpty); // now copy back to the original buffer segment & clean up tmpSpan.CopyTo(source.Slice(_frameOffset, totalMapPayloadEncodingLength)); s_bufferPool.Return(tempBuffer); } ReturnKeyEncodingRangeAllocation(); ReturnKeyValuePairEncodingRangeAllocation(); } // Gets or initializes a hashset containing all key encoding ranges for the current CBOR map context // Equality of the HashSet is determined up to key encoding equality. private HashSet<(int Offset, int Length)> GetKeyEncodingRanges() { if (_keyEncodingRanges != null) { return _keyEncodingRanges; } if (_pooledKeyEncodingRangeSets != null && _pooledKeyEncodingRangeSets.TryPop(out HashSet<(int Offset, int Length)>? result)) { result.Clear(); return _keyEncodingRanges = result; } return _keyEncodingRanges = new HashSet<(int Offset, int Length)>(GetKeyEncodingComparer()); } // Gets or initializes a list containing all key/value encoding ranges for the current CBOR map context private void ReturnKeyEncodingRangeAllocation() { if (_keyEncodingRanges != null) { _pooledKeyEncodingRangeSets ??= new Stack<HashSet<(int Offset, int Length)>>(); _pooledKeyEncodingRangeSets.Push(_keyEncodingRanges); _keyEncodingRanges = null; } } private List<KeyValuePairEncodingRange> GetKeyValueEncodingRanges() { if (_keyValuePairEncodingRanges != null) { return _keyValuePairEncodingRanges; } if (_pooledKeyValuePairEncodingRangeLists != null && _pooledKeyValuePairEncodingRangeLists.TryPop(out List<KeyValuePairEncodingRange>? result)) { result.Clear(); return _keyValuePairEncodingRanges = result; } return _keyValuePairEncodingRanges = new List<KeyValuePairEncodingRange>(); } private void ReturnKeyValuePairEncodingRangeAllocation() { if (_keyValuePairEncodingRanges != null) { _pooledKeyValuePairEncodingRangeLists ??= new Stack<List<KeyValuePairEncodingRange>>(); _pooledKeyValuePairEncodingRangeLists.Push(_keyValuePairEncodingRanges); _keyValuePairEncodingRanges = null; } } private KeyEncodingComparer GetKeyEncodingComparer() { return _keyEncodingComparer ??= new KeyEncodingComparer(this); } private readonly struct KeyValuePairEncodingRange { public KeyValuePairEncodingRange(int offset, int keyLength, int totalLength) { Offset = offset; KeyLength = keyLength; TotalLength = totalLength; } public int Offset { get; } public int KeyLength { get; } public int TotalLength { get; } } // Defines order and equality semantics for a key/value encoding range pair up to key encoding private sealed class KeyEncodingComparer : IComparer<KeyValuePairEncodingRange>, IEqualityComparer<(int Offset, int Length)> { private readonly CborWriter _writer; public KeyEncodingComparer(CborWriter writer) { _writer = writer; } private Span<byte> GetKeyEncoding((int Offset, int Length) range) { return _writer._buffer.AsSpan(range.Offset, range.Length); } private Span<byte> GetKeyEncoding(in KeyValuePairEncodingRange range) { return _writer._buffer.AsSpan(range.Offset, range.KeyLength); } public int GetHashCode((int Offset, int Length) range) { return CborConformanceModeHelpers.GetKeyEncodingHashCode(GetKeyEncoding(range)); } public bool Equals((int Offset, int Length) x, (int Offset, int Length) y) { return CborConformanceModeHelpers.AreEqualKeyEncodings(GetKeyEncoding(x), GetKeyEncoding(y)); } public int Compare(KeyValuePairEncodingRange x, KeyValuePairEncodingRange y) { return CborConformanceModeHelpers.CompareKeyEncodings(GetKeyEncoding(in x), GetKeyEncoding(in y), _writer.ConformanceMode); } } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.Simple.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; namespace System.Formats.Cbor { public partial class CborWriter { // Implements major type 7 encoding per https://tools.ietf.org/html/rfc7049#section-2.1 /// <summary>Writes a single-precision floating point number (major type 7).</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteSingle(float value) { if (!CborConformanceModeHelpers.RequiresPreservingFloatPrecision(ConformanceMode) && TryConvertSingleToHalf(value, out var half)) { WriteHalf(half); } else { WriteSingleCore(value); } } /// <summary>Writes a double-precision floating point number (major type 7).</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteDouble(double value) { if (!CborConformanceModeHelpers.RequiresPreservingFloatPrecision(ConformanceMode) && TryConvertDoubleToSingle(value, out float single)) { if (TryConvertSingleToHalf(single, out var half)) { WriteHalf(half); } else { WriteSingleCore(single); } } else { WriteDoubleCore(value); } } private void WriteSingleCore(float value) { EnsureWriteCapacity(1 + sizeof(float)); WriteInitialByte(new CborInitialByte(CborMajorType.Simple, CborAdditionalInfo.Additional32BitData)); CborHelpers.WriteSingleBigEndian(_buffer.AsSpan(_offset), value); _offset += sizeof(float); AdvanceDataItemCounters(); } private void WriteDoubleCore(double value) { EnsureWriteCapacity(1 + sizeof(double)); WriteInitialByte(new CborInitialByte(CborMajorType.Simple, CborAdditionalInfo.Additional64BitData)); CborHelpers.WriteDoubleBigEndian(_buffer.AsSpan(_offset), value); _offset += sizeof(double); AdvanceDataItemCounters(); } /// <summary>Writes a boolean value (major type 7).</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteBoolean(bool value) { WriteSimpleValue(value ? CborSimpleValue.True : CborSimpleValue.False); } /// <summary>Writes a <see langword="null" /> value (major type 7).</summary> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteNull() { WriteSimpleValue(CborSimpleValue.Null); } /// <summary>Writes a simple value encoding (major type 7).</summary> /// <param name="value">The value to write.</param> /// <exception cref="ArgumentOutOfRangeException">The <paramref name="value" /> parameter is in the invalid 24-31 range.</exception> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteSimpleValue(CborSimpleValue value) { if (value < (CborSimpleValue)CborAdditionalInfo.Additional8BitData) { EnsureWriteCapacity(1); WriteInitialByte(new CborInitialByte(CborMajorType.Simple, (CborAdditionalInfo)value)); } else if (value <= (CborSimpleValue)CborAdditionalInfo.IndefiniteLength && CborConformanceModeHelpers.RequireCanonicalSimpleValueEncodings(ConformanceMode)) { throw new ArgumentOutOfRangeException(SR.Format(SR.Cbor_ConformanceMode_InvalidSimpleValueEncoding, ConformanceMode)); } else { EnsureWriteCapacity(2); WriteInitialByte(new CborInitialByte(CborMajorType.Simple, CborAdditionalInfo.Additional8BitData)); _buffer[_offset++] = (byte)value; } AdvanceDataItemCounters(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryConvertDoubleToSingle(double value, out float result) { result = (float)value; return BitConverter.DoubleToInt64Bits(result) == BitConverter.DoubleToInt64Bits(value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; namespace System.Formats.Cbor { public partial class CborWriter { // Implements major type 7 encoding per https://tools.ietf.org/html/rfc7049#section-2.1 /// <summary>Writes a single-precision floating point number (major type 7).</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> public void WriteSingle(float value) { if (!CborConformanceModeHelpers.RequiresPreservingFloatPrecision(ConformanceMode) && TryConvertSingleToHalf(value, out var half)) { WriteHalf(half); } else { WriteSingleCore(value); } } /// <summary>Writes a double-precision floating point number (major type 7).</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> public void WriteDouble(double value) { if (!CborConformanceModeHelpers.RequiresPreservingFloatPrecision(ConformanceMode) && TryConvertDoubleToSingle(value, out float single)) { if (TryConvertSingleToHalf(single, out var half)) { WriteHalf(half); } else { WriteSingleCore(single); } } else { WriteDoubleCore(value); } } private void WriteSingleCore(float value) { EnsureWriteCapacity(1 + sizeof(float)); WriteInitialByte(new CborInitialByte(CborMajorType.Simple, CborAdditionalInfo.Additional32BitData)); CborHelpers.WriteSingleBigEndian(_buffer.AsSpan(_offset), value); _offset += sizeof(float); AdvanceDataItemCounters(); } private void WriteDoubleCore(double value) { EnsureWriteCapacity(1 + sizeof(double)); WriteInitialByte(new CborInitialByte(CborMajorType.Simple, CborAdditionalInfo.Additional64BitData)); CborHelpers.WriteDoubleBigEndian(_buffer.AsSpan(_offset), value); _offset += sizeof(double); AdvanceDataItemCounters(); } /// <summary>Writes a boolean value (major type 7).</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteBoolean(bool value) { WriteSimpleValue(value ? CborSimpleValue.True : CborSimpleValue.False); } /// <summary>Writes a <see langword="null" /> value (major type 7).</summary> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteNull() { WriteSimpleValue(CborSimpleValue.Null); } /// <summary>Writes a simple value encoding (major type 7).</summary> /// <param name="value">The value to write.</param> /// <exception cref="ArgumentOutOfRangeException">The <paramref name="value" /> parameter is in the invalid 24-31 range.</exception> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteSimpleValue(CborSimpleValue value) { if (value < (CborSimpleValue)CborAdditionalInfo.Additional8BitData) { EnsureWriteCapacity(1); WriteInitialByte(new CborInitialByte(CborMajorType.Simple, (CborAdditionalInfo)value)); } else if (value <= (CborSimpleValue)CborAdditionalInfo.IndefiniteLength && CborConformanceModeHelpers.RequireCanonicalSimpleValueEncodings(ConformanceMode)) { throw new ArgumentOutOfRangeException(SR.Format(SR.Cbor_ConformanceMode_InvalidSimpleValueEncoding, ConformanceMode)); } else { EnsureWriteCapacity(2); WriteInitialByte(new CborInitialByte(CborMajorType.Simple, CborAdditionalInfo.Additional8BitData)); _buffer[_offset++] = (byte)value; } AdvanceDataItemCounters(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryConvertDoubleToSingle(double value, out float result) { result = (float)value; return BitConverter.DoubleToInt64Bits(result) == BitConverter.DoubleToInt64Bits(value); } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.Simple.netcoreapp.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; using System.Runtime.CompilerServices; namespace System.Formats.Cbor { public partial class CborWriter { // Implements major type 7 encoding per https://tools.ietf.org/html/rfc7049#section-2.1 /// <summary>Writes a half-precision floating point number (major type 7).</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteHalf(Half value) { EnsureWriteCapacity(1 + sizeof(short)); WriteInitialByte(new CborInitialByte(CborMajorType.Simple, CborAdditionalInfo.Additional16BitData)); BinaryPrimitives.WriteHalfBigEndian(_buffer.AsSpan(_offset), value); _offset += sizeof(short); AdvanceDataItemCounters(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool TryConvertSingleToHalf(float value, out Half result) { result = (Half)value; return BitConverter.SingleToInt32Bits((float)result) == BitConverter.SingleToInt32Bits(value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; using System.Runtime.CompilerServices; namespace System.Formats.Cbor { public partial class CborWriter { // Implements major type 7 encoding per https://tools.ietf.org/html/rfc7049#section-2.1 /// <summary>Writes a half-precision floating point number (major type 7).</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> public void WriteHalf(Half value) { EnsureWriteCapacity(1 + sizeof(short)); WriteInitialByte(new CborInitialByte(CborMajorType.Simple, CborAdditionalInfo.Additional16BitData)); BinaryPrimitives.WriteHalfBigEndian(_buffer.AsSpan(_offset), value); _offset += sizeof(short); AdvanceDataItemCounters(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool TryConvertSingleToHalf(float value, out Half result) { result = (Half)value; return BitConverter.SingleToInt32Bits((float)result) == BitConverter.SingleToInt32Bits(value); } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.Simple.netstandard.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; using System.Runtime.CompilerServices; namespace System.Formats.Cbor { public partial class CborWriter { // Implements major type 7 encoding per https://tools.ietf.org/html/rfc7049#section-2.1 /// <summary>Writes a half-precision floating point number (major type 7).</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> private void WriteHalf(ushort value) { EnsureWriteCapacity(1 + sizeof(ushort)); WriteInitialByte(new CborInitialByte(CborMajorType.Simple, CborAdditionalInfo.Additional16BitData)); CborHelpers.WriteHalfBigEndian(_buffer.AsSpan(_offset), value); _offset += sizeof(ushort); AdvanceDataItemCounters(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool TryConvertSingleToHalf(float value, out ushort result) { result = HalfHelpers.FloatToHalf(value); return CborHelpers.SingleToInt32Bits(HalfHelpers.HalfToFloat(result)) == CborHelpers.SingleToInt32Bits(value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; using System.Runtime.CompilerServices; namespace System.Formats.Cbor { public partial class CborWriter { // Implements major type 7 encoding per https://tools.ietf.org/html/rfc7049#section-2.1 /// <summary>Writes a half-precision floating point number (major type 7).</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> private void WriteHalf(ushort value) { EnsureWriteCapacity(1 + sizeof(ushort)); WriteInitialByte(new CborInitialByte(CborMajorType.Simple, CborAdditionalInfo.Additional16BitData)); CborHelpers.WriteHalfBigEndian(_buffer.AsSpan(_offset), value); _offset += sizeof(ushort); AdvanceDataItemCounters(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool TryConvertSingleToHalf(float value, out ushort result) { result = HalfHelpers.FloatToHalf(value); return CborHelpers.SingleToInt32Bits(HalfHelpers.HalfToFloat(result)) == CborHelpers.SingleToInt32Bits(value); } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.String.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace System.Formats.Cbor { public partial class CborWriter { // Implements major type 2,3 encoding per https://tools.ietf.org/html/rfc7049#section-2.1 // keeps track of chunk offsets for written indefinite-length string ranges private List<(int Offset, int Length)>? _currentIndefiniteLengthStringRanges; /// <summary>Writes a buffer as a byte string encoding (major type 2).</summary> /// <param name="value">The value to write.</param> /// <exception cref="ArgumentNullException">The provided value cannot be <see langword="null" />.</exception> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteByteString(byte[] value!!) { WriteByteString(value.AsSpan()); } /// <summary>Writes a buffer as a byte string encoding (major type 2).</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteByteString(ReadOnlySpan<byte> value) { WriteUnsignedInteger(CborMajorType.ByteString, (ulong)value.Length); EnsureWriteCapacity(value.Length); if (ConvertIndefiniteLengthEncodings && _currentMajorType == CborMajorType.ByteString) { // operation is writing chunk of an indefinite-length string // the string will be converted to a definite-length encoding later, // so we need to record the ranges of each chunk Debug.Assert(_currentIndefiniteLengthStringRanges != null); _currentIndefiniteLengthStringRanges.Add((_offset, value.Length)); } value.CopyTo(_buffer.AsSpan(_offset)); _offset += value.Length; AdvanceDataItemCounters(); } /// <summary>Writes the start of an indefinite-length byte string (major type 2).</summary> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> /// <remarks> /// Pushes a context where definite-length chunks of the same major type can be written. /// In canonical conformance modes, the writer will reject indefinite-length writes unless /// the <see cref="ConvertIndefiniteLengthEncodings" /> flag is enabled. /// </remarks> public void WriteStartIndefiniteLengthByteString() { if (!ConvertIndefiniteLengthEncodings && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new InvalidOperationException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } if (ConvertIndefiniteLengthEncodings) { // Writer does not allow indefinite-length encodings. // We need to keep track of chunk offsets to convert to // a definite-length encoding once writing is complete. _currentIndefiniteLengthStringRanges ??= new List<(int, int)>(); } EnsureWriteCapacity(1); WriteInitialByte(new CborInitialByte(CborMajorType.ByteString, CborAdditionalInfo.IndefiniteLength)); PushDataItem(CborMajorType.ByteString, definiteLength: null); } /// <summary>Writes the end of an indefinite-length byte string (major type 2).</summary> /// <exception cref="InvalidOperationException">The written data is not accepted under the current conformance mode.</exception> public void WriteEndIndefiniteLengthByteString() { PopDataItem(CborMajorType.ByteString); AdvanceDataItemCounters(); } /// <summary>Writes a buffer as a UTF-8 string encoding (major type 3).</summary> /// <param name="value">The value to write.</param> /// <exception cref="ArgumentNullException">The provided value cannot be <see langword="null" />.</exception> /// <exception cref="ArgumentException">The supplied string is not a valid UTF-8 encoding, which is not permitted under the current conformance mode.</exception> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteTextString(string value!!) { WriteTextString(value.AsSpan()); } /// <summary>Writes a buffer as a UTF-8 string encoding (major type 3).</summary> /// <param name="value">The value to write.</param> /// <exception cref="ArgumentException">The supplied string is not a valid UTF-8 encoding, which is not permitted under the current conformance mode.</exception> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteTextString(ReadOnlySpan<char> value) { Encoding utf8Encoding = CborConformanceModeHelpers.GetUtf8Encoding(ConformanceMode); int length; try { length = CborHelpers.GetByteCount(utf8Encoding, value); } catch (EncoderFallbackException e) { throw new ArgumentException(SR.Cbor_Writer_InvalidUtf8String, e); } WriteUnsignedInteger(CborMajorType.TextString, (ulong)length); EnsureWriteCapacity(length); if (ConvertIndefiniteLengthEncodings && _currentMajorType == CborMajorType.TextString) { // operation is writing chunk of an indefinite-length string // the string will be converted to a definite-length encoding later, // so we need to record the ranges of each chunk Debug.Assert(_currentIndefiniteLengthStringRanges != null); _currentIndefiniteLengthStringRanges.Add((_offset, value.Length)); } CborHelpers.GetBytes(utf8Encoding, value, _buffer.AsSpan(_offset, length)); _offset += length; AdvanceDataItemCounters(); } /// <summary>Writes the start of an indefinite-length UTF-8 string (major type 3).</summary> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> /// <remarks> /// Pushes a context where definite-length chunks of the same major type can be written. /// In canonical conformance modes, the writer will reject indefinite-length writes unless /// the <see cref="ConvertIndefiniteLengthEncodings" /> flag is enabled. /// </remarks> public void WriteStartIndefiniteLengthTextString() { if (!ConvertIndefiniteLengthEncodings && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new InvalidOperationException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } if (ConvertIndefiniteLengthEncodings) { // Writer does not allow indefinite-length encodings. // We need to keep track of chunk offsets to convert to // a definite-length encoding once writing is complete. _currentIndefiniteLengthStringRanges ??= new List<(int, int)>(); } EnsureWriteCapacity(1); WriteInitialByte(new CborInitialByte(CborMajorType.TextString, CborAdditionalInfo.IndefiniteLength)); PushDataItem(CborMajorType.TextString, definiteLength: null); } /// <summary>Writes the end of an indefinite-length UTF-8 string (major type 3).</summary> /// <exception cref="InvalidOperationException">The written data is not accepted under the current conformance mode.</exception> public void WriteEndIndefiniteLengthTextString() { PopDataItem(CborMajorType.TextString); AdvanceDataItemCounters(); } // perform an in-place conversion of an indefinite-length encoding into an equivalent definite-length private void PatchIndefiniteLengthString(CborMajorType type) { Debug.Assert(type == CborMajorType.ByteString || type == CborMajorType.TextString); Debug.Assert(_currentIndefiniteLengthStringRanges != null); int initialOffset = _offset; // calculate the definite length of the concatenated string int definiteLength = 0; foreach ((int _, int length) in _currentIndefiniteLengthStringRanges) { definiteLength += length; } Span<byte> buffer = _buffer.AsSpan(); // copy chunks to a temporary buffer byte[] tempBuffer = s_bufferPool.Rent(definiteLength); Span<byte> tempSpan = tempBuffer.AsSpan(0, definiteLength); Span<byte> s = tempSpan; foreach ((int offset, int length) in _currentIndefiniteLengthStringRanges) { buffer.Slice(offset, length).CopyTo(s); s = s.Slice(length); } Debug.Assert(s.IsEmpty); // write back to the original buffer _offset = _frameOffset - 1; WriteUnsignedInteger(type, (ulong)definiteLength); tempSpan.CopyTo(buffer.Slice(_offset, definiteLength)); _offset += definiteLength; // clean up s_bufferPool.Return(tempBuffer); _currentIndefiniteLengthStringRanges.Clear(); buffer.Slice(_offset, initialOffset - _offset).Clear(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace System.Formats.Cbor { public partial class CborWriter { // Implements major type 2,3 encoding per https://tools.ietf.org/html/rfc7049#section-2.1 // keeps track of chunk offsets for written indefinite-length string ranges private List<(int Offset, int Length)>? _currentIndefiniteLengthStringRanges; /// <summary>Writes a buffer as a byte string encoding (major type 2).</summary> /// <param name="value">The value to write.</param> /// <exception cref="ArgumentNullException">The provided value cannot be <see langword="null" />.</exception> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> public void WriteByteString(byte[] value!!) { WriteByteString(value.AsSpan()); } /// <summary>Writes a buffer as a byte string encoding (major type 2).</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> public void WriteByteString(ReadOnlySpan<byte> value) { WriteUnsignedInteger(CborMajorType.ByteString, (ulong)value.Length); EnsureWriteCapacity(value.Length); if (ConvertIndefiniteLengthEncodings && _currentMajorType == CborMajorType.ByteString) { // operation is writing chunk of an indefinite-length string // the string will be converted to a definite-length encoding later, // so we need to record the ranges of each chunk Debug.Assert(_currentIndefiniteLengthStringRanges != null); _currentIndefiniteLengthStringRanges.Add((_offset, value.Length)); } value.CopyTo(_buffer.AsSpan(_offset)); _offset += value.Length; AdvanceDataItemCounters(); } /// <summary>Writes the start of an indefinite-length byte string (major type 2).</summary> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> /// <remarks> /// Pushes a context where definite-length chunks of the same major type can be written. /// In canonical conformance modes, the writer will reject indefinite-length writes unless /// the <see cref="ConvertIndefiniteLengthEncodings" /> flag is enabled. /// </remarks> public void WriteStartIndefiniteLengthByteString() { if (!ConvertIndefiniteLengthEncodings && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new InvalidOperationException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } if (ConvertIndefiniteLengthEncodings) { // Writer does not allow indefinite-length encodings. // We need to keep track of chunk offsets to convert to // a definite-length encoding once writing is complete. _currentIndefiniteLengthStringRanges ??= new List<(int, int)>(); } EnsureWriteCapacity(1); WriteInitialByte(new CborInitialByte(CborMajorType.ByteString, CborAdditionalInfo.IndefiniteLength)); PushDataItem(CborMajorType.ByteString, definiteLength: null); } /// <summary>Writes the end of an indefinite-length byte string (major type 2).</summary> /// <exception cref="InvalidOperationException">The written data is not accepted under the current conformance mode.</exception> public void WriteEndIndefiniteLengthByteString() { PopDataItem(CborMajorType.ByteString); AdvanceDataItemCounters(); } /// <summary>Writes a buffer as a UTF-8 string encoding (major type 3).</summary> /// <param name="value">The value to write.</param> /// <exception cref="ArgumentNullException">The provided value cannot be <see langword="null" />.</exception> /// <exception cref="ArgumentException">The supplied string is not a valid UTF-8 encoding, which is not permitted under the current conformance mode.</exception> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> public void WriteTextString(string value!!) { WriteTextString(value.AsSpan()); } /// <summary>Writes a buffer as a UTF-8 string encoding (major type 3).</summary> /// <param name="value">The value to write.</param> /// <exception cref="ArgumentException">The supplied string is not a valid UTF-8 encoding, which is not permitted under the current conformance mode.</exception> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> public void WriteTextString(ReadOnlySpan<char> value) { Encoding utf8Encoding = CborConformanceModeHelpers.GetUtf8Encoding(ConformanceMode); int length; try { length = CborHelpers.GetByteCount(utf8Encoding, value); } catch (EncoderFallbackException e) { throw new ArgumentException(SR.Cbor_Writer_InvalidUtf8String, e); } WriteUnsignedInteger(CborMajorType.TextString, (ulong)length); EnsureWriteCapacity(length); if (ConvertIndefiniteLengthEncodings && _currentMajorType == CborMajorType.TextString) { // operation is writing chunk of an indefinite-length string // the string will be converted to a definite-length encoding later, // so we need to record the ranges of each chunk Debug.Assert(_currentIndefiniteLengthStringRanges != null); _currentIndefiniteLengthStringRanges.Add((_offset, value.Length)); } CborHelpers.GetBytes(utf8Encoding, value, _buffer.AsSpan(_offset, length)); _offset += length; AdvanceDataItemCounters(); } /// <summary>Writes the start of an indefinite-length UTF-8 string (major type 3).</summary> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> /// <remarks> /// Pushes a context where definite-length chunks of the same major type can be written. /// In canonical conformance modes, the writer will reject indefinite-length writes unless /// the <see cref="ConvertIndefiniteLengthEncodings" /> flag is enabled. /// </remarks> public void WriteStartIndefiniteLengthTextString() { if (!ConvertIndefiniteLengthEncodings && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new InvalidOperationException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } if (ConvertIndefiniteLengthEncodings) { // Writer does not allow indefinite-length encodings. // We need to keep track of chunk offsets to convert to // a definite-length encoding once writing is complete. _currentIndefiniteLengthStringRanges ??= new List<(int, int)>(); } EnsureWriteCapacity(1); WriteInitialByte(new CborInitialByte(CborMajorType.TextString, CborAdditionalInfo.IndefiniteLength)); PushDataItem(CborMajorType.TextString, definiteLength: null); } /// <summary>Writes the end of an indefinite-length UTF-8 string (major type 3).</summary> /// <exception cref="InvalidOperationException">The written data is not accepted under the current conformance mode.</exception> public void WriteEndIndefiniteLengthTextString() { PopDataItem(CborMajorType.TextString); AdvanceDataItemCounters(); } // perform an in-place conversion of an indefinite-length encoding into an equivalent definite-length private void PatchIndefiniteLengthString(CborMajorType type) { Debug.Assert(type == CborMajorType.ByteString || type == CborMajorType.TextString); Debug.Assert(_currentIndefiniteLengthStringRanges != null); int initialOffset = _offset; // calculate the definite length of the concatenated string int definiteLength = 0; foreach ((int _, int length) in _currentIndefiniteLengthStringRanges) { definiteLength += length; } Span<byte> buffer = _buffer.AsSpan(); // copy chunks to a temporary buffer byte[] tempBuffer = s_bufferPool.Rent(definiteLength); Span<byte> tempSpan = tempBuffer.AsSpan(0, definiteLength); Span<byte> s = tempSpan; foreach ((int offset, int length) in _currentIndefiniteLengthStringRanges) { buffer.Slice(offset, length).CopyTo(s); s = s.Slice(length); } Debug.Assert(s.IsEmpty); // write back to the original buffer _offset = _frameOffset - 1; WriteUnsignedInteger(type, (ulong)definiteLength); tempSpan.CopyTo(buffer.Slice(_offset, definiteLength)); _offset += definiteLength; // clean up s_bufferPool.Return(tempBuffer); _currentIndefiniteLengthStringRanges.Clear(); buffer.Slice(_offset, initialOffset - _offset).Clear(); } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.Tag.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Numerics; namespace System.Formats.Cbor { public partial class CborWriter { /// <summary>Assign a semantic tag (major type 6) to the next data item.</summary> /// <param name="tag">The value to write.</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> [CLSCompliant(false)] public void WriteTag(CborTag tag) { if (!CborConformanceModeHelpers.AllowsTags(ConformanceMode)) { throw new InvalidOperationException(SR.Format(SR.Cbor_ConformanceMode_TagsNotSupported, ConformanceMode)); } WriteUnsignedInteger(CborMajorType.Tag, (ulong)tag); _isTagContext = true; } /// <summary>Writes the provided value as a tagged date/time string, as described in RFC7049 section 2.4.1.</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteDateTimeOffset(DateTimeOffset value) { string dateString = value.Offset == TimeSpan.Zero ? value.UtcDateTime.ToString(Rfc3339FormatString) : // prefer 'Z' over '+00:00' value.ToString(Rfc3339FormatString); WriteTag(CborTag.DateTimeString); WriteTextString(dateString); } /// <summary>Writes a unix time in seconds as a tagged date/time value, as described in RFC7049 section 2.4.1.</summary> /// <param name="seconds">The value to write.</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteUnixTimeSeconds(long seconds) { WriteTag(CborTag.UnixTimeSeconds); WriteInt64(seconds); } /// <summary>Writes a unix time in seconds as a tagged date/time value, as described in RFC7049 section 2.4.1.</summary> /// <param name="seconds">The value to write.</param> /// <exception cref="ArgumentException">The <paramref name="seconds" /> parameter cannot be infinite or NaN</exception> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteUnixTimeSeconds(double seconds) { if (double.IsInfinity(seconds) || double.IsNaN(seconds)) { throw new ArgumentException(SR.Cbor_Writer_ValueCannotBeInfiniteOrNaN, nameof(seconds)); } WriteTag(CborTag.UnixTimeSeconds); WriteDouble(seconds); } /// <summary>Writes the provided value as a tagged bignum encoding, as described in RFC7049 section 2.4.2.</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteBigInteger(BigInteger value) { bool isUnsigned = value.Sign >= 0; BigInteger unsignedValue = isUnsigned ? value : -1 - value; byte[] unsignedBigEndianEncoding = CborHelpers.CreateUnsignedBigEndianBytesFromBigInteger(unsignedValue); WriteTag(isUnsigned ? CborTag.UnsignedBigNum : CborTag.NegativeBigNum); WriteByteString(unsignedBigEndianEncoding); } /// <summary>Writes the provided value value as a tagged decimal fraction encoding, as described in RFC7049 section 2.4.3</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException">Writing a new value exceeds the definite length of the parent data item. /// -or- /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode.</exception> public void WriteDecimal(decimal value) { DecimalHelpers.Deconstruct(value, out decimal mantissa, out byte scale); WriteTag(CborTag.DecimalFraction); WriteStartArray(2); WriteInt64(-(long)scale); if (-1m - ulong.MinValue <= mantissa && mantissa <= ulong.MaxValue) { if (mantissa >= 0m) { WriteUInt64((ulong)mantissa); } else { WriteCborNegativeIntegerRepresentation((ulong)(-1m - mantissa)); } } else { // the mantissa can also be a BigNum WriteBigInteger((BigInteger)mantissa); } WriteEndArray(); } internal const string Rfc3339FormatString = "yyyy-MM-ddTHH:mm:ss.FFFFFFFK"; internal static class DecimalHelpers { private const int SignMask = unchecked((int)0x80000000); private const int ScaleMask = 0x00ff0000; private const int ScaleShift = 16; private const int ExponentUpperBound = 28; /// deconstructs a decimal value into its signed integral component and negative base-10 exponent public static void Deconstruct(decimal value, out decimal mantissa, out byte scale) { Span<int> buf = stackalloc int[4]; CborHelpers.GetBitsFromDecimal(value, buf); int flags = buf[3]; bool isNegative = (flags & SignMask) == SignMask; mantissa = new decimal(lo: buf[0], mid: buf[1], hi: buf[2], isNegative: isNegative, scale: 0); scale = (byte)((flags & ScaleMask) >> ScaleShift); } /// reconstructs a decimal value out of a signed integral component and a negative base-10 exponent private static decimal ReconstructFromNegativeScale(decimal mantissa, byte scale) { Span<int> buf = stackalloc int[4]; CborHelpers.GetBitsFromDecimal(mantissa, buf); int flags = buf[3]; bool isNegative = (flags & SignMask) == SignMask; Debug.Assert((flags & ScaleMask) == 0, "mantissa argument should be integral."); return new decimal(lo: buf[0], mid: buf[1], hi: buf[2], isNegative: isNegative, scale: scale); } public static decimal Reconstruct(decimal mantissa, long exponent) { if (mantissa == 0) { return mantissa; } else if (exponent > ExponentUpperBound) { throw new OverflowException(SR.Cbor_Writer_DecimalOverflow); } else if (exponent >= 0) { // for positive exponents attempt to compute a decimal // representation, with risk of throwing OverflowException for (; exponent >= 5; exponent -= 5) { mantissa *= 100_000m; } switch (exponent) { case 0: return mantissa; case 1: return mantissa * 10m; case 2: return mantissa * 100m; case 3: return mantissa * 1000m; case 4: return mantissa * 10000m; default: Debug.Fail("Unreachable code in decimal exponentiation logic"); throw new Exception(); } } else if (exponent >= -ExponentUpperBound) { // exponent falls within range of decimal normal-form representation return ReconstructFromNegativeScale(mantissa, (byte)(-exponent)); } else { throw new OverflowException(SR.Cbor_Writer_DecimalOverflow); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Numerics; namespace System.Formats.Cbor { public partial class CborWriter { /// <summary>Assign a semantic tag (major type 6) to the next data item.</summary> /// <param name="tag">The value to write.</param> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> [CLSCompliant(false)] public void WriteTag(CborTag tag) { if (!CborConformanceModeHelpers.AllowsTags(ConformanceMode)) { throw new InvalidOperationException(SR.Format(SR.Cbor_ConformanceMode_TagsNotSupported, ConformanceMode)); } WriteUnsignedInteger(CborMajorType.Tag, (ulong)tag); _isTagContext = true; } /// <summary>Writes the provided value as a tagged date/time string, as described in RFC7049 section 2.4.1.</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> public void WriteDateTimeOffset(DateTimeOffset value) { string dateString = value.Offset == TimeSpan.Zero ? value.UtcDateTime.ToString(Rfc3339FormatString) : // prefer 'Z' over '+00:00' value.ToString(Rfc3339FormatString); WriteTag(CborTag.DateTimeString); WriteTextString(dateString); } /// <summary>Writes a unix time in seconds as a tagged date/time value, as described in RFC7049 section 2.4.1.</summary> /// <param name="seconds">The value to write.</param> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> public void WriteUnixTimeSeconds(long seconds) { WriteTag(CborTag.UnixTimeSeconds); WriteInt64(seconds); } /// <summary>Writes a unix time in seconds as a tagged date/time value, as described in RFC7049 section 2.4.1.</summary> /// <param name="seconds">The value to write.</param> /// <exception cref="ArgumentException">The <paramref name="seconds" /> parameter cannot be infinite or NaN.</exception> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> public void WriteUnixTimeSeconds(double seconds) { if (double.IsInfinity(seconds) || double.IsNaN(seconds)) { throw new ArgumentException(SR.Cbor_Writer_ValueCannotBeInfiniteOrNaN, nameof(seconds)); } WriteTag(CborTag.UnixTimeSeconds); WriteDouble(seconds); } /// <summary>Writes the provided value as a tagged bignum encoding, as described in RFC7049 section 2.4.2.</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> public void WriteBigInteger(BigInteger value) { bool isUnsigned = value.Sign >= 0; BigInteger unsignedValue = isUnsigned ? value : -1 - value; byte[] unsignedBigEndianEncoding = CborHelpers.CreateUnsignedBigEndianBytesFromBigInteger(unsignedValue); WriteTag(isUnsigned ? CborTag.UnsignedBigNum : CborTag.NegativeBigNum); WriteByteString(unsignedBigEndianEncoding); } /// <summary>Writes the provided value value as a tagged decimal fraction encoding, as described in RFC7049 section 2.4.3</summary> /// <param name="value">The value to write.</param> /// <exception cref="InvalidOperationException"><para>Writing a new value exceeds the definite length of the parent data item.</para> /// <para>-or-</para> /// <para>The major type of the encoded value is not permitted in the parent data item.</para> /// <para>-or-</para> /// <para>The written data is not accepted under the current conformance mode.</para></exception> public void WriteDecimal(decimal value) { DecimalHelpers.Deconstruct(value, out decimal mantissa, out byte scale); WriteTag(CborTag.DecimalFraction); WriteStartArray(2); WriteInt64(-(long)scale); if (-1m - ulong.MinValue <= mantissa && mantissa <= ulong.MaxValue) { if (mantissa >= 0m) { WriteUInt64((ulong)mantissa); } else { WriteCborNegativeIntegerRepresentation((ulong)(-1m - mantissa)); } } else { // the mantissa can also be a BigNum WriteBigInteger((BigInteger)mantissa); } WriteEndArray(); } internal const string Rfc3339FormatString = "yyyy-MM-ddTHH:mm:ss.FFFFFFFK"; internal static class DecimalHelpers { private const int SignMask = unchecked((int)0x80000000); private const int ScaleMask = 0x00ff0000; private const int ScaleShift = 16; private const int ExponentUpperBound = 28; /// deconstructs a decimal value into its signed integral component and negative base-10 exponent public static void Deconstruct(decimal value, out decimal mantissa, out byte scale) { Span<int> buf = stackalloc int[4]; CborHelpers.GetBitsFromDecimal(value, buf); int flags = buf[3]; bool isNegative = (flags & SignMask) == SignMask; mantissa = new decimal(lo: buf[0], mid: buf[1], hi: buf[2], isNegative: isNegative, scale: 0); scale = (byte)((flags & ScaleMask) >> ScaleShift); } /// reconstructs a decimal value out of a signed integral component and a negative base-10 exponent private static decimal ReconstructFromNegativeScale(decimal mantissa, byte scale) { Span<int> buf = stackalloc int[4]; CborHelpers.GetBitsFromDecimal(mantissa, buf); int flags = buf[3]; bool isNegative = (flags & SignMask) == SignMask; Debug.Assert((flags & ScaleMask) == 0, "mantissa argument should be integral."); return new decimal(lo: buf[0], mid: buf[1], hi: buf[2], isNegative: isNegative, scale: scale); } public static decimal Reconstruct(decimal mantissa, long exponent) { if (mantissa == 0) { return mantissa; } else if (exponent > ExponentUpperBound) { throw new OverflowException(SR.Cbor_Writer_DecimalOverflow); } else if (exponent >= 0) { // for positive exponents attempt to compute a decimal // representation, with risk of throwing OverflowException for (; exponent >= 5; exponent -= 5) { mantissa *= 100_000m; } switch (exponent) { case 0: return mantissa; case 1: return mantissa * 10m; case 2: return mantissa * 100m; case 3: return mantissa * 1000m; case 4: return mantissa * 10000m; default: Debug.Fail("Unreachable code in decimal exponentiation logic"); throw new Exception(); } } else if (exponent >= -ExponentUpperBound) { // exponent falls within range of decimal normal-form representation return ReconstructFromNegativeScale(mantissa, (byte)(-exponent)); } else { throw new OverflowException(SR.Cbor_Writer_DecimalOverflow); } } } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Formats.Cbor { /// <summary>A writer for Concise Binary Object Representation (CBOR) encoded data.</summary> public partial class CborWriter { private static readonly ArrayPool<byte> s_bufferPool = ArrayPool<byte>.Create(); private byte[] _buffer = null!; private int _offset; private Stack<StackFrame>? _nestedDataItems; private CborMajorType? _currentMajorType; // major type of the current data item context private int? _definiteLength; // predetermined definite-length of current data item context private int _itemsWritten; // number of items written in the current context private int _frameOffset; // buffer offset particular to the current data item context private bool _isTagContext; // true if writer is expecting a tagged value // Map-specific book-keeping private int? _currentKeyOffset; // offset for the current key encoding private int? _currentValueOffset; // offset for the current value encoding private bool _keysRequireSorting; // tracks whether key/value pair encodings need to be sorted private List<KeyValuePairEncodingRange>? _keyValuePairEncodingRanges; // all key/value pair encoding ranges private HashSet<(int Offset, int Length)>? _keyEncodingRanges; // all key encoding ranges up to encoding equality /// <summary>Gets the conformance mode used by this writer.</summary> /// <value>One of the enumeration values that represent the conformance mode used by this writer.</value> public CborConformanceMode ConformanceMode { get; } /// <summary>Gets a value that indicates whether the writer automatically converts indefinite-length encodings into definite-length equivalents.</summary> /// <value><see langword="true" /> if the writer automatically converts indefinite-length encodings into definite-length equivalents; otherwise, <see langword="false" />.</value> public bool ConvertIndefiniteLengthEncodings { get; } /// <summary>Gets a value that indicates whether this writer allows multiple root-level CBOR data items.</summary> /// <value><see langword="true" /> if the writer allows multiple root-level CBOR data items; otherwise, <see langword="false" />.</value> public bool AllowMultipleRootLevelValues { get; } /// <summary>Gets the writer's current level of nestedness in the CBOR document.</summary> /// <value>A number that represents the current level of nestedness in the CBOR document.</value> public int CurrentDepth => _nestedDataItems is null ? 0 : _nestedDataItems.Count; /// <summary>Gets the total number of bytes that have been written to the buffer.</summary> /// <value>The total number of bytes that have been written to the buffer.</value> public int BytesWritten => _offset; /// <summary>Declares whether the writer has completed writing a complete root-level CBOR document, or sequence of root-level CBOR documents.</summary> /// <value><see langword="true" /> if the writer has completed writing a complete root-level CBOR document, or sequence of root-level CBOR documents; <see langword="false" /> otherwise.</value> public bool IsWriteCompleted => _currentMajorType is null && _itemsWritten > 0; /// <summary>Initializes a new instance of <see cref="CborWriter" /> class using the specified configuration.</summary> /// <param name="conformanceMode">One of the enumeration values that specifies the guidance on the conformance checks performed on the encoded data. /// Defaults to <see cref="CborConformanceMode.Strict" /> conformance mode.</param> /// <param name="convertIndefiniteLengthEncodings"><see langword="true" /> to enable automatically converting indefinite-length encodings into definite-length equivalents and allow use of indefinite-length write APIs in conformance modes that otherwise do not permit it; otherwise, <see langword="false" /></param> /// <param name="allowMultipleRootLevelValues"><see langword="true" /> to allow multiple root-level values to be written by the writer; otherwise, <see langword="false" />.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="conformanceMode" /> is not a defined <see cref="CborConformanceMode" />.</exception> public CborWriter(CborConformanceMode conformanceMode = CborConformanceMode.Strict, bool convertIndefiniteLengthEncodings = false, bool allowMultipleRootLevelValues = false) { CborConformanceModeHelpers.Validate(conformanceMode); ConformanceMode = conformanceMode; ConvertIndefiniteLengthEncodings = convertIndefiniteLengthEncodings; AllowMultipleRootLevelValues = allowMultipleRootLevelValues; _definiteLength = allowMultipleRootLevelValues ? null : (int?)1; } /// <summary>Resets the writer to have no data, without releasing resources.</summary> public void Reset() { if (_offset > 0) { Array.Clear(_buffer, 0, _offset); _offset = 0; _nestedDataItems?.Clear(); _currentMajorType = null; _definiteLength = null; _itemsWritten = 0; _frameOffset = 0; _isTagContext = false; _currentKeyOffset = null; _currentValueOffset = null; _keysRequireSorting = false; _keyValuePairEncodingRanges?.Clear(); _keyEncodingRanges?.Clear(); } } /// <summary>Writes a single CBOR data item which has already been encoded.</summary> /// <param name="encodedValue">The encoded value to write.</param> /// <exception cref="ArgumentException"><paramref name="encodedValue" /> is not a well-formed CBOR encoding. /// -or- /// <paramref name="encodedValue" /> is not valid under the current conformance mode.</exception> public void WriteEncodedValue(ReadOnlySpan<byte> encodedValue) { ValidateEncoding(encodedValue, ConformanceMode); EnsureWriteCapacity(encodedValue.Length); // even though the encoding might be valid CBOR, it might not be valid within the current writer context. // E.g. we're at the end of a definite-length collection or writing integers in an indefinite-length string. // For this reason we write the initial byte separately and perform the usual validation. CborInitialByte initialByte = new CborInitialByte(encodedValue[0]); WriteInitialByte(initialByte); // now copy any remaining bytes encodedValue = encodedValue.Slice(1); if (!encodedValue.IsEmpty) { encodedValue.CopyTo(_buffer.AsSpan(_offset)); _offset += encodedValue.Length; } AdvanceDataItemCounters(); static unsafe void ValidateEncoding(ReadOnlySpan<byte> encodedValue, CborConformanceMode conformanceMode) { fixed (byte* ptr = &MemoryMarshal.GetReference(encodedValue)) { using var manager = new PointerMemoryManager<byte>(ptr, encodedValue.Length); var reader = new CborReader(manager.Memory, conformanceMode: conformanceMode, allowMultipleRootLevelValues: false); try { reader.SkipValue(disableConformanceModeChecks: false); } catch (CborContentException e) { throw new ArgumentException(SR.Cbor_Writer_PayloadIsNotValidCbor, e); } if (reader.BytesRemaining > 0) { throw new ArgumentException(SR.Cbor_Writer_PayloadIsNotValidCbor); } } } } /// <summary>Returns a new array containing the encoded value.</summary> /// <returns>A precisely-sized array containing the encoded value.</returns> /// <exception cref="InvalidOperationException">The writer does not contain a complete CBOR value or sequence of root-level values.</exception> public byte[] Encode() => GetSpanEncoding().ToArray(); /// <summary>Writes the encoded representation of the data to <paramref name="destination" />.</summary> /// <param name="destination">The buffer in which to write.</param> /// <returns>The number of bytes written to <paramref name="destination" />.</returns> /// <exception cref="InvalidOperationException">The writer does not contain a complete CBOR value or sequence of root-level values.</exception> /// <exception cref="ArgumentException">The destination buffer is not large enough to hold the encoded value.</exception> public int Encode(Span<byte> destination) { ReadOnlySpan<byte> encoding = GetSpanEncoding(); if (encoding.Length > destination.Length) { throw new ArgumentException(SR.Argument_EncodeDestinationTooSmall, nameof(destination)); } encoding.CopyTo(destination); return encoding.Length; } /// <summary>Attempts to write the encoded representation of the data to <paramref name="destination" />.</summary> /// <param name="destination">The buffer in which to write.</param> /// <param name="bytesWritten">When this method returns, contains the number of bytes written to <paramref name="destination" />.</param> /// <returns><see langword="true" /> if the encode succeeded, <see langword="false" /> if <paramref name="destination" /> is too small.</returns> /// <exception cref="InvalidOperationException">The writer does not contain a complete CBOR value or sequence of root-level values.</exception> public bool TryEncode(Span<byte> destination, out int bytesWritten) { ReadOnlySpan<byte> encoding = GetSpanEncoding(); if (encoding.Length > destination.Length) { bytesWritten = 0; return false; } encoding.CopyTo(destination); bytesWritten = encoding.Length; return true; } private ReadOnlySpan<byte> GetSpanEncoding() { if (!IsWriteCompleted) { throw new InvalidOperationException(SR.Cbor_Writer_IncompleteCborDocument); } return new ReadOnlySpan<byte>(_buffer, 0, _offset); } private void EnsureWriteCapacity(int pendingCount) { if (pendingCount < 0) { throw new OverflowException(); } if (_buffer is null || _buffer.Length - _offset < pendingCount) { const int BlockSize = 1024; int blocks = checked(_offset + pendingCount + (BlockSize - 1)) / BlockSize; Array.Resize(ref _buffer, BlockSize * blocks); } } private void PushDataItem(CborMajorType newMajorType, int? definiteLength) { _nestedDataItems ??= new Stack<StackFrame>(); var frame = new StackFrame( type: _currentMajorType, frameOffset: _frameOffset, definiteLength: _definiteLength, itemsWritten: _itemsWritten, currentKeyOffset: _currentKeyOffset, currentValueOffset: _currentValueOffset, keysRequireSorting: _keysRequireSorting, keyValuePairEncodingRanges: _keyValuePairEncodingRanges, keyEncodingRanges: _keyEncodingRanges ); _nestedDataItems.Push(frame); _currentMajorType = newMajorType; _frameOffset = _offset; _definiteLength = definiteLength; _itemsWritten = 0; _currentKeyOffset = null; _currentValueOffset = null; _keysRequireSorting = false; _keyEncodingRanges = null; _keyValuePairEncodingRanges = null; _isTagContext = false; } private void PopDataItem(CborMajorType typeToPop) { // Validate that the pop operation can be performed if (typeToPop != _currentMajorType) { if (_currentMajorType.HasValue) { throw new InvalidOperationException(SR.Format(SR.Cbor_PopMajorTypeMismatch, (int)_currentMajorType)); } else { throw new InvalidOperationException(SR.Cbor_Reader_IsAtRootContext); } } Debug.Assert(_nestedDataItems?.Count > 0); // implied by previous check if (_isTagContext) { // writer expecting value after a tag data item, cannot pop the current context throw new InvalidOperationException(SR.Format(SR.Cbor_PopMajorTypeMismatch, (int)CborMajorType.Tag)); } if (_definiteLength - _itemsWritten > 0) { throw new InvalidOperationException(SR.Cbor_NotAtEndOfDefiniteLengthDataItem); } // Perform encoding fixups that require the current context and must be done before popping // NB map key sorting must happen _before_ indefinite-length patching if (typeToPop == CborMajorType.Map) { CompleteMapWrite(); } if (_definiteLength == null) { CompleteIndefiniteLengthWrite(typeToPop); } // pop writer state StackFrame frame = _nestedDataItems.Pop(); _currentMajorType = frame.MajorType; _frameOffset = frame.FrameOffset; _definiteLength = frame.DefiniteLength; _itemsWritten = frame.ItemsWritten; _currentKeyOffset = frame.CurrentKeyOffset; _currentValueOffset = frame.CurrentValueOffset; _keysRequireSorting = frame.KeysRequireSorting; _keyValuePairEncodingRanges = frame.KeyValuePairEncodingRanges; _keyEncodingRanges = frame.KeyEncodingRanges; } // Advance writer state after a data item has been written to the buffer private void AdvanceDataItemCounters() { if (_currentMajorType == CborMajorType.Map) { if (_itemsWritten % 2 == 0) { HandleMapKeyWritten(); } else { HandleMapValueWritten(); } } _itemsWritten++; _isTagContext = false; } private void WriteInitialByte(CborInitialByte initialByte) { if (_definiteLength - _itemsWritten == 0) { throw new InvalidOperationException(SR.Cbor_Writer_DefiniteLengthExceeded); } switch (_currentMajorType) { case CborMajorType.ByteString: case CborMajorType.TextString: // Indefinite-length string contexts allow two possible data items: // 1) Definite-length string chunks of the same major type OR // 2) a break byte denoting the end of the indefinite-length string context. // NB the second check is not needed here, as we use a separate mechanism to append the break byte if (initialByte.MajorType != _currentMajorType || initialByte.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { throw new InvalidOperationException(SR.Cbor_Writer_CannotNestDataItemsInIndefiniteLengthStrings); } break; } _buffer[_offset++] = initialByte.InitialByte; } private void CompleteIndefiniteLengthWrite(CborMajorType type) { Debug.Assert(_definiteLength == null); if (ConvertIndefiniteLengthEncodings) { // indefinite-length not allowed, convert the encoding into definite-length switch (type) { case CborMajorType.ByteString: case CborMajorType.TextString: PatchIndefiniteLengthString(type); break; case CborMajorType.Array: PatchIndefiniteLengthCollection(CborMajorType.Array, _itemsWritten); break; case CborMajorType.Map: Debug.Assert(_itemsWritten % 2 == 0); PatchIndefiniteLengthCollection(CborMajorType.Map, _itemsWritten / 2); break; default: Debug.Fail("Invalid CBOR major type pushed to stack."); throw new Exception(); } } else { // using indefinite-length encoding, append a break byte to the existing encoding EnsureWriteCapacity(1); _buffer[_offset++] = CborInitialByte.IndefiniteLengthBreakByte; } } private readonly struct StackFrame { public StackFrame( CborMajorType? type, int frameOffset, int? definiteLength, int itemsWritten, int? currentKeyOffset, int? currentValueOffset, bool keysRequireSorting, List<KeyValuePairEncodingRange>? keyValuePairEncodingRanges, HashSet<(int Offset, int Length)>? keyEncodingRanges) { MajorType = type; FrameOffset = frameOffset; DefiniteLength = definiteLength; ItemsWritten = itemsWritten; CurrentKeyOffset = currentKeyOffset; CurrentValueOffset = currentValueOffset; KeysRequireSorting = keysRequireSorting; KeyValuePairEncodingRanges = keyValuePairEncodingRanges; KeyEncodingRanges = keyEncodingRanges; } public CborMajorType? MajorType { get; } public int FrameOffset { get; } public int? DefiniteLength { get; } public int ItemsWritten { get; } public int? CurrentKeyOffset { get; } public int? CurrentValueOffset { get; } public bool KeysRequireSorting { get; } public List<KeyValuePairEncodingRange>? KeyValuePairEncodingRanges { get; } public HashSet<(int Offset, int Length)>? KeyEncodingRanges { 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.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Formats.Cbor { /// <summary>A writer for Concise Binary Object Representation (CBOR) encoded data.</summary> public partial class CborWriter { private static readonly ArrayPool<byte> s_bufferPool = ArrayPool<byte>.Create(); private byte[] _buffer = null!; private int _offset; private Stack<StackFrame>? _nestedDataItems; private CborMajorType? _currentMajorType; // major type of the current data item context private int? _definiteLength; // predetermined definite-length of current data item context private int _itemsWritten; // number of items written in the current context private int _frameOffset; // buffer offset particular to the current data item context private bool _isTagContext; // true if writer is expecting a tagged value // Map-specific book-keeping private int? _currentKeyOffset; // offset for the current key encoding private int? _currentValueOffset; // offset for the current value encoding private bool _keysRequireSorting; // tracks whether key/value pair encodings need to be sorted private List<KeyValuePairEncodingRange>? _keyValuePairEncodingRanges; // all key/value pair encoding ranges private HashSet<(int Offset, int Length)>? _keyEncodingRanges; // all key encoding ranges up to encoding equality /// <summary>Gets the conformance mode used by this writer.</summary> /// <value>One of the enumeration values that represent the conformance mode used by this writer.</value> public CborConformanceMode ConformanceMode { get; } /// <summary>Gets a value that indicates whether the writer automatically converts indefinite-length encodings into definite-length equivalents.</summary> /// <value><see langword="true" /> if the writer automatically converts indefinite-length encodings into definite-length equivalents; otherwise, <see langword="false" />.</value> public bool ConvertIndefiniteLengthEncodings { get; } /// <summary>Gets a value that indicates whether this writer allows multiple root-level CBOR data items.</summary> /// <value><see langword="true" /> if the writer allows multiple root-level CBOR data items; otherwise, <see langword="false" />.</value> public bool AllowMultipleRootLevelValues { get; } /// <summary>Gets the writer's current level of nestedness in the CBOR document.</summary> /// <value>A number that represents the current level of nestedness in the CBOR document.</value> public int CurrentDepth => _nestedDataItems is null ? 0 : _nestedDataItems.Count; /// <summary>Gets the total number of bytes that have been written to the buffer.</summary> /// <value>The total number of bytes that have been written to the buffer.</value> public int BytesWritten => _offset; /// <summary>Declares whether the writer has completed writing a complete root-level CBOR document, or sequence of root-level CBOR documents.</summary> /// <value><see langword="true" /> if the writer has completed writing a complete root-level CBOR document, or sequence of root-level CBOR documents; <see langword="false" /> otherwise.</value> public bool IsWriteCompleted => _currentMajorType is null && _itemsWritten > 0; /// <summary>Initializes a new instance of <see cref="CborWriter" /> class using the specified configuration.</summary> /// <param name="conformanceMode">One of the enumeration values that specifies the guidance on the conformance checks performed on the encoded data. /// Defaults to <see cref="CborConformanceMode.Strict" /> conformance mode.</param> /// <param name="convertIndefiniteLengthEncodings"><see langword="true" /> to enable automatically converting indefinite-length encodings into definite-length equivalents and allow use of indefinite-length write APIs in conformance modes that otherwise do not permit it; otherwise, <see langword="false" />.</param> /// <param name="allowMultipleRootLevelValues"><see langword="true" /> to allow multiple root-level values to be written by the writer; otherwise, <see langword="false" />.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="conformanceMode" /> is not a defined <see cref="CborConformanceMode" />.</exception> public CborWriter(CborConformanceMode conformanceMode = CborConformanceMode.Strict, bool convertIndefiniteLengthEncodings = false, bool allowMultipleRootLevelValues = false) { CborConformanceModeHelpers.Validate(conformanceMode); ConformanceMode = conformanceMode; ConvertIndefiniteLengthEncodings = convertIndefiniteLengthEncodings; AllowMultipleRootLevelValues = allowMultipleRootLevelValues; _definiteLength = allowMultipleRootLevelValues ? null : (int?)1; } /// <summary>Resets the writer to have no data, without releasing resources.</summary> public void Reset() { if (_offset > 0) { Array.Clear(_buffer, 0, _offset); _offset = 0; _nestedDataItems?.Clear(); _currentMajorType = null; _definiteLength = null; _itemsWritten = 0; _frameOffset = 0; _isTagContext = false; _currentKeyOffset = null; _currentValueOffset = null; _keysRequireSorting = false; _keyValuePairEncodingRanges?.Clear(); _keyEncodingRanges?.Clear(); } } /// <summary>Writes a single CBOR data item which has already been encoded.</summary> /// <param name="encodedValue">The encoded value to write.</param> /// <exception cref="ArgumentException"><para><paramref name="encodedValue" /> is not a well-formed CBOR encoding.</para> /// <para>-or-</para> /// <para><paramref name="encodedValue" /> is not valid under the current conformance mode.</para></exception> public void WriteEncodedValue(ReadOnlySpan<byte> encodedValue) { ValidateEncoding(encodedValue, ConformanceMode); EnsureWriteCapacity(encodedValue.Length); // even though the encoding might be valid CBOR, it might not be valid within the current writer context. // E.g. we're at the end of a definite-length collection or writing integers in an indefinite-length string. // For this reason we write the initial byte separately and perform the usual validation. CborInitialByte initialByte = new CborInitialByte(encodedValue[0]); WriteInitialByte(initialByte); // now copy any remaining bytes encodedValue = encodedValue.Slice(1); if (!encodedValue.IsEmpty) { encodedValue.CopyTo(_buffer.AsSpan(_offset)); _offset += encodedValue.Length; } AdvanceDataItemCounters(); static unsafe void ValidateEncoding(ReadOnlySpan<byte> encodedValue, CborConformanceMode conformanceMode) { fixed (byte* ptr = &MemoryMarshal.GetReference(encodedValue)) { using var manager = new PointerMemoryManager<byte>(ptr, encodedValue.Length); var reader = new CborReader(manager.Memory, conformanceMode: conformanceMode, allowMultipleRootLevelValues: false); try { reader.SkipValue(disableConformanceModeChecks: false); } catch (CborContentException e) { throw new ArgumentException(SR.Cbor_Writer_PayloadIsNotValidCbor, e); } if (reader.BytesRemaining > 0) { throw new ArgumentException(SR.Cbor_Writer_PayloadIsNotValidCbor); } } } } /// <summary>Returns a new array containing the encoded value.</summary> /// <returns>A precisely-sized array containing the encoded value.</returns> /// <exception cref="InvalidOperationException">The writer does not contain a complete CBOR value or sequence of root-level values.</exception> public byte[] Encode() => GetSpanEncoding().ToArray(); /// <summary>Writes the encoded representation of the data to <paramref name="destination" />.</summary> /// <param name="destination">The buffer in which to write.</param> /// <returns>The number of bytes written to <paramref name="destination" />.</returns> /// <exception cref="InvalidOperationException">The writer does not contain a complete CBOR value or sequence of root-level values.</exception> /// <exception cref="ArgumentException">The destination buffer is not large enough to hold the encoded value.</exception> public int Encode(Span<byte> destination) { ReadOnlySpan<byte> encoding = GetSpanEncoding(); if (encoding.Length > destination.Length) { throw new ArgumentException(SR.Argument_EncodeDestinationTooSmall, nameof(destination)); } encoding.CopyTo(destination); return encoding.Length; } /// <summary>Attempts to write the encoded representation of the data to <paramref name="destination" />.</summary> /// <param name="destination">The buffer in which to write.</param> /// <param name="bytesWritten">When this method returns, contains the number of bytes written to <paramref name="destination" />.</param> /// <returns><see langword="true" /> if the encode succeeded, <see langword="false" /> if <paramref name="destination" /> is too small.</returns> /// <exception cref="InvalidOperationException">The writer does not contain a complete CBOR value or sequence of root-level values.</exception> public bool TryEncode(Span<byte> destination, out int bytesWritten) { ReadOnlySpan<byte> encoding = GetSpanEncoding(); if (encoding.Length > destination.Length) { bytesWritten = 0; return false; } encoding.CopyTo(destination); bytesWritten = encoding.Length; return true; } private ReadOnlySpan<byte> GetSpanEncoding() { if (!IsWriteCompleted) { throw new InvalidOperationException(SR.Cbor_Writer_IncompleteCborDocument); } return new ReadOnlySpan<byte>(_buffer, 0, _offset); } private void EnsureWriteCapacity(int pendingCount) { if (pendingCount < 0) { throw new OverflowException(); } if (_buffer is null || _buffer.Length - _offset < pendingCount) { const int BlockSize = 1024; int blocks = checked(_offset + pendingCount + (BlockSize - 1)) / BlockSize; Array.Resize(ref _buffer, BlockSize * blocks); } } private void PushDataItem(CborMajorType newMajorType, int? definiteLength) { _nestedDataItems ??= new Stack<StackFrame>(); var frame = new StackFrame( type: _currentMajorType, frameOffset: _frameOffset, definiteLength: _definiteLength, itemsWritten: _itemsWritten, currentKeyOffset: _currentKeyOffset, currentValueOffset: _currentValueOffset, keysRequireSorting: _keysRequireSorting, keyValuePairEncodingRanges: _keyValuePairEncodingRanges, keyEncodingRanges: _keyEncodingRanges ); _nestedDataItems.Push(frame); _currentMajorType = newMajorType; _frameOffset = _offset; _definiteLength = definiteLength; _itemsWritten = 0; _currentKeyOffset = null; _currentValueOffset = null; _keysRequireSorting = false; _keyEncodingRanges = null; _keyValuePairEncodingRanges = null; _isTagContext = false; } private void PopDataItem(CborMajorType typeToPop) { // Validate that the pop operation can be performed if (typeToPop != _currentMajorType) { if (_currentMajorType.HasValue) { throw new InvalidOperationException(SR.Format(SR.Cbor_PopMajorTypeMismatch, (int)_currentMajorType)); } else { throw new InvalidOperationException(SR.Cbor_Reader_IsAtRootContext); } } Debug.Assert(_nestedDataItems?.Count > 0); // implied by previous check if (_isTagContext) { // writer expecting value after a tag data item, cannot pop the current context throw new InvalidOperationException(SR.Format(SR.Cbor_PopMajorTypeMismatch, (int)CborMajorType.Tag)); } if (_definiteLength - _itemsWritten > 0) { throw new InvalidOperationException(SR.Cbor_NotAtEndOfDefiniteLengthDataItem); } // Perform encoding fixups that require the current context and must be done before popping // NB map key sorting must happen _before_ indefinite-length patching if (typeToPop == CborMajorType.Map) { CompleteMapWrite(); } if (_definiteLength == null) { CompleteIndefiniteLengthWrite(typeToPop); } // pop writer state StackFrame frame = _nestedDataItems.Pop(); _currentMajorType = frame.MajorType; _frameOffset = frame.FrameOffset; _definiteLength = frame.DefiniteLength; _itemsWritten = frame.ItemsWritten; _currentKeyOffset = frame.CurrentKeyOffset; _currentValueOffset = frame.CurrentValueOffset; _keysRequireSorting = frame.KeysRequireSorting; _keyValuePairEncodingRanges = frame.KeyValuePairEncodingRanges; _keyEncodingRanges = frame.KeyEncodingRanges; } // Advance writer state after a data item has been written to the buffer private void AdvanceDataItemCounters() { if (_currentMajorType == CborMajorType.Map) { if (_itemsWritten % 2 == 0) { HandleMapKeyWritten(); } else { HandleMapValueWritten(); } } _itemsWritten++; _isTagContext = false; } private void WriteInitialByte(CborInitialByte initialByte) { if (_definiteLength - _itemsWritten == 0) { throw new InvalidOperationException(SR.Cbor_Writer_DefiniteLengthExceeded); } switch (_currentMajorType) { case CborMajorType.ByteString: case CborMajorType.TextString: // Indefinite-length string contexts allow two possible data items: // 1) Definite-length string chunks of the same major type OR // 2) a break byte denoting the end of the indefinite-length string context. // NB the second check is not needed here, as we use a separate mechanism to append the break byte if (initialByte.MajorType != _currentMajorType || initialByte.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { throw new InvalidOperationException(SR.Cbor_Writer_CannotNestDataItemsInIndefiniteLengthStrings); } break; } _buffer[_offset++] = initialByte.InitialByte; } private void CompleteIndefiniteLengthWrite(CborMajorType type) { Debug.Assert(_definiteLength == null); if (ConvertIndefiniteLengthEncodings) { // indefinite-length not allowed, convert the encoding into definite-length switch (type) { case CborMajorType.ByteString: case CborMajorType.TextString: PatchIndefiniteLengthString(type); break; case CborMajorType.Array: PatchIndefiniteLengthCollection(CborMajorType.Array, _itemsWritten); break; case CborMajorType.Map: Debug.Assert(_itemsWritten % 2 == 0); PatchIndefiniteLengthCollection(CborMajorType.Map, _itemsWritten / 2); break; default: Debug.Fail("Invalid CBOR major type pushed to stack."); throw new Exception(); } } else { // using indefinite-length encoding, append a break byte to the existing encoding EnsureWriteCapacity(1); _buffer[_offset++] = CborInitialByte.IndefiniteLengthBreakByte; } } private readonly struct StackFrame { public StackFrame( CborMajorType? type, int frameOffset, int? definiteLength, int itemsWritten, int? currentKeyOffset, int? currentValueOffset, bool keysRequireSorting, List<KeyValuePairEncodingRange>? keyValuePairEncodingRanges, HashSet<(int Offset, int Length)>? keyEncodingRanges) { MajorType = type; FrameOffset = frameOffset; DefiniteLength = definiteLength; ItemsWritten = itemsWritten; CurrentKeyOffset = currentKeyOffset; CurrentValueOffset = currentValueOffset; KeysRequireSorting = keysRequireSorting; KeyValuePairEncodingRanges = keyValuePairEncodingRanges; KeyEncodingRanges = keyEncodingRanges; } public CborMajorType? MajorType { get; } public int FrameOffset { get; } public int? DefiniteLength { get; } public int ItemsWritten { get; } public int? CurrentKeyOffset { get; } public int? CurrentValueOffset { get; } public bool KeysRequireSorting { get; } public List<KeyValuePairEncodingRange>? KeyValuePairEncodingRanges { get; } public HashSet<(int Offset, int Length)>? KeyEncodingRanges { get; } } } }
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/AddPairwiseWideningAndAdd.Vector128.SByte.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void AddPairwiseWideningAndAdd_Vector128_SByte() { var test = new SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte { 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, SByte[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); 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<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 Vector128<Int16> _fld1; public Vector128<SByte> _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<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte testClass) { var result = AdvSimd.AddPairwiseWideningAndAdd(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.AddPairwiseWideningAndAdd( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((SByte*)(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<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<Int16> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, 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.AddPairwiseWideningAndAdd( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_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.AddPairwiseWideningAndAdd( AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((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(AdvSimd).GetMethod(nameof(AdvSimd.AddPairwiseWideningAndAdd), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddPairwiseWideningAndAdd), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.AddPairwiseWideningAndAdd( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.AddPairwiseWideningAndAdd( AdvSimd.LoadVector128((Int16*)(pClsVar1)), AdvSimd.LoadVector128((SByte*)(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<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = AdvSimd.AddPairwiseWideningAndAdd(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((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.AddPairwiseWideningAndAdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte(); var result = AdvSimd.AddPairwiseWideningAndAdd(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__AddPairwiseWideningAndAdd_Vector128_SByte(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.AddPairwiseWideningAndAdd( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.AddPairwiseWideningAndAdd(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.AddPairwiseWideningAndAdd( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((SByte*)(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.AddPairwiseWideningAndAdd(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.AddPairwiseWideningAndAdd( AdvSimd.LoadVector128((Int16*)(&test._fld1)), AdvSimd.LoadVector128((SByte*)(&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<Int16> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, SByte[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.AddPairwiseWideningAndAdd(left, right, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AddPairwiseWideningAndAdd)}<Int16>(Vector128<Int16>, Vector128<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.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 AddPairwiseWideningAndAdd_Vector128_SByte() { var test = new SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte { 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, SByte[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); 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<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 Vector128<Int16> _fld1; public Vector128<SByte> _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<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte testClass) { var result = AdvSimd.AddPairwiseWideningAndAdd(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.AddPairwiseWideningAndAdd( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((SByte*)(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<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<Int16> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, 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.AddPairwiseWideningAndAdd( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_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.AddPairwiseWideningAndAdd( AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((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(AdvSimd).GetMethod(nameof(AdvSimd.AddPairwiseWideningAndAdd), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddPairwiseWideningAndAdd), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.AddPairwiseWideningAndAdd( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.AddPairwiseWideningAndAdd( AdvSimd.LoadVector128((Int16*)(pClsVar1)), AdvSimd.LoadVector128((SByte*)(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<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = AdvSimd.AddPairwiseWideningAndAdd(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((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.AddPairwiseWideningAndAdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte(); var result = AdvSimd.AddPairwiseWideningAndAdd(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__AddPairwiseWideningAndAdd_Vector128_SByte(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.AddPairwiseWideningAndAdd( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.AddPairwiseWideningAndAdd(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.AddPairwiseWideningAndAdd( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((SByte*)(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.AddPairwiseWideningAndAdd(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.AddPairwiseWideningAndAdd( AdvSimd.LoadVector128((Int16*)(&test._fld1)), AdvSimd.LoadVector128((SByte*)(&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<Int16> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, SByte[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.AddPairwiseWideningAndAdd(left, right, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AddPairwiseWideningAndAdd)}<Int16>(Vector128<Int16>, Vector128<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,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Security.AccessControl/tests/CommonSecurityDescriptor/CommonSecurityDescriptor_GetSddlForm.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.Security.Principal; using Xunit; namespace System.Security.AccessControl.Tests { public partial class CommonSecurityDescriptor_GetSddlForm { public static IEnumerable<object[]> CommonSecurityDescriptor_GetSddlForm_TestData() { yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", false, false, false, false , "" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", false, false, false, true , "D:(D;;0x1000;;;BO)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", false, false, true , false, "S:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", false, false, true , true , "D:(D;;0x1000;;;BO)S:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", false, true , false, false, "G:BG" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", false, true , false, true , "G:BGD:(D;;0x1000;;;BO)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", false, true , true , false, "G:BGS:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", false, true , true , true , "G:BGD:(D;;0x1000;;;BO)S:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , false, false, false, "O:BA" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , false, false, true , "O:BAD:(D;;0x1000;;;BO)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , false, true , false, "O:BAS:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , false, true , true , "O:BAD:(D;;0x1000;;;BO)S:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , true , false, false, "O:BAG:BG" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , true , false, true , "O:BAG:BGD:(D;;0x1000;;;BO)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , true , true , false, "O:BAG:BGS:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , true , true , true , "O:BAG:BGD:(D;;0x1000;;;BO)S:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 0 , null, null, null , null , true , true , true , true , "" }; yield return new object[] { true, false, 4 , "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , true , true , true , "O:BAG:BGD:(D;;0x1000;;;BO)S:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 4 , "BA", "BG", null , "0:1:4096:BO:false:0", true , true , true , true , "O:BAG:BGD:(D;;0x1000;;;BO)" }; yield return new object[] { true, false, 20, "BA", "BG", null , "0:1:4096:BO:false:0", true , true , true , true , "O:BAG:BGD:(D;;0x1000;;;BO)" }; yield return new object[] { true, false, 16, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , true , true , true , "O:BAG:BGD:(D;;0x1000;;;BO)S:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 16, "BA", "BG", "64:2:4096:BA:false:0", null , true , true , true , true , "O:BAG:BGS:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", null , true , true , true , true , "O:BAG:BGS:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, null, "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , true , true , true , "G:BGD:(D;;0x1000;;;BO)S:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", null, "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , true , true , true , "O:BAD:(D;;0x1000;;;BO)S:(AU;SA;0x1000;;;BA)" }; } [Theory] [MemberData(nameof(CommonSecurityDescriptor_GetSddlForm_TestData))] public static void TestGetSddlForm(bool isContainer, bool isDS, int flags, string ownerStr, string groupStr, string saclStr, string daclStr, bool getOwner, bool getGroup, bool getSacl, bool getDacl, string expectedSddl) { CommonSecurityDescriptor commonSecurityDescriptor = null; string resultSddl = null; ControlFlags controlFlags = ControlFlags.OwnerDefaulted; SecurityIdentifier owner = null; SecurityIdentifier group = null; RawAcl rawAcl = null; SystemAcl sacl = null; DiscretionaryAcl dacl = null; AccessControlSections accControlSections = AccessControlSections.None; controlFlags = (ControlFlags)flags; owner = (ownerStr != null) ? new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(ownerStr)) : null; group = (groupStr != null) ? new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(groupStr)) : null; rawAcl = (saclStr != null) ? Utils.CreateRawAclFromString(saclStr) : null; if (rawAcl == null) sacl = null; else sacl = new SystemAcl(isContainer, isDS, rawAcl); rawAcl = (daclStr != null) ? Utils.CreateRawAclFromString(daclStr) : null; if (rawAcl == null) dacl = null; else dacl = new DiscretionaryAcl(isContainer, isDS, rawAcl); commonSecurityDescriptor = new CommonSecurityDescriptor(isContainer, isDS, controlFlags, owner, group, sacl, dacl); if (getOwner) accControlSections |= AccessControlSections.Owner; if (getGroup) accControlSections |= AccessControlSections.Group; if (getSacl) accControlSections |= AccessControlSections.Audit; if (getDacl) accControlSections |= AccessControlSections.Access; resultSddl = commonSecurityDescriptor.GetSddlForm(accControlSections); Assert.True(string.Compare(expectedSddl, resultSddl, StringComparison.CurrentCultureIgnoreCase) == 0); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Security.Principal; using Xunit; namespace System.Security.AccessControl.Tests { public partial class CommonSecurityDescriptor_GetSddlForm { public static IEnumerable<object[]> CommonSecurityDescriptor_GetSddlForm_TestData() { yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", false, false, false, false , "" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", false, false, false, true , "D:(D;;0x1000;;;BO)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", false, false, true , false, "S:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", false, false, true , true , "D:(D;;0x1000;;;BO)S:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", false, true , false, false, "G:BG" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", false, true , false, true , "G:BGD:(D;;0x1000;;;BO)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", false, true , true , false, "G:BGS:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", false, true , true , true , "G:BGD:(D;;0x1000;;;BO)S:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , false, false, false, "O:BA" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , false, false, true , "O:BAD:(D;;0x1000;;;BO)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , false, true , false, "O:BAS:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , false, true , true , "O:BAD:(D;;0x1000;;;BO)S:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , true , false, false, "O:BAG:BG" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , true , false, true , "O:BAG:BGD:(D;;0x1000;;;BO)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , true , true , false, "O:BAG:BGS:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , true , true , true , "O:BAG:BGD:(D;;0x1000;;;BO)S:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 0 , null, null, null , null , true , true , true , true , "" }; yield return new object[] { true, false, 4 , "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , true , true , true , "O:BAG:BGD:(D;;0x1000;;;BO)S:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 4 , "BA", "BG", null , "0:1:4096:BO:false:0", true , true , true , true , "O:BAG:BGD:(D;;0x1000;;;BO)" }; yield return new object[] { true, false, 20, "BA", "BG", null , "0:1:4096:BO:false:0", true , true , true , true , "O:BAG:BGD:(D;;0x1000;;;BO)" }; yield return new object[] { true, false, 16, "BA", "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , true , true , true , "O:BAG:BGD:(D;;0x1000;;;BO)S:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 16, "BA", "BG", "64:2:4096:BA:false:0", null , true , true , true , true , "O:BAG:BGS:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", "BG", "64:2:4096:BA:false:0", null , true , true , true , true , "O:BAG:BGS:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, null, "BG", "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , true , true , true , "G:BGD:(D;;0x1000;;;BO)S:(AU;SA;0x1000;;;BA)" }; yield return new object[] { true, false, 20, "BA", null, "64:2:4096:BA:false:0", "0:1:4096:BO:false:0", true , true , true , true , "O:BAD:(D;;0x1000;;;BO)S:(AU;SA;0x1000;;;BA)" }; } [Theory] [MemberData(nameof(CommonSecurityDescriptor_GetSddlForm_TestData))] public static void TestGetSddlForm(bool isContainer, bool isDS, int flags, string ownerStr, string groupStr, string saclStr, string daclStr, bool getOwner, bool getGroup, bool getSacl, bool getDacl, string expectedSddl) { CommonSecurityDescriptor commonSecurityDescriptor = null; string resultSddl = null; ControlFlags controlFlags = ControlFlags.OwnerDefaulted; SecurityIdentifier owner = null; SecurityIdentifier group = null; RawAcl rawAcl = null; SystemAcl sacl = null; DiscretionaryAcl dacl = null; AccessControlSections accControlSections = AccessControlSections.None; controlFlags = (ControlFlags)flags; owner = (ownerStr != null) ? new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(ownerStr)) : null; group = (groupStr != null) ? new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(groupStr)) : null; rawAcl = (saclStr != null) ? Utils.CreateRawAclFromString(saclStr) : null; if (rawAcl == null) sacl = null; else sacl = new SystemAcl(isContainer, isDS, rawAcl); rawAcl = (daclStr != null) ? Utils.CreateRawAclFromString(daclStr) : null; if (rawAcl == null) dacl = null; else dacl = new DiscretionaryAcl(isContainer, isDS, rawAcl); commonSecurityDescriptor = new CommonSecurityDescriptor(isContainer, isDS, controlFlags, owner, group, sacl, dacl); if (getOwner) accControlSections |= AccessControlSections.Owner; if (getGroup) accControlSections |= AccessControlSections.Group; if (getSacl) accControlSections |= AccessControlSections.Audit; if (getDacl) accControlSections |= AccessControlSections.Access; resultSddl = commonSecurityDescriptor.GetSddlForm(accControlSections); Assert.True(string.Compare(expectedSddl, resultSddl, StringComparison.CurrentCultureIgnoreCase) == 0); } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DebugInformationProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Internal.IL; namespace ILCompiler { /// <summary> /// Provides debug information by delegating to the <see cref="MethodIL"/>. /// </summary> public class DebugInformationProvider { public virtual MethodDebugInformation GetDebugInfo(MethodIL methodIL) { return methodIL.GetDebugInfo(); } } /// <summary> /// Provides empty debug information. /// </summary> public sealed class NullDebugInformationProvider : DebugInformationProvider { public override MethodDebugInformation GetDebugInfo(MethodIL methodIL) { return MethodDebugInformation.None; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Internal.IL; namespace ILCompiler { /// <summary> /// Provides debug information by delegating to the <see cref="MethodIL"/>. /// </summary> public class DebugInformationProvider { public virtual MethodDebugInformation GetDebugInfo(MethodIL methodIL) { return methodIL.GetDebugInfo(); } } /// <summary> /// Provides empty debug information. /// </summary> public sealed class NullDebugInformationProvider : DebugInformationProvider { public override MethodDebugInformation GetDebugInfo(MethodIL methodIL) { return MethodDebugInformation.None; } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/installer/tests/Assets/TestProjects/LightupLib/Program.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; namespace LightupLib { public class Greet { public static string Hello(string name) { // Load a dependency of LightupLib var t = typeof(Newtonsoft.Json.JsonReader); if (t != null) return "Hello "+name; else return "Failed to load LibDependency"; } } }
// 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; namespace LightupLib { public class Greet { public static string Hello(string name) { // Load a dependency of LightupLib var t = typeof(Newtonsoft.Json.JsonReader); if (t != null) return "Hello "+name; else return "Failed to load LibDependency"; } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/coreclr/System.Private.CoreLib/Tools/GenUnicodeProp/StrongBidiCategory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace GenUnicodeProp { // Corresponds to the "strong" categories from https://www.unicode.org/reports/tr44/#Bidi_Class_Values. // For our purposes, each code point is strongly left-to-right ("L"), strongly right-to-left ("R", "AL"), // or other (all remaining code points). This is only used internally by IDN processing, and since our // IDN processing logic only cares about "strong" values we don't carry the rest of the data. internal enum StrongBidiCategory { Other = 0, StrongLeftToRight = 1, StrongRightToLeft = 2, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace GenUnicodeProp { // Corresponds to the "strong" categories from https://www.unicode.org/reports/tr44/#Bidi_Class_Values. // For our purposes, each code point is strongly left-to-right ("L"), strongly right-to-left ("R", "AL"), // or other (all remaining code points). This is only used internally by IDN processing, and since our // IDN processing logic only cares about "strong" values we don't carry the rest of the data. internal enum StrongBidiCategory { Other = 0, StrongLeftToRight = 1, StrongRightToLeft = 2, } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/mono/mono/tests/assembly_append_ordering.cs
using System; using System.Linq; using System.Reflection; using System.Reflection.Emit; class Driver { static int Main () { var dyn = DefineDynamicAssembly (AppDomain.CurrentDomain); var core = TriggerLoadingSystemCore (); var asm = AppDomain.CurrentDomain.GetAssemblies (); if (asm [0] != typeof (object).Assembly) { Console.WriteLine ("first assembly must be mscorlib, but it was {0}", asm [0]); return 1; } if (asm [1] != typeof (Driver).Assembly) { Console.WriteLine ("second assembly must be test assembly, but it was {0}", asm [1]); return 2; } if (asm [2] != dyn) { Console.WriteLine ("third assembly must be SRE, but it was {0}", asm [2]); return 3; } if (asm [3] != core) { Console.WriteLine ("last assembly must be System.Core, but it was {0}", asm [3]); return 4; } return 0; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] static Assembly TriggerLoadingSystemCore () { int[] x = new int[] { 1,2,3}; x.Where (v => v > 1); return typeof (Enumerable).Assembly; } static Assembly DefineDynamicAssembly (AppDomain domain) { AssemblyName assemblyName = new AssemblyName (); assemblyName.Name = "MyDynamicAssembly"; AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly (assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule ("MyDynamicModule"); TypeBuilder typeBuilder = moduleBuilder.DefineType ("MyDynamicType", TypeAttributes.Public); ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor (MethodAttributes.Public, CallingConventions.Standard, null); ILGenerator ilGenerator = constructorBuilder.GetILGenerator (); ilGenerator.EmitWriteLine ("MyDynamicType instantiated!"); ilGenerator.Emit (OpCodes.Ret); typeBuilder.CreateType (); return assemblyBuilder; } }
using System; using System.Linq; using System.Reflection; using System.Reflection.Emit; class Driver { static int Main () { var dyn = DefineDynamicAssembly (AppDomain.CurrentDomain); var core = TriggerLoadingSystemCore (); var asm = AppDomain.CurrentDomain.GetAssemblies (); if (asm [0] != typeof (object).Assembly) { Console.WriteLine ("first assembly must be mscorlib, but it was {0}", asm [0]); return 1; } if (asm [1] != typeof (Driver).Assembly) { Console.WriteLine ("second assembly must be test assembly, but it was {0}", asm [1]); return 2; } if (asm [2] != dyn) { Console.WriteLine ("third assembly must be SRE, but it was {0}", asm [2]); return 3; } if (asm [3] != core) { Console.WriteLine ("last assembly must be System.Core, but it was {0}", asm [3]); return 4; } return 0; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] static Assembly TriggerLoadingSystemCore () { int[] x = new int[] { 1,2,3}; x.Where (v => v > 1); return typeof (Enumerable).Assembly; } static Assembly DefineDynamicAssembly (AppDomain domain) { AssemblyName assemblyName = new AssemblyName (); assemblyName.Name = "MyDynamicAssembly"; AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly (assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule ("MyDynamicModule"); TypeBuilder typeBuilder = moduleBuilder.DefineType ("MyDynamicType", TypeAttributes.Public); ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor (MethodAttributes.Public, CallingConventions.Standard, null); ILGenerator ilGenerator = constructorBuilder.GetILGenerator (); ilGenerator.EmitWriteLine ("MyDynamicType instantiated!"); ilGenerator.Emit (OpCodes.Ret); typeBuilder.CreateType (); return assemblyBuilder; } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/X86Emitter.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; namespace ILCompiler.DependencyAnalysis.X86 { public struct X86Emitter { public X86Emitter(NodeFactory factory, bool relocsOnly) { Builder = new ObjectDataBuilder(factory, relocsOnly); TargetRegister = new TargetRegisterMap(factory.Target.OperatingSystem); } public ObjectDataBuilder Builder; public TargetRegisterMap TargetRegister; public void EmitCMP(ref AddrMode addrMode, sbyte immediate) { if (addrMode.Size == AddrModeSize.Int16) Builder.EmitByte(0x66); EmitIndirInstruction((byte)((addrMode.Size != AddrModeSize.Int8) ? 0x83 : 0x80), 0x7, ref addrMode); Builder.EmitByte((byte)immediate); } public void EmitADD(ref AddrMode addrMode, sbyte immediate) { if (addrMode.Size == AddrModeSize.Int16) Builder.EmitByte(0x66); EmitIndirInstruction((byte)((addrMode.Size != AddrModeSize.Int8) ? 0x83 : 0x80), (byte)0, ref addrMode); Builder.EmitByte((byte)immediate); } public void EmitJMP(ISymbolNode symbol) { if (symbol.RepresentsIndirectionCell) { Builder.EmitByte(0xff); Builder.EmitByte(0x25); Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_HIGHLOW); } else { Builder.EmitByte(0xE9); Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_REL32); } } public void EmitXOR(Register register1, Register register2) { Builder.EmitByte(0x33); Builder.EmitByte((byte)(0xC0 | ((byte)register1 << 3) | (byte)register2)); } public void EmitPUSH(sbyte imm8) { Builder.EmitByte(0x6A); Builder.EmitByte(unchecked((byte)imm8)); } public void EmitPUSH(ISymbolNode node) { if (node.RepresentsIndirectionCell) { // push [node address] Builder.EmitByte(0xFF); Builder.EmitByte(0x35); } else { // push <node address> Builder.EmitByte(0x68); } Builder.EmitReloc(node, RelocType.IMAGE_REL_BASED_HIGHLOW); } public void EmitMOV(Register regDst, Register regSrc) { Builder.EmitByte(0x8B); Builder.EmitByte((byte)(0xC0 | (((int)regDst & 0x07) << 3) | (((int)regSrc & 0x07)))); } public void EmitMOV(Register register, ISymbolNode node, int delta = 0) { if (node.RepresentsIndirectionCell) { // mov register, [node address] Builder.EmitByte(0x8B); Builder.EmitByte((byte)(0x00 | ((byte)register << 3) | 0x5)); } else { // mov register, immediate Builder.EmitByte((byte)(0xB8 + (byte)register)); } Builder.EmitReloc(node, RelocType.IMAGE_REL_BASED_HIGHLOW, delta); } public void EmitINT3() { Builder.EmitByte(0xCC); } public void EmitRET() { Builder.EmitByte(0xC3); } public void EmitRETIfEqual() { // jne @+1 Builder.EmitByte(0x75); Builder.EmitByte(0x01); // ret Builder.EmitByte(0xC3); } private bool InSignedByteRange(int i) { return i == (int)(sbyte)i; } private void EmitImmediate(int immediate, int size) { switch (size) { case 0: break; case 1: Builder.EmitByte((byte)immediate); break; case 2: Builder.EmitShort((short)immediate); break; case 4: Builder.EmitInt(immediate); break; default: throw new NotImplementedException(); } } private void EmitModRM(byte subOpcode, ref AddrMode addrMode) { byte modRM = (byte)((subOpcode & 0x07) << 3); if (addrMode.BaseReg > Register.None) { Debug.Assert(addrMode.BaseReg >= Register.RegDirect); Register reg = (Register)(addrMode.BaseReg - Register.RegDirect); Builder.EmitByte((byte)(0xC0 | modRM | ((int)reg & 0x07))); } else { byte lowOrderBitsOfBaseReg = (byte)((int)addrMode.BaseReg & 0x07); modRM |= lowOrderBitsOfBaseReg; int offsetSize = 0; if (addrMode.Offset == 0 && (lowOrderBitsOfBaseReg != (byte)Register.EBP)) { offsetSize = 0; } else if (InSignedByteRange(addrMode.Offset)) { offsetSize = 1; modRM |= 0x40; } else { offsetSize = 4; modRM |= 0x80; } bool emitSibByte = false; Register sibByteBaseRegister = addrMode.BaseReg; if (addrMode.BaseReg == Register.None) { emitSibByte = (addrMode.IndexReg != Register.NoIndex); modRM &= 0x38; // set Mod bits to 00 and clear out base reg offsetSize = 4; // this forces 32-bit displacement if (emitSibByte) { // EBP in SIB byte means no base // ModRM base register forced to ESP in SIB code below sibByteBaseRegister = Register.EBP; } else { // EBP in ModRM means no base modRM |= (byte)(Register.EBP); } } else if (lowOrderBitsOfBaseReg == (byte)Register.ESP || addrMode.IndexReg.HasValue) { emitSibByte = true; } if (!emitSibByte) { Builder.EmitByte(modRM); } else { modRM = (byte)((modRM & 0xF8) | (int)Register.ESP); Builder.EmitByte(modRM); int indexRegAsInt = (int)(addrMode.IndexReg.HasValue ? addrMode.IndexReg.Value : Register.ESP); Builder.EmitByte((byte)((addrMode.Scale << 6) + ((indexRegAsInt & 0x07) << 3) + ((int)sibByteBaseRegister & 0x07))); } EmitImmediate(addrMode.Offset, offsetSize); } } private void EmitExtendedOpcode(int opcode) { if ((opcode >> 16) != 0) { if ((opcode >> 24) != 0) { Builder.EmitByte((byte)(opcode >> 24)); } Builder.EmitByte((byte)(opcode >> 16)); } Builder.EmitByte((byte)(opcode >> 8)); } private void EmitIndirInstruction(int opcode, byte subOpcode, ref AddrMode addrMode) { if ((opcode >> 8) != 0) { EmitExtendedOpcode(opcode); } Builder.EmitByte((byte)opcode); EmitModRM(subOpcode, ref addrMode); } } }
// 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; namespace ILCompiler.DependencyAnalysis.X86 { public struct X86Emitter { public X86Emitter(NodeFactory factory, bool relocsOnly) { Builder = new ObjectDataBuilder(factory, relocsOnly); TargetRegister = new TargetRegisterMap(factory.Target.OperatingSystem); } public ObjectDataBuilder Builder; public TargetRegisterMap TargetRegister; public void EmitCMP(ref AddrMode addrMode, sbyte immediate) { if (addrMode.Size == AddrModeSize.Int16) Builder.EmitByte(0x66); EmitIndirInstruction((byte)((addrMode.Size != AddrModeSize.Int8) ? 0x83 : 0x80), 0x7, ref addrMode); Builder.EmitByte((byte)immediate); } public void EmitADD(ref AddrMode addrMode, sbyte immediate) { if (addrMode.Size == AddrModeSize.Int16) Builder.EmitByte(0x66); EmitIndirInstruction((byte)((addrMode.Size != AddrModeSize.Int8) ? 0x83 : 0x80), (byte)0, ref addrMode); Builder.EmitByte((byte)immediate); } public void EmitJMP(ISymbolNode symbol) { if (symbol.RepresentsIndirectionCell) { Builder.EmitByte(0xff); Builder.EmitByte(0x25); Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_HIGHLOW); } else { Builder.EmitByte(0xE9); Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_REL32); } } public void EmitXOR(Register register1, Register register2) { Builder.EmitByte(0x33); Builder.EmitByte((byte)(0xC0 | ((byte)register1 << 3) | (byte)register2)); } public void EmitPUSH(sbyte imm8) { Builder.EmitByte(0x6A); Builder.EmitByte(unchecked((byte)imm8)); } public void EmitPUSH(ISymbolNode node) { if (node.RepresentsIndirectionCell) { // push [node address] Builder.EmitByte(0xFF); Builder.EmitByte(0x35); } else { // push <node address> Builder.EmitByte(0x68); } Builder.EmitReloc(node, RelocType.IMAGE_REL_BASED_HIGHLOW); } public void EmitMOV(Register regDst, Register regSrc) { Builder.EmitByte(0x8B); Builder.EmitByte((byte)(0xC0 | (((int)regDst & 0x07) << 3) | (((int)regSrc & 0x07)))); } public void EmitMOV(Register register, ISymbolNode node, int delta = 0) { if (node.RepresentsIndirectionCell) { // mov register, [node address] Builder.EmitByte(0x8B); Builder.EmitByte((byte)(0x00 | ((byte)register << 3) | 0x5)); } else { // mov register, immediate Builder.EmitByte((byte)(0xB8 + (byte)register)); } Builder.EmitReloc(node, RelocType.IMAGE_REL_BASED_HIGHLOW, delta); } public void EmitINT3() { Builder.EmitByte(0xCC); } public void EmitRET() { Builder.EmitByte(0xC3); } public void EmitRETIfEqual() { // jne @+1 Builder.EmitByte(0x75); Builder.EmitByte(0x01); // ret Builder.EmitByte(0xC3); } private bool InSignedByteRange(int i) { return i == (int)(sbyte)i; } private void EmitImmediate(int immediate, int size) { switch (size) { case 0: break; case 1: Builder.EmitByte((byte)immediate); break; case 2: Builder.EmitShort((short)immediate); break; case 4: Builder.EmitInt(immediate); break; default: throw new NotImplementedException(); } } private void EmitModRM(byte subOpcode, ref AddrMode addrMode) { byte modRM = (byte)((subOpcode & 0x07) << 3); if (addrMode.BaseReg > Register.None) { Debug.Assert(addrMode.BaseReg >= Register.RegDirect); Register reg = (Register)(addrMode.BaseReg - Register.RegDirect); Builder.EmitByte((byte)(0xC0 | modRM | ((int)reg & 0x07))); } else { byte lowOrderBitsOfBaseReg = (byte)((int)addrMode.BaseReg & 0x07); modRM |= lowOrderBitsOfBaseReg; int offsetSize = 0; if (addrMode.Offset == 0 && (lowOrderBitsOfBaseReg != (byte)Register.EBP)) { offsetSize = 0; } else if (InSignedByteRange(addrMode.Offset)) { offsetSize = 1; modRM |= 0x40; } else { offsetSize = 4; modRM |= 0x80; } bool emitSibByte = false; Register sibByteBaseRegister = addrMode.BaseReg; if (addrMode.BaseReg == Register.None) { emitSibByte = (addrMode.IndexReg != Register.NoIndex); modRM &= 0x38; // set Mod bits to 00 and clear out base reg offsetSize = 4; // this forces 32-bit displacement if (emitSibByte) { // EBP in SIB byte means no base // ModRM base register forced to ESP in SIB code below sibByteBaseRegister = Register.EBP; } else { // EBP in ModRM means no base modRM |= (byte)(Register.EBP); } } else if (lowOrderBitsOfBaseReg == (byte)Register.ESP || addrMode.IndexReg.HasValue) { emitSibByte = true; } if (!emitSibByte) { Builder.EmitByte(modRM); } else { modRM = (byte)((modRM & 0xF8) | (int)Register.ESP); Builder.EmitByte(modRM); int indexRegAsInt = (int)(addrMode.IndexReg.HasValue ? addrMode.IndexReg.Value : Register.ESP); Builder.EmitByte((byte)((addrMode.Scale << 6) + ((indexRegAsInt & 0x07) << 3) + ((int)sibByteBaseRegister & 0x07))); } EmitImmediate(addrMode.Offset, offsetSize); } } private void EmitExtendedOpcode(int opcode) { if ((opcode >> 16) != 0) { if ((opcode >> 24) != 0) { Builder.EmitByte((byte)(opcode >> 24)); } Builder.EmitByte((byte)(opcode >> 16)); } Builder.EmitByte((byte)(opcode >> 8)); } private void EmitIndirInstruction(int opcode, byte subOpcode, ref AddrMode addrMode) { if ((opcode >> 8) != 0) { EmitExtendedOpcode(opcode); } Builder.EmitByte((byte)opcode); EmitModRM(subOpcode, ref addrMode); } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.ServiceModel.Syndication/tests/Utils/ThrowingXmlReader.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Xml; namespace System.ServiceModel.Syndication.Tests { public class ThrowingXmlReader : XmlReader { public ThrowingXmlReader(Exception exception) => Exception = exception; public Exception Exception { get; } public override int AttributeCount => throw Exception; public override string BaseURI => throw Exception; public override int Depth => throw Exception; public override bool EOF => throw Exception; public override bool IsEmptyElement => throw Exception; public override string LocalName => throw Exception; public override string NamespaceURI => throw Exception; public override XmlNameTable NameTable => throw Exception; public override XmlNodeType NodeType => XmlNodeType.Element; public override string Prefix => throw Exception; public override ReadState ReadState => throw Exception; public override string Value => throw Exception; public override string GetAttribute(int i) => throw Exception; public override string GetAttribute(string name) => throw Exception; public override string GetAttribute(string name, string namespaceURI) => throw Exception; public override string LookupNamespace(string prefix) => throw Exception; public override bool MoveToAttribute(string name) => throw Exception; public override bool MoveToAttribute(string name, string ns) => throw Exception; public override bool MoveToElement() => throw Exception; public override bool MoveToFirstAttribute() => throw Exception; public override bool MoveToNextAttribute() => throw Exception; public override bool Read() => throw Exception; public override bool ReadAttributeValue() => throw Exception; public override void ResolveEntity() => throw Exception; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Xml; namespace System.ServiceModel.Syndication.Tests { public class ThrowingXmlReader : XmlReader { public ThrowingXmlReader(Exception exception) => Exception = exception; public Exception Exception { get; } public override int AttributeCount => throw Exception; public override string BaseURI => throw Exception; public override int Depth => throw Exception; public override bool EOF => throw Exception; public override bool IsEmptyElement => throw Exception; public override string LocalName => throw Exception; public override string NamespaceURI => throw Exception; public override XmlNameTable NameTable => throw Exception; public override XmlNodeType NodeType => XmlNodeType.Element; public override string Prefix => throw Exception; public override ReadState ReadState => throw Exception; public override string Value => throw Exception; public override string GetAttribute(int i) => throw Exception; public override string GetAttribute(string name) => throw Exception; public override string GetAttribute(string name, string namespaceURI) => throw Exception; public override string LookupNamespace(string prefix) => throw Exception; public override bool MoveToAttribute(string name) => throw Exception; public override bool MoveToAttribute(string name, string ns) => throw Exception; public override bool MoveToElement() => throw Exception; public override bool MoveToFirstAttribute() => throw Exception; public override bool MoveToNextAttribute() => throw Exception; public override bool Read() => throw Exception; public override bool ReadAttributeValue() => throw Exception; public override void ResolveEntity() => throw Exception; } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Data.Common/src/System/Data/Common/DbTransaction.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.Threading; using System.Threading.Tasks; namespace System.Data.Common { public abstract class DbTransaction : MarshalByRefObject, IDbTransaction, IAsyncDisposable { protected DbTransaction() : base() { } public DbConnection? Connection => DbConnection; IDbConnection? IDbTransaction.Connection => DbConnection; protected abstract DbConnection? DbConnection { get; } public abstract IsolationLevel IsolationLevel { get; } public abstract void Commit(); public virtual Task CommitAsync(CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } try { Commit(); return Task.CompletedTask; } catch (Exception e) { return Task.FromException(e); } } public void Dispose() => Dispose(true); protected virtual void Dispose(bool disposing) { } public virtual ValueTask DisposeAsync() { Dispose(); return default; } public abstract void Rollback(); public virtual Task RollbackAsync(CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } try { Rollback(); return Task.CompletedTask; } catch (Exception e) { return Task.FromException(e); } } #region Savepoints /// <summary> /// Gets a value that indicates whether this <see cref="DbTransaction" /> instance supports database savepoints. /// If <see langword="false" />, the methods <see cref="SaveAsync" />, /// <see cref="RollbackAsync(string, System.Threading.CancellationToken)"/> and <see cref="ReleaseAsync" /> as /// well as their synchronous counterparts are expected to throw <see cref="NotSupportedException" />. /// </summary> /// <returns> /// <see langword="true" /> if this <see cref="DbTransaction"/> instance supports database savepoints; otherwise, /// <see langword="false" />. /// </returns> public virtual bool SupportsSavepoints => false; /// <summary> /// Creates a savepoint in the transaction. This allows all commands that are executed after the savepoint was /// established to be rolled back, restoring the transaction state to what it was at the time of the savepoint. /// </summary> /// <param name="savepointName">The name of the savepoint to be created.</param> /// <param name="cancellationToken"> /// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None" />. /// </param> /// <returns>A <see cref="Task " /> representing the asynchronous operation.</returns> public virtual Task SaveAsync(string savepointName, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } try { Save(savepointName); return Task.CompletedTask; } catch (Exception e) { return Task.FromException(e); } } /// <summary> /// Rolls back all commands that were executed after the specified savepoint was established. /// </summary> /// <param name="savepointName">The name of the savepoint to roll back to.</param> /// <param name="cancellationToken"> /// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None" />. /// </param> /// <returns>A <see cref="Task " /> representing the asynchronous operation.</returns> public virtual Task RollbackAsync(string savepointName, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } try { Rollback(savepointName); return Task.CompletedTask; } catch (Exception e) { return Task.FromException(e); } } /// <summary> /// Destroys a savepoint previously defined in the current transaction. This allows the system to /// reclaim some resources before the transaction ends. /// </summary> /// <param name="savepointName">The name of the savepoint to release.</param> /// <param name="cancellationToken"> /// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None" />. /// </param> /// <returns>A <see cref="Task " /> representing the asynchronous operation.</returns> public virtual Task ReleaseAsync(string savepointName, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } try { Release(savepointName); return Task.CompletedTask; } catch (Exception e) { return Task.FromException(e); } } /// <summary> /// Creates a savepoint in the transaction. This allows all commands that are executed after the savepoint was /// established to be rolled back, restoring the transaction state to what it was at the time of the savepoint. /// </summary> /// <param name="savepointName">The name of the savepoint to be created.</param> public virtual void Save(string savepointName) => throw new NotSupportedException(); /// <summary> /// Rolls back all commands that were executed after the specified savepoint was established. /// </summary> /// <param name="savepointName">The name of the savepoint to roll back to.</param> public virtual void Rollback(string savepointName) => throw new NotSupportedException(); /// <summary> /// Destroys a savepoint previously defined in the current transaction. This allows the system to /// reclaim some resources before the transaction ends. /// </summary> /// <param name="savepointName">The name of the savepoint to release.</param> public virtual void Release(string savepointName) {} #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Threading; using System.Threading.Tasks; namespace System.Data.Common { public abstract class DbTransaction : MarshalByRefObject, IDbTransaction, IAsyncDisposable { protected DbTransaction() : base() { } public DbConnection? Connection => DbConnection; IDbConnection? IDbTransaction.Connection => DbConnection; protected abstract DbConnection? DbConnection { get; } public abstract IsolationLevel IsolationLevel { get; } public abstract void Commit(); public virtual Task CommitAsync(CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } try { Commit(); return Task.CompletedTask; } catch (Exception e) { return Task.FromException(e); } } public void Dispose() => Dispose(true); protected virtual void Dispose(bool disposing) { } public virtual ValueTask DisposeAsync() { Dispose(); return default; } public abstract void Rollback(); public virtual Task RollbackAsync(CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } try { Rollback(); return Task.CompletedTask; } catch (Exception e) { return Task.FromException(e); } } #region Savepoints /// <summary> /// Gets a value that indicates whether this <see cref="DbTransaction" /> instance supports database savepoints. /// If <see langword="false" />, the methods <see cref="SaveAsync" />, /// <see cref="RollbackAsync(string, System.Threading.CancellationToken)"/> and <see cref="ReleaseAsync" /> as /// well as their synchronous counterparts are expected to throw <see cref="NotSupportedException" />. /// </summary> /// <returns> /// <see langword="true" /> if this <see cref="DbTransaction"/> instance supports database savepoints; otherwise, /// <see langword="false" />. /// </returns> public virtual bool SupportsSavepoints => false; /// <summary> /// Creates a savepoint in the transaction. This allows all commands that are executed after the savepoint was /// established to be rolled back, restoring the transaction state to what it was at the time of the savepoint. /// </summary> /// <param name="savepointName">The name of the savepoint to be created.</param> /// <param name="cancellationToken"> /// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None" />. /// </param> /// <returns>A <see cref="Task " /> representing the asynchronous operation.</returns> public virtual Task SaveAsync(string savepointName, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } try { Save(savepointName); return Task.CompletedTask; } catch (Exception e) { return Task.FromException(e); } } /// <summary> /// Rolls back all commands that were executed after the specified savepoint was established. /// </summary> /// <param name="savepointName">The name of the savepoint to roll back to.</param> /// <param name="cancellationToken"> /// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None" />. /// </param> /// <returns>A <see cref="Task " /> representing the asynchronous operation.</returns> public virtual Task RollbackAsync(string savepointName, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } try { Rollback(savepointName); return Task.CompletedTask; } catch (Exception e) { return Task.FromException(e); } } /// <summary> /// Destroys a savepoint previously defined in the current transaction. This allows the system to /// reclaim some resources before the transaction ends. /// </summary> /// <param name="savepointName">The name of the savepoint to release.</param> /// <param name="cancellationToken"> /// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None" />. /// </param> /// <returns>A <see cref="Task " /> representing the asynchronous operation.</returns> public virtual Task ReleaseAsync(string savepointName, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } try { Release(savepointName); return Task.CompletedTask; } catch (Exception e) { return Task.FromException(e); } } /// <summary> /// Creates a savepoint in the transaction. This allows all commands that are executed after the savepoint was /// established to be rolled back, restoring the transaction state to what it was at the time of the savepoint. /// </summary> /// <param name="savepointName">The name of the savepoint to be created.</param> public virtual void Save(string savepointName) => throw new NotSupportedException(); /// <summary> /// Rolls back all commands that were executed after the specified savepoint was established. /// </summary> /// <param name="savepointName">The name of the savepoint to roll back to.</param> public virtual void Rollback(string savepointName) => throw new NotSupportedException(); /// <summary> /// Destroys a savepoint previously defined in the current transaction. This allows the system to /// reclaim some resources before the transaction ends. /// </summary> /// <param name="savepointName">The name of the savepoint to release.</param> public virtual void Release(string savepointName) {} #endregion } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/coreclr/tools/Common/TypeSystem/Common/MetadataType.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 Internal.TypeSystem { /// <summary> /// Type with metadata available that is equivalent to a TypeDef record in an ECMA 335 metadata stream. /// A class, an interface, or a value type. /// </summary> public abstract partial class MetadataType : DefType { public abstract override string Name { get; } public abstract override string Namespace { get; } /// <summary> /// Gets metadata that controls instance layout of this type. /// </summary> public abstract ClassLayoutMetadata GetClassLayout(); /// <summary> /// If true, the type layout is dictated by the explicit layout rules provided. /// Corresponds to the definition of explicitlayout semantic defined in the ECMA-335 specification. /// </summary> public abstract bool IsExplicitLayout { get; } /// <summary> /// If true, the order of the fields needs to be preserved. Corresponds to the definition /// of sequentiallayout semantic defined in the ECMA-335 specification. /// </summary> public abstract bool IsSequentialLayout { get; } /// <summary> /// If true, the type initializer of this type has a relaxed semantic. Corresponds /// to the definition of beforefieldinit semantic defined in the ECMA-335 specification. /// </summary> public abstract bool IsBeforeFieldInit { get; } /// <summary> /// If true, this is the special &lt;Module&gt; type that contains the definitions /// of global fields and methods in the module. /// </summary> public virtual bool IsModuleType { get { return Module.GetGlobalModuleType() == this; } } /// <summary> /// Gets the module that defines this type. /// </summary> public abstract ModuleDesc Module { get; } /// <summary> /// Same as <see cref="TypeDesc.BaseType"/>, but the result is a MetadataType (avoids casting). /// </summary> public abstract MetadataType MetadataBaseType { get; } // Make sure children remember to override both MetadataBaseType and BaseType. public abstract override DefType BaseType { get; } /// <summary> /// If true, the type cannot be used as a base type of any other type. /// </summary> public abstract bool IsSealed { get; } /// <summary> /// Gets a value indicating whether the type is abstract and cannot be allocated. /// </summary> public abstract bool IsAbstract { get; } /// <summary> /// Returns true if the type has given custom attribute. /// </summary> public abstract bool HasCustomAttribute(string attributeNamespace, string attributeName); public abstract override DefType ContainingType { get; } /// <summary> /// Get all of the types nested in this type. /// </summary> public abstract IEnumerable<MetadataType> GetNestedTypes(); /// <summary> /// Get a specific type nested in this type. Returns null if the type /// doesn't exist. /// </summary> public abstract MetadataType GetNestedType(string name); } public struct ClassLayoutMetadata { public int PackingSize; public int Size; public FieldAndOffset[] Offsets; } public struct FieldAndOffset { public static readonly LayoutInt InvalidOffset = new LayoutInt(int.MaxValue); public readonly FieldDesc Field; public readonly LayoutInt Offset; public FieldAndOffset(FieldDesc field, LayoutInt offset) { Field = field; Offset = offset; } } }
// 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 Internal.TypeSystem { /// <summary> /// Type with metadata available that is equivalent to a TypeDef record in an ECMA 335 metadata stream. /// A class, an interface, or a value type. /// </summary> public abstract partial class MetadataType : DefType { public abstract override string Name { get; } public abstract override string Namespace { get; } /// <summary> /// Gets metadata that controls instance layout of this type. /// </summary> public abstract ClassLayoutMetadata GetClassLayout(); /// <summary> /// If true, the type layout is dictated by the explicit layout rules provided. /// Corresponds to the definition of explicitlayout semantic defined in the ECMA-335 specification. /// </summary> public abstract bool IsExplicitLayout { get; } /// <summary> /// If true, the order of the fields needs to be preserved. Corresponds to the definition /// of sequentiallayout semantic defined in the ECMA-335 specification. /// </summary> public abstract bool IsSequentialLayout { get; } /// <summary> /// If true, the type initializer of this type has a relaxed semantic. Corresponds /// to the definition of beforefieldinit semantic defined in the ECMA-335 specification. /// </summary> public abstract bool IsBeforeFieldInit { get; } /// <summary> /// If true, this is the special &lt;Module&gt; type that contains the definitions /// of global fields and methods in the module. /// </summary> public virtual bool IsModuleType { get { return Module.GetGlobalModuleType() == this; } } /// <summary> /// Gets the module that defines this type. /// </summary> public abstract ModuleDesc Module { get; } /// <summary> /// Same as <see cref="TypeDesc.BaseType"/>, but the result is a MetadataType (avoids casting). /// </summary> public abstract MetadataType MetadataBaseType { get; } // Make sure children remember to override both MetadataBaseType and BaseType. public abstract override DefType BaseType { get; } /// <summary> /// If true, the type cannot be used as a base type of any other type. /// </summary> public abstract bool IsSealed { get; } /// <summary> /// Gets a value indicating whether the type is abstract and cannot be allocated. /// </summary> public abstract bool IsAbstract { get; } /// <summary> /// Returns true if the type has given custom attribute. /// </summary> public abstract bool HasCustomAttribute(string attributeNamespace, string attributeName); public abstract override DefType ContainingType { get; } /// <summary> /// Get all of the types nested in this type. /// </summary> public abstract IEnumerable<MetadataType> GetNestedTypes(); /// <summary> /// Get a specific type nested in this type. Returns null if the type /// doesn't exist. /// </summary> public abstract MetadataType GetNestedType(string name); } public struct ClassLayoutMetadata { public int PackingSize; public int Size; public FieldAndOffset[] Offsets; } public struct FieldAndOffset { public static readonly LayoutInt InvalidOffset = new LayoutInt(int.MaxValue); public readonly FieldDesc Field; public readonly LayoutInt Offset; public FieldAndOffset(FieldDesc field, LayoutInt offset) { Field = field; Offset = offset; } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteVisitor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace Microsoft.Extensions.DependencyInjection.ServiceLookup { internal abstract class CallSiteVisitor<TArgument, TResult> { private readonly StackGuard _stackGuard; protected CallSiteVisitor() { _stackGuard = new StackGuard(); } protected virtual TResult VisitCallSite(ServiceCallSite callSite, TArgument argument) { if (!_stackGuard.TryEnterOnCurrentStack()) { return _stackGuard.RunOnEmptyStack((c, a) => VisitCallSite(c, a), callSite, argument); } switch (callSite.Cache.Location) { case CallSiteResultCacheLocation.Root: return VisitRootCache(callSite, argument); case CallSiteResultCacheLocation.Scope: return VisitScopeCache(callSite, argument); case CallSiteResultCacheLocation.Dispose: return VisitDisposeCache(callSite, argument); case CallSiteResultCacheLocation.None: return VisitNoCache(callSite, argument); default: throw new ArgumentOutOfRangeException(); } } protected virtual TResult VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) { switch (callSite.Kind) { case CallSiteKind.Factory: return VisitFactory((FactoryCallSite)callSite, argument); case CallSiteKind.IEnumerable: return VisitIEnumerable((IEnumerableCallSite)callSite, argument); case CallSiteKind.Constructor: return VisitConstructor((ConstructorCallSite)callSite, argument); case CallSiteKind.Constant: return VisitConstant((ConstantCallSite)callSite, argument); case CallSiteKind.ServiceProvider: return VisitServiceProvider((ServiceProviderCallSite)callSite, argument); default: throw new NotSupportedException(SR.Format(SR.CallSiteTypeNotSupported, callSite.GetType())); } } protected virtual TResult VisitNoCache(ServiceCallSite callSite, TArgument argument) { return VisitCallSiteMain(callSite, argument); } protected virtual TResult VisitDisposeCache(ServiceCallSite callSite, TArgument argument) { return VisitCallSiteMain(callSite, argument); } protected virtual TResult VisitRootCache(ServiceCallSite callSite, TArgument argument) { return VisitCallSiteMain(callSite, argument); } protected virtual TResult VisitScopeCache(ServiceCallSite callSite, TArgument argument) { return VisitCallSiteMain(callSite, argument); } protected abstract TResult VisitConstructor(ConstructorCallSite constructorCallSite, TArgument argument); protected abstract TResult VisitConstant(ConstantCallSite constantCallSite, TArgument argument); protected abstract TResult VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, TArgument argument); protected abstract TResult VisitIEnumerable(IEnumerableCallSite enumerableCallSite, TArgument argument); protected abstract TResult VisitFactory(FactoryCallSite factoryCallSite, TArgument argument); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace Microsoft.Extensions.DependencyInjection.ServiceLookup { internal abstract class CallSiteVisitor<TArgument, TResult> { private readonly StackGuard _stackGuard; protected CallSiteVisitor() { _stackGuard = new StackGuard(); } protected virtual TResult VisitCallSite(ServiceCallSite callSite, TArgument argument) { if (!_stackGuard.TryEnterOnCurrentStack()) { return _stackGuard.RunOnEmptyStack((c, a) => VisitCallSite(c, a), callSite, argument); } switch (callSite.Cache.Location) { case CallSiteResultCacheLocation.Root: return VisitRootCache(callSite, argument); case CallSiteResultCacheLocation.Scope: return VisitScopeCache(callSite, argument); case CallSiteResultCacheLocation.Dispose: return VisitDisposeCache(callSite, argument); case CallSiteResultCacheLocation.None: return VisitNoCache(callSite, argument); default: throw new ArgumentOutOfRangeException(); } } protected virtual TResult VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) { switch (callSite.Kind) { case CallSiteKind.Factory: return VisitFactory((FactoryCallSite)callSite, argument); case CallSiteKind.IEnumerable: return VisitIEnumerable((IEnumerableCallSite)callSite, argument); case CallSiteKind.Constructor: return VisitConstructor((ConstructorCallSite)callSite, argument); case CallSiteKind.Constant: return VisitConstant((ConstantCallSite)callSite, argument); case CallSiteKind.ServiceProvider: return VisitServiceProvider((ServiceProviderCallSite)callSite, argument); default: throw new NotSupportedException(SR.Format(SR.CallSiteTypeNotSupported, callSite.GetType())); } } protected virtual TResult VisitNoCache(ServiceCallSite callSite, TArgument argument) { return VisitCallSiteMain(callSite, argument); } protected virtual TResult VisitDisposeCache(ServiceCallSite callSite, TArgument argument) { return VisitCallSiteMain(callSite, argument); } protected virtual TResult VisitRootCache(ServiceCallSite callSite, TArgument argument) { return VisitCallSiteMain(callSite, argument); } protected virtual TResult VisitScopeCache(ServiceCallSite callSite, TArgument argument) { return VisitCallSiteMain(callSite, argument); } protected abstract TResult VisitConstructor(ConstructorCallSite constructorCallSite, TArgument argument); protected abstract TResult VisitConstant(ConstantCallSite constantCallSite, TArgument argument); protected abstract TResult VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, TArgument argument); protected abstract TResult VisitIEnumerable(IEnumerableCallSite enumerableCallSite, TArgument argument); protected abstract TResult VisitFactory(FactoryCallSite factoryCallSite, TArgument argument); } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/GC/Scenarios/THDList/thdlist.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /** * Description: * Mainly stresses the GC by creating n threads each manipulating its own local Linked List. * Each thread in turn adds and deletes thousands of nodes from the linked list. */ namespace ThdList { using System.Threading; using System; using System.IO; public class ThdList { public static int Main (System.String[] Args) { Console.Out.WriteLine("Test should return with ExitCode 100 ..."); // console synchronization Console.SetOut(TextWriter.Synchronized(Console.Out)); int iNofThread = 0; if (Args.Length == 1) { if (!Int32.TryParse( Args[0], out iNofThread )) { iNofThread = 2; } } else { iNofThread = 2; } LLThread Mv_LLThread; //Creates m_iNofThreads LLThread objects //Each LLThread then launches a thread in its constructor for (int i = 0; i < iNofThread; i++) { Mv_LLThread = new LLThread(i); } return 100; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /** * Description: * Mainly stresses the GC by creating n threads each manipulating its own local Linked List. * Each thread in turn adds and deletes thousands of nodes from the linked list. */ namespace ThdList { using System.Threading; using System; using System.IO; public class ThdList { public static int Main (System.String[] Args) { Console.Out.WriteLine("Test should return with ExitCode 100 ..."); // console synchronization Console.SetOut(TextWriter.Synchronized(Console.Out)); int iNofThread = 0; if (Args.Length == 1) { if (!Int32.TryParse( Args[0], out iNofThread )) { iNofThread = 2; } } else { iNofThread = 2; } LLThread Mv_LLThread; //Creates m_iNofThreads LLThread objects //Each LLThread then launches a thread in its constructor for (int i = 0; i < iNofThread; i++) { Mv_LLThread = new LLThread(i); } return 100; } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/Common/src/SkipLocalsInit.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Used to indicate to the compiler that the .locals init flag should not be set in method headers. [module: System.Runtime.CompilerServices.SkipLocalsInit]
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Used to indicate to the compiler that the .locals init flag should not be set in method headers. [module: System.Runtime.CompilerServices.SkipLocalsInit]
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextRaggedExclude.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Microsoft.Extensions.FileSystemGlobbing.Abstractions; namespace Microsoft.Extensions.FileSystemGlobbing.Internal.PatternContexts { public class PatternContextRaggedExclude : PatternContextRagged { public PatternContextRaggedExclude(IRaggedPattern pattern) : base(pattern) { } public override bool Test(DirectoryInfoBase directory) { if (IsStackEmpty()) { throw new InvalidOperationException(SR.CannotTestDirectory); } if (Frame.IsNotApplicable) { return false; } if (IsEndingGroup() && TestMatchingGroup(directory)) { // directory excluded with file-like pattern return true; } if (Pattern.EndsWith.Count == 0 && Frame.SegmentGroupIndex == Pattern.Contains.Count - 1 && TestMatchingGroup(directory)) { // directory excluded by matching up to final '/**' return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Microsoft.Extensions.FileSystemGlobbing.Abstractions; namespace Microsoft.Extensions.FileSystemGlobbing.Internal.PatternContexts { public class PatternContextRaggedExclude : PatternContextRagged { public PatternContextRaggedExclude(IRaggedPattern pattern) : base(pattern) { } public override bool Test(DirectoryInfoBase directory) { if (IsStackEmpty()) { throw new InvalidOperationException(SR.CannotTestDirectory); } if (Frame.IsNotApplicable) { return false; } if (IsEndingGroup() && TestMatchingGroup(directory)) { // directory excluded with file-like pattern return true; } if (Pattern.EndsWith.Count == 0 && Frame.SegmentGroupIndex == Pattern.Contains.Count - 1 && TestMatchingGroup(directory)) { // directory excluded by matching up to final '/**' return true; } return false; } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Memory/tests/ReadOnlySpan/Empty.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.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.SpanTests { public static partial class ReadOnlySpanTests { [Fact] public static void Empty() { ReadOnlySpan<int> empty = ReadOnlySpan<int>.Empty; Assert.True(empty.IsEmpty); Assert.Equal(0, empty.Length); unsafe { ref int expected = ref Unsafe.AsRef<int>(null); ref int actual = ref Unsafe.AsRef(in MemoryMarshal.GetReference(empty)); Assert.True(Unsafe.AreSame(ref expected, ref actual)); } } } }
// 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.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.SpanTests { public static partial class ReadOnlySpanTests { [Fact] public static void Empty() { ReadOnlySpan<int> empty = ReadOnlySpan<int>.Empty; Assert.True(empty.IsEmpty); Assert.Equal(0, empty.Length); unsafe { ref int expected = ref Unsafe.AsRef<int>(null); ref int actual = ref Unsafe.AsRef(in MemoryMarshal.GetReference(empty)); Assert.True(Unsafe.AreSame(ref expected, ref actual)); } } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Private.CoreLib/src/System/IO/TextReader.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; using System.Threading; using System.Threading.Tasks; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Buffers; namespace System.IO { // This abstract base class represents a reader that can read a sequential // stream of characters. This is not intended for reading bytes - // there are methods on the Stream class to read bytes. // A subclass must minimally implement the Peek() and Read() methods. // // This class is intended for character input, not bytes. // There are methods on the Stream class for reading bytes. public abstract partial class TextReader : MarshalByRefObject, IDisposable { // Create our own instance to avoid static field initialization order problems on Mono. public static readonly TextReader Null = new StreamReader.NullStreamReader(); protected TextReader() { } public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } // Returns the next available character without actually reading it from // the input stream. The current position of the TextReader is not changed by // this operation. The returned value is -1 if no further characters are // available. // // This default method simply returns -1. // public virtual int Peek() { return -1; } // Reads the next character from the input stream. The returned value is // -1 if no further characters are available. // // This default method simply returns -1. // public virtual int Read() { return -1; } // Reads a block of characters. This method will read up to // count characters from this TextReader into the // buffer character array starting at position // index. Returns the actual number of characters read. // public virtual int Read(char[] buffer!!, int index, int count) { if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } int n; for (n = 0; n < count; n++) { int ch = Read(); if (ch == -1) break; buffer[index + n] = (char)ch; } return n; } // Reads a span of characters. This method will read up to // count characters from this TextReader into the // span of characters Returns the actual number of characters read. // public virtual int Read(Span<char> buffer) { char[] array = ArrayPool<char>.Shared.Rent(buffer.Length); try { int numRead = Read(array, 0, buffer.Length); if ((uint)numRead > (uint)buffer.Length) { throw new IOException(SR.IO_InvalidReadLength); } new Span<char>(array, 0, numRead).CopyTo(buffer); return numRead; } finally { ArrayPool<char>.Shared.Return(array); } } // Reads all characters from the current position to the end of the // TextReader, and returns them as one string. public virtual string ReadToEnd() { char[] chars = new char[4096]; int len; StringBuilder sb = new StringBuilder(4096); while ((len = Read(chars, 0, chars.Length)) != 0) { sb.Append(chars, 0, len); } return sb.ToString(); } // Blocking version of read. Returns only when count // characters have been read or the end of the file was reached. // public virtual int ReadBlock(char[] buffer, int index, int count) { int i, n = 0; do { n += (i = Read(buffer, index + n, count - n)); } while (i > 0 && n < count); return n; } // Blocking version of read for span of characters. Returns only when count // characters have been read or the end of the file was reached. // public virtual int ReadBlock(Span<char> buffer) { char[] array = ArrayPool<char>.Shared.Rent(buffer.Length); try { int numRead = ReadBlock(array, 0, buffer.Length); if ((uint)numRead > (uint)buffer.Length) { throw new IOException(SR.IO_InvalidReadLength); } new Span<char>(array, 0, numRead).CopyTo(buffer); return numRead; } finally { ArrayPool<char>.Shared.Return(array); } } // Reads a line. A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the input stream has been reached. // public virtual string? ReadLine() { StringBuilder sb = new StringBuilder(); while (true) { int ch = Read(); if (ch == -1) break; if (ch == '\r' || ch == '\n') { if (ch == '\r' && Peek() == '\n') { Read(); } return sb.ToString(); } sb.Append((char)ch); } if (sb.Length > 0) { return sb.ToString(); } return null; } #region Task based Async APIs public virtual Task<string?> ReadLineAsync() => ReadLineCoreAsync(default); /// <summary> /// Reads a line of characters asynchronously and returns the data as a string. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A value task that represents the asynchronous read operation. The value of the <c>TResult</c> /// parameter contains the next line from the text reader, or is <see langword="null" /> if all of the characters have been read.</returns> /// <exception cref="ArgumentOutOfRangeException">The number of characters in the next line is larger than <see cref="int.MaxValue"/>.</exception> /// <exception cref="ObjectDisposedException">The text reader has been disposed.</exception> /// <exception cref="InvalidOperationException">The reader is currently in use by a previous read operation.</exception> /// <remarks> /// <para>The <see cref="TextReader"/> class is an abstract class. Therefore, you do not instantiate it in /// your code. For an example of using the <see cref="ReadLineAsync(CancellationToken)"/> method, see the /// <see cref="StreamReader.ReadLineAsync(CancellationToken)"/> method.</para> /// <para>If the current <see cref="TextReader"/> represents the standard input stream returned by /// the <c>Console.In</c> property, the <see cref="ReadLineAsync(CancellationToken)"/> method /// executes synchronously rather than asynchronously.</para> /// </remarks> public virtual ValueTask<string?> ReadLineAsync(CancellationToken cancellationToken) => new ValueTask<string?>(ReadLineCoreAsync(cancellationToken)); private Task<string?> ReadLineCoreAsync(CancellationToken cancellationToken) => Task<string?>.Factory.StartNew(static state => ((TextReader)state!).ReadLine(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); public virtual Task<string> ReadToEndAsync() => ReadToEndAsync(default); /// <summary> /// Reads all characters from the current position to the end of the text reader asynchronously and returns them as one string. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous read operation. The value of the <c>TResult</c> parameter contains /// a string with the characters from the current position to the end of the text reader.</returns> /// <exception cref="ArgumentOutOfRangeException">The number of characters is larger than <see cref="int.MaxValue"/>.</exception> /// <exception cref="ObjectDisposedException">The text reader has been disposed.</exception> /// <exception cref="InvalidOperationException">The reader is currently in use by a previous read operation.</exception> /// <remarks> /// <para>The <see cref="TextReader"/> class is an abstract class. Therefore, you do not instantiate it in /// your code. For an example of using the <see cref="ReadToEndAsync(CancellationToken)"/> method, see the /// <see cref="StreamReader.ReadToEndAsync(CancellationToken)"/> method.</para> /// </remarks> public virtual async Task<string> ReadToEndAsync(CancellationToken cancellationToken) { var sb = new StringBuilder(4096); char[] chars = ArrayPool<char>.Shared.Rent(4096); try { int len; while ((len = await ReadAsyncInternal(chars, cancellationToken).ConfigureAwait(false)) != 0) { sb.Append(chars, 0, len); } } finally { ArrayPool<char>.Shared.Return(chars); } return sb.ToString(); } public virtual Task<int> ReadAsync(char[] buffer!!, int index, int count) { if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return ReadAsyncInternal(new Memory<char>(buffer, index, count), default).AsTask(); } public virtual ValueTask<int> ReadAsync(Memory<char> buffer, CancellationToken cancellationToken = default) => new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ? ReadAsync(array.Array!, array.Offset, array.Count) : Task<int>.Factory.StartNew(static state => { var t = (TupleSlim<TextReader, Memory<char>>)state!; return t.Item1.Read(t.Item2.Span); }, new TupleSlim<TextReader, Memory<char>>(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); internal virtual ValueTask<int> ReadAsyncInternal(Memory<char> buffer, CancellationToken cancellationToken) => new ValueTask<int>(Task<int>.Factory.StartNew(static state => { var t = (TupleSlim<TextReader, Memory<char>>)state!; return t.Item1.Read(t.Item2.Span); }, new TupleSlim<TextReader, Memory<char>>(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); public virtual Task<int> ReadBlockAsync(char[] buffer!!, int index, int count) { if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return ReadBlockAsyncInternal(new Memory<char>(buffer, index, count), default).AsTask(); } public virtual ValueTask<int> ReadBlockAsync(Memory<char> buffer, CancellationToken cancellationToken = default) => new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ? ReadBlockAsync(array.Array!, array.Offset, array.Count) : Task<int>.Factory.StartNew(static state => { var t = (TupleSlim<TextReader, Memory<char>>)state!; return t.Item1.ReadBlock(t.Item2.Span); }, new TupleSlim<TextReader, Memory<char>>(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); internal async ValueTask<int> ReadBlockAsyncInternal(Memory<char> buffer, CancellationToken cancellationToken) { int n = 0, i; do { i = await ReadAsyncInternal(buffer.Slice(n), cancellationToken).ConfigureAwait(false); n += i; } while (i > 0 && n < buffer.Length); return n; } #endregion public static TextReader Synchronized(TextReader reader!!) { return reader is SyncTextReader ? reader : new SyncTextReader(reader); } internal sealed class SyncTextReader : TextReader { internal readonly TextReader _in; internal SyncTextReader(TextReader t) { _in = t; } [MethodImpl(MethodImplOptions.Synchronized)] public override void Close() => _in.Close(); [MethodImpl(MethodImplOptions.Synchronized)] protected override void Dispose(bool disposing) { // Explicitly pick up a potentially methodimpl'ed Dispose if (disposing) ((IDisposable)_in).Dispose(); } [MethodImpl(MethodImplOptions.Synchronized)] public override int Peek() => _in.Peek(); [MethodImpl(MethodImplOptions.Synchronized)] public override int Read() => _in.Read(); [MethodImpl(MethodImplOptions.Synchronized)] public override int Read(char[] buffer, int index, int count) => _in.Read(buffer, index, count); [MethodImpl(MethodImplOptions.Synchronized)] public override int ReadBlock(char[] buffer, int index, int count) => _in.ReadBlock(buffer, index, count); [MethodImpl(MethodImplOptions.Synchronized)] public override string? ReadLine() => _in.ReadLine(); [MethodImpl(MethodImplOptions.Synchronized)] public override string ReadToEnd() => _in.ReadToEnd(); // // On SyncTextReader all APIs should run synchronously, even the async ones. // [MethodImpl(MethodImplOptions.Synchronized)] public override Task<string?> ReadLineAsync() => Task.FromResult(ReadLine()); [MethodImpl(MethodImplOptions.Synchronized)] public override ValueTask<string?> ReadLineAsync(CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? ValueTask.FromCanceled<string?>(cancellationToken) : new ValueTask<string?>(ReadLine()); [MethodImpl(MethodImplOptions.Synchronized)] public override Task<string> ReadToEndAsync() => Task.FromResult(ReadToEnd()); [MethodImpl(MethodImplOptions.Synchronized)] public override Task<string> ReadToEndAsync(CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled<string>(cancellationToken) : Task.FromResult(ReadToEnd()); [MethodImpl(MethodImplOptions.Synchronized)] public override Task<int> ReadBlockAsync(char[] buffer!!, int index, int count) { if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); return Task.FromResult(ReadBlock(buffer, index, count)); } [MethodImpl(MethodImplOptions.Synchronized)] public override Task<int> ReadAsync(char[] buffer!!, int index, int count) { if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); return Task.FromResult(Read(buffer, index, count)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Text; using System.Threading; using System.Threading.Tasks; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Buffers; namespace System.IO { // This abstract base class represents a reader that can read a sequential // stream of characters. This is not intended for reading bytes - // there are methods on the Stream class to read bytes. // A subclass must minimally implement the Peek() and Read() methods. // // This class is intended for character input, not bytes. // There are methods on the Stream class for reading bytes. public abstract partial class TextReader : MarshalByRefObject, IDisposable { // Create our own instance to avoid static field initialization order problems on Mono. public static readonly TextReader Null = new StreamReader.NullStreamReader(); protected TextReader() { } public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } // Returns the next available character without actually reading it from // the input stream. The current position of the TextReader is not changed by // this operation. The returned value is -1 if no further characters are // available. // // This default method simply returns -1. // public virtual int Peek() { return -1; } // Reads the next character from the input stream. The returned value is // -1 if no further characters are available. // // This default method simply returns -1. // public virtual int Read() { return -1; } // Reads a block of characters. This method will read up to // count characters from this TextReader into the // buffer character array starting at position // index. Returns the actual number of characters read. // public virtual int Read(char[] buffer!!, int index, int count) { if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } int n; for (n = 0; n < count; n++) { int ch = Read(); if (ch == -1) break; buffer[index + n] = (char)ch; } return n; } // Reads a span of characters. This method will read up to // count characters from this TextReader into the // span of characters Returns the actual number of characters read. // public virtual int Read(Span<char> buffer) { char[] array = ArrayPool<char>.Shared.Rent(buffer.Length); try { int numRead = Read(array, 0, buffer.Length); if ((uint)numRead > (uint)buffer.Length) { throw new IOException(SR.IO_InvalidReadLength); } new Span<char>(array, 0, numRead).CopyTo(buffer); return numRead; } finally { ArrayPool<char>.Shared.Return(array); } } // Reads all characters from the current position to the end of the // TextReader, and returns them as one string. public virtual string ReadToEnd() { char[] chars = new char[4096]; int len; StringBuilder sb = new StringBuilder(4096); while ((len = Read(chars, 0, chars.Length)) != 0) { sb.Append(chars, 0, len); } return sb.ToString(); } // Blocking version of read. Returns only when count // characters have been read or the end of the file was reached. // public virtual int ReadBlock(char[] buffer, int index, int count) { int i, n = 0; do { n += (i = Read(buffer, index + n, count - n)); } while (i > 0 && n < count); return n; } // Blocking version of read for span of characters. Returns only when count // characters have been read or the end of the file was reached. // public virtual int ReadBlock(Span<char> buffer) { char[] array = ArrayPool<char>.Shared.Rent(buffer.Length); try { int numRead = ReadBlock(array, 0, buffer.Length); if ((uint)numRead > (uint)buffer.Length) { throw new IOException(SR.IO_InvalidReadLength); } new Span<char>(array, 0, numRead).CopyTo(buffer); return numRead; } finally { ArrayPool<char>.Shared.Return(array); } } // Reads a line. A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the input stream has been reached. // public virtual string? ReadLine() { StringBuilder sb = new StringBuilder(); while (true) { int ch = Read(); if (ch == -1) break; if (ch == '\r' || ch == '\n') { if (ch == '\r' && Peek() == '\n') { Read(); } return sb.ToString(); } sb.Append((char)ch); } if (sb.Length > 0) { return sb.ToString(); } return null; } #region Task based Async APIs public virtual Task<string?> ReadLineAsync() => ReadLineCoreAsync(default); /// <summary> /// Reads a line of characters asynchronously and returns the data as a string. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A value task that represents the asynchronous read operation. The value of the <c>TResult</c> /// parameter contains the next line from the text reader, or is <see langword="null" /> if all of the characters have been read.</returns> /// <exception cref="ArgumentOutOfRangeException">The number of characters in the next line is larger than <see cref="int.MaxValue"/>.</exception> /// <exception cref="ObjectDisposedException">The text reader has been disposed.</exception> /// <exception cref="InvalidOperationException">The reader is currently in use by a previous read operation.</exception> /// <remarks> /// <para>The <see cref="TextReader"/> class is an abstract class. Therefore, you do not instantiate it in /// your code. For an example of using the <see cref="ReadLineAsync(CancellationToken)"/> method, see the /// <see cref="StreamReader.ReadLineAsync(CancellationToken)"/> method.</para> /// <para>If the current <see cref="TextReader"/> represents the standard input stream returned by /// the <c>Console.In</c> property, the <see cref="ReadLineAsync(CancellationToken)"/> method /// executes synchronously rather than asynchronously.</para> /// </remarks> public virtual ValueTask<string?> ReadLineAsync(CancellationToken cancellationToken) => new ValueTask<string?>(ReadLineCoreAsync(cancellationToken)); private Task<string?> ReadLineCoreAsync(CancellationToken cancellationToken) => Task<string?>.Factory.StartNew(static state => ((TextReader)state!).ReadLine(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); public virtual Task<string> ReadToEndAsync() => ReadToEndAsync(default); /// <summary> /// Reads all characters from the current position to the end of the text reader asynchronously and returns them as one string. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous read operation. The value of the <c>TResult</c> parameter contains /// a string with the characters from the current position to the end of the text reader.</returns> /// <exception cref="ArgumentOutOfRangeException">The number of characters is larger than <see cref="int.MaxValue"/>.</exception> /// <exception cref="ObjectDisposedException">The text reader has been disposed.</exception> /// <exception cref="InvalidOperationException">The reader is currently in use by a previous read operation.</exception> /// <remarks> /// <para>The <see cref="TextReader"/> class is an abstract class. Therefore, you do not instantiate it in /// your code. For an example of using the <see cref="ReadToEndAsync(CancellationToken)"/> method, see the /// <see cref="StreamReader.ReadToEndAsync(CancellationToken)"/> method.</para> /// </remarks> public virtual async Task<string> ReadToEndAsync(CancellationToken cancellationToken) { var sb = new StringBuilder(4096); char[] chars = ArrayPool<char>.Shared.Rent(4096); try { int len; while ((len = await ReadAsyncInternal(chars, cancellationToken).ConfigureAwait(false)) != 0) { sb.Append(chars, 0, len); } } finally { ArrayPool<char>.Shared.Return(chars); } return sb.ToString(); } public virtual Task<int> ReadAsync(char[] buffer!!, int index, int count) { if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return ReadAsyncInternal(new Memory<char>(buffer, index, count), default).AsTask(); } public virtual ValueTask<int> ReadAsync(Memory<char> buffer, CancellationToken cancellationToken = default) => new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ? ReadAsync(array.Array!, array.Offset, array.Count) : Task<int>.Factory.StartNew(static state => { var t = (TupleSlim<TextReader, Memory<char>>)state!; return t.Item1.Read(t.Item2.Span); }, new TupleSlim<TextReader, Memory<char>>(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); internal virtual ValueTask<int> ReadAsyncInternal(Memory<char> buffer, CancellationToken cancellationToken) => new ValueTask<int>(Task<int>.Factory.StartNew(static state => { var t = (TupleSlim<TextReader, Memory<char>>)state!; return t.Item1.Read(t.Item2.Span); }, new TupleSlim<TextReader, Memory<char>>(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); public virtual Task<int> ReadBlockAsync(char[] buffer!!, int index, int count) { if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return ReadBlockAsyncInternal(new Memory<char>(buffer, index, count), default).AsTask(); } public virtual ValueTask<int> ReadBlockAsync(Memory<char> buffer, CancellationToken cancellationToken = default) => new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ? ReadBlockAsync(array.Array!, array.Offset, array.Count) : Task<int>.Factory.StartNew(static state => { var t = (TupleSlim<TextReader, Memory<char>>)state!; return t.Item1.ReadBlock(t.Item2.Span); }, new TupleSlim<TextReader, Memory<char>>(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); internal async ValueTask<int> ReadBlockAsyncInternal(Memory<char> buffer, CancellationToken cancellationToken) { int n = 0, i; do { i = await ReadAsyncInternal(buffer.Slice(n), cancellationToken).ConfigureAwait(false); n += i; } while (i > 0 && n < buffer.Length); return n; } #endregion public static TextReader Synchronized(TextReader reader!!) { return reader is SyncTextReader ? reader : new SyncTextReader(reader); } internal sealed class SyncTextReader : TextReader { internal readonly TextReader _in; internal SyncTextReader(TextReader t) { _in = t; } [MethodImpl(MethodImplOptions.Synchronized)] public override void Close() => _in.Close(); [MethodImpl(MethodImplOptions.Synchronized)] protected override void Dispose(bool disposing) { // Explicitly pick up a potentially methodimpl'ed Dispose if (disposing) ((IDisposable)_in).Dispose(); } [MethodImpl(MethodImplOptions.Synchronized)] public override int Peek() => _in.Peek(); [MethodImpl(MethodImplOptions.Synchronized)] public override int Read() => _in.Read(); [MethodImpl(MethodImplOptions.Synchronized)] public override int Read(char[] buffer, int index, int count) => _in.Read(buffer, index, count); [MethodImpl(MethodImplOptions.Synchronized)] public override int ReadBlock(char[] buffer, int index, int count) => _in.ReadBlock(buffer, index, count); [MethodImpl(MethodImplOptions.Synchronized)] public override string? ReadLine() => _in.ReadLine(); [MethodImpl(MethodImplOptions.Synchronized)] public override string ReadToEnd() => _in.ReadToEnd(); // // On SyncTextReader all APIs should run synchronously, even the async ones. // [MethodImpl(MethodImplOptions.Synchronized)] public override Task<string?> ReadLineAsync() => Task.FromResult(ReadLine()); [MethodImpl(MethodImplOptions.Synchronized)] public override ValueTask<string?> ReadLineAsync(CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? ValueTask.FromCanceled<string?>(cancellationToken) : new ValueTask<string?>(ReadLine()); [MethodImpl(MethodImplOptions.Synchronized)] public override Task<string> ReadToEndAsync() => Task.FromResult(ReadToEnd()); [MethodImpl(MethodImplOptions.Synchronized)] public override Task<string> ReadToEndAsync(CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled<string>(cancellationToken) : Task.FromResult(ReadToEnd()); [MethodImpl(MethodImplOptions.Synchronized)] public override Task<int> ReadBlockAsync(char[] buffer!!, int index, int count) { if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); return Task.FromResult(ReadBlock(buffer, index, count)); } [MethodImpl(MethodImplOptions.Synchronized)] public override Task<int> ReadAsync(char[] buffer!!, int index, int count) { if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); return Task.FromResult(Read(buffer, index, count)); } } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.ComponentModel/src/System/ComponentModel/CancelEventArgs.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.ComponentModel { /// <summary> /// EventArgs used to describe a cancel event. /// </summary> public class CancelEventArgs : EventArgs { /// <summary> /// Gets or sets a value indicating whether we should cancel the operation or not /// </summary> public bool Cancel { get; set; } /// <summary> /// Default constructor /// </summary> public CancelEventArgs() { } /// <summary> /// Helper constructor /// </summary> /// <param name="cancel"></param> public CancelEventArgs(bool cancel) => Cancel = cancel; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.ComponentModel { /// <summary> /// EventArgs used to describe a cancel event. /// </summary> public class CancelEventArgs : EventArgs { /// <summary> /// Gets or sets a value indicating whether we should cancel the operation or not /// </summary> public bool Cancel { get; set; } /// <summary> /// Default constructor /// </summary> public CancelEventArgs() { } /// <summary> /// Helper constructor /// </summary> /// <param name="cancel"></param> public CancelEventArgs(bool cancel) => Cancel = cancel; } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Private.CoreLib/src/System/IO/Path.Unix.NoniOS.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 { public static partial class Path { private static string DefaultTempPath => "/tmp/"; } }
// 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 { public static partial class Path { private static string DefaultTempPath => "/tmp/"; } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Enumerator.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.Collections.Immutable { public partial struct ImmutableArray<T> { /// <summary> /// An array enumerator. /// </summary> /// <remarks> /// It is important that this enumerator does NOT implement <see cref="IDisposable"/>. /// We want the iterator to inline when we do foreach and to not result in /// a try/finally frame in the client. /// </remarks> public struct Enumerator { /// <summary> /// The array being enumerated. /// </summary> private readonly T[] _array; /// <summary> /// The currently enumerated position. /// </summary> /// <value> /// -1 before the first call to <see cref="MoveNext"/>. /// >= this.array.Length after <see cref="MoveNext"/> returns false. /// </value> private int _index; /// <summary> /// Initializes a new instance of the <see cref="Enumerator"/> struct. /// </summary> /// <param name="array">The array to enumerate.</param> internal Enumerator(T[] array) { _array = array; _index = -1; } /// <summary> /// Gets the currently enumerated value. /// </summary> public T Current { get { // PERF: no need to do a range check, we already did in MoveNext. // if user did not call MoveNext or ignored its result (incorrect use) // they will still get an exception from the array access range check. return _array[_index]; } } /// <summary> /// Advances to the next value to be enumerated. /// </summary> /// <returns><c>true</c> if another item exists in the array; <c>false</c> otherwise.</returns> public bool MoveNext() { return ++_index < _array.Length; } } /// <summary> /// An array enumerator that implements <see cref="IEnumerator{T}"/> pattern (including <see cref="IDisposable"/>). /// </summary> private sealed class EnumeratorObject : IEnumerator<T> { /// <summary> /// A shareable singleton for enumerating empty arrays. /// </summary> private static readonly IEnumerator<T> s_EmptyEnumerator = new EnumeratorObject(ImmutableArray<T>.Empty.array!); /// <summary> /// The array being enumerated. /// </summary> private readonly T[] _array; /// <summary> /// The currently enumerated position. /// </summary> /// <value> /// -1 before the first call to <see cref="MoveNext"/>. /// this.array.Length - 1 after MoveNext returns false. /// </value> private int _index; /// <summary> /// Initializes a new instance of the <see cref="Enumerator"/> class. /// </summary> private EnumeratorObject(T[] array) { _index = -1; _array = array; } /// <summary> /// Gets the currently enumerated value. /// </summary> public T Current { get { // this.index >= 0 && this.index < this.array.Length // unsigned compare performs the range check above in one compare if (unchecked((uint)_index) < (uint)_array.Length) { return _array[_index]; } // Before first or after last MoveNext. throw new InvalidOperationException(); } } /// <summary> /// Gets the currently enumerated value. /// </summary> object? IEnumerator.Current { get { return this.Current; } } /// <summary> /// If another item exists in the array, advances to the next value to be enumerated. /// </summary> /// <returns><c>true</c> if another item exists in the array; <c>false</c> otherwise.</returns> public bool MoveNext() { int newIndex = _index + 1; int length = _array.Length; // unsigned math is used to prevent false positive if index + 1 overflows. if ((uint)newIndex <= (uint)length) { _index = newIndex; return (uint)newIndex < (uint)length; } return false; } /// <summary> /// Resets enumeration to the start of the array. /// </summary> void IEnumerator.Reset() { _index = -1; } /// <summary> /// Disposes this enumerator. /// </summary> /// <remarks> /// Currently has no action. /// </remarks> public void Dispose() { // we do not have any native or disposable resources. // nothing to do here. } /// <summary> /// Creates an enumerator for the specified array. /// </summary> internal static IEnumerator<T> Create(T[] array) { if (array.Length != 0) { return new EnumeratorObject(array); } else { return s_EmptyEnumerator; } } } } }
// 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.Collections.Immutable { public partial struct ImmutableArray<T> { /// <summary> /// An array enumerator. /// </summary> /// <remarks> /// It is important that this enumerator does NOT implement <see cref="IDisposable"/>. /// We want the iterator to inline when we do foreach and to not result in /// a try/finally frame in the client. /// </remarks> public struct Enumerator { /// <summary> /// The array being enumerated. /// </summary> private readonly T[] _array; /// <summary> /// The currently enumerated position. /// </summary> /// <value> /// -1 before the first call to <see cref="MoveNext"/>. /// >= this.array.Length after <see cref="MoveNext"/> returns false. /// </value> private int _index; /// <summary> /// Initializes a new instance of the <see cref="Enumerator"/> struct. /// </summary> /// <param name="array">The array to enumerate.</param> internal Enumerator(T[] array) { _array = array; _index = -1; } /// <summary> /// Gets the currently enumerated value. /// </summary> public T Current { get { // PERF: no need to do a range check, we already did in MoveNext. // if user did not call MoveNext or ignored its result (incorrect use) // they will still get an exception from the array access range check. return _array[_index]; } } /// <summary> /// Advances to the next value to be enumerated. /// </summary> /// <returns><c>true</c> if another item exists in the array; <c>false</c> otherwise.</returns> public bool MoveNext() { return ++_index < _array.Length; } } /// <summary> /// An array enumerator that implements <see cref="IEnumerator{T}"/> pattern (including <see cref="IDisposable"/>). /// </summary> private sealed class EnumeratorObject : IEnumerator<T> { /// <summary> /// A shareable singleton for enumerating empty arrays. /// </summary> private static readonly IEnumerator<T> s_EmptyEnumerator = new EnumeratorObject(ImmutableArray<T>.Empty.array!); /// <summary> /// The array being enumerated. /// </summary> private readonly T[] _array; /// <summary> /// The currently enumerated position. /// </summary> /// <value> /// -1 before the first call to <see cref="MoveNext"/>. /// this.array.Length - 1 after MoveNext returns false. /// </value> private int _index; /// <summary> /// Initializes a new instance of the <see cref="Enumerator"/> class. /// </summary> private EnumeratorObject(T[] array) { _index = -1; _array = array; } /// <summary> /// Gets the currently enumerated value. /// </summary> public T Current { get { // this.index >= 0 && this.index < this.array.Length // unsigned compare performs the range check above in one compare if (unchecked((uint)_index) < (uint)_array.Length) { return _array[_index]; } // Before first or after last MoveNext. throw new InvalidOperationException(); } } /// <summary> /// Gets the currently enumerated value. /// </summary> object? IEnumerator.Current { get { return this.Current; } } /// <summary> /// If another item exists in the array, advances to the next value to be enumerated. /// </summary> /// <returns><c>true</c> if another item exists in the array; <c>false</c> otherwise.</returns> public bool MoveNext() { int newIndex = _index + 1; int length = _array.Length; // unsigned math is used to prevent false positive if index + 1 overflows. if ((uint)newIndex <= (uint)length) { _index = newIndex; return (uint)newIndex < (uint)length; } return false; } /// <summary> /// Resets enumeration to the start of the array. /// </summary> void IEnumerator.Reset() { _index = -1; } /// <summary> /// Disposes this enumerator. /// </summary> /// <remarks> /// Currently has no action. /// </remarks> public void Dispose() { // we do not have any native or disposable resources. // nothing to do here. } /// <summary> /// Creates an enumerator for the specified array. /// </summary> internal static IEnumerator<T> Create(T[] array) { if (array.Length != 0) { return new EnumeratorObject(array); } else { return s_EmptyEnumerator; } } } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/Regression/JitBlue/DevDiv_714266/DevDiv_714266.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Numerics; using System.Runtime.CompilerServices; // Based on DevDiv_714266, the issue reporoduced with JitStressRegs=0x1. // `minRegCandidateCount` for `RefTypeUpperVectorSaveDef` did not count one temporary register // that it used for the save. So if we had a call that did not require any registers (no defs/uses) // then we set `minRegCandidateCount = 0`for `RefTypeUpperVectorSaveDef` `refPosition` // and was not able to find a register for do the saving. class DevDiv_714266 { [MethodImpl(MethodImplOptions.NoInlining)] public static void CallWithoutUsesAndDefs() { } [MethodImpl(MethodImplOptions.NoInlining)] public static void MethodWithManyLiveVectors() { Vector<float> v = new Vector<float>(); Vector<float> v0 = -v; Vector<float> v1 = -v; Vector<float> v2 = -v; Vector<float> v3 = -v; Vector<float> v4 = -v; Vector<float> v5 = -v; Vector<float> v6 = -v; Vector<float> v7 = -v; Vector<float> v8 = -v; Vector<float> v9 = -v; CallWithoutUsesAndDefs(); GC.KeepAlive(new object[10] { v1, v2, v3, v4, v5, v6, v7, v8, v9, v0 }); } static int Main() { MethodWithManyLiveVectors(); 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.Numerics; using System.Runtime.CompilerServices; // Based on DevDiv_714266, the issue reporoduced with JitStressRegs=0x1. // `minRegCandidateCount` for `RefTypeUpperVectorSaveDef` did not count one temporary register // that it used for the save. So if we had a call that did not require any registers (no defs/uses) // then we set `minRegCandidateCount = 0`for `RefTypeUpperVectorSaveDef` `refPosition` // and was not able to find a register for do the saving. class DevDiv_714266 { [MethodImpl(MethodImplOptions.NoInlining)] public static void CallWithoutUsesAndDefs() { } [MethodImpl(MethodImplOptions.NoInlining)] public static void MethodWithManyLiveVectors() { Vector<float> v = new Vector<float>(); Vector<float> v0 = -v; Vector<float> v1 = -v; Vector<float> v2 = -v; Vector<float> v3 = -v; Vector<float> v4 = -v; Vector<float> v5 = -v; Vector<float> v6 = -v; Vector<float> v7 = -v; Vector<float> v8 = -v; Vector<float> v9 = -v; CallWithoutUsesAndDefs(); GC.KeepAlive(new object[10] { v1, v2, v3, v4, v5, v6, v7, v8, v9, v0 }); } static int Main() { MethodWithManyLiveVectors(); return 100; } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.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.Schema; using System.Xml.XPath; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Diagnostics.CodeAnalysis; namespace System.Xml { // Represents an element. public class XmlElement : XmlLinkedNode { private XmlName _name; private XmlAttributeCollection? _attributes; private XmlLinkedNode? _lastChild; // == this for empty elements otherwise it is the last child internal XmlElement(XmlName name, bool empty, XmlDocument doc) : base(doc) { Debug.Assert(name != null); this.parentNode = null; if (!doc.IsLoading) { XmlDocument.CheckName(name.Prefix); XmlDocument.CheckName(name.LocalName); } if (name.LocalName.Length == 0) throw new ArgumentException(SR.Xdom_Empty_LocalName); _name = name; if (empty) { _lastChild = this; } } protected internal XmlElement(string prefix, string localName, string? namespaceURI, XmlDocument doc) : this(doc.AddXmlName(prefix, localName, namespaceURI, null), true, doc) { } internal XmlName XmlName { get { return _name; } set { _name = value; } } // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { Debug.Assert(OwnerDocument != null); XmlDocument doc = OwnerDocument; bool OrigLoadingStatus = doc.IsLoading; doc.IsLoading = true; XmlElement element = doc.CreateElement(Prefix, LocalName, NamespaceURI); doc.IsLoading = OrigLoadingStatus; if (element.IsEmpty != this.IsEmpty) element.IsEmpty = this.IsEmpty; if (HasAttributes) { foreach (XmlAttribute attr in Attributes) { XmlAttribute newAttr = (XmlAttribute)(attr.CloneNode(true)); XmlUnspecifiedAttribute? unspecAttr = newAttr as XmlUnspecifiedAttribute; if (unspecAttr != null && attr.Specified == false) { unspecAttr.SetSpecified(false); } element.Attributes.InternalAppendAttribute(newAttr); } } if (deep) element.CopyChildren(doc, this, deep); return element; } // Gets the name of the node. public override string Name { get { return _name.Name; } } // Gets the name of the current node without the namespace prefix. public override string LocalName { get { return _name.LocalName; } } // Gets the namespace URI of this node. public override string NamespaceURI { get { return _name.NamespaceURI; } } // Gets or sets the namespace prefix of this node. public override string Prefix { get { return _name.Prefix; } set { _name = _name.OwnerDocument.AddXmlName(value, LocalName, NamespaceURI, SchemaInfo); } } // Gets the type of the current node. public override XmlNodeType NodeType { get { return XmlNodeType.Element; } } public override XmlNode? ParentNode { get { return this.parentNode; } } // Gets the XmlDocument that contains this node. public override XmlDocument OwnerDocument { get { return _name.OwnerDocument; } } internal override bool IsContainer { get { return true; } } //the function is provided only at Load time to speed up Load process internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { XmlNodeChangedEventArgs? args = doc.GetInsertEventArgsForLoad(newChild, this); if (args != null) doc.BeforeEvent(args); XmlLinkedNode newNode = (XmlLinkedNode)newChild; if (_lastChild == null || _lastChild == this) { // if LastNode == null newNode.next = newNode; _lastChild = newNode; // LastNode = newNode; newNode.SetParentForLoad(this); } else { XmlLinkedNode refNode = _lastChild; // refNode = LastNode; newNode.next = refNode.next; refNode.next = newNode; _lastChild = newNode; // LastNode = newNode; if (refNode.IsText && newNode.IsText) { NestTextNodes(refNode, newNode); } else { newNode.SetParentForLoad(this); } } if (args != null) doc.AfterEvent(args); return newNode; } // Gets or sets whether the element does not have any children. public bool IsEmpty { get { return _lastChild == this; } set { if (value) { if (_lastChild != this) { RemoveAllChildren(); _lastChild = this; } } else { if (_lastChild == this) { _lastChild = null; } } } } internal override XmlLinkedNode? LastNode { get { return _lastChild == this ? null : _lastChild; } set { _lastChild = value; } } internal override bool IsValidChildType(XmlNodeType type) { switch (type) { case XmlNodeType.Element: case XmlNodeType.Text: case XmlNodeType.EntityReference: case XmlNodeType.Comment: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.ProcessingInstruction: case XmlNodeType.CDATA: return true; default: return false; } } // Gets a XmlAttributeCollection containing the list of attributes for this node. public override XmlAttributeCollection Attributes { get { if (_attributes == null) { lock (OwnerDocument.objLock) { if (_attributes == null) { _attributes = new XmlAttributeCollection(this); } } } return _attributes; } } // Gets a value indicating whether the current node // has any attributes. public virtual bool HasAttributes { get { if (_attributes == null) return false; else return _attributes.Count > 0; } } // Returns the value for the attribute with the specified name. public virtual string GetAttribute(string name) { XmlAttribute? attr = GetAttributeNode(name); if (attr != null) return attr.Value; return string.Empty; } // Sets the value of the attribute // with the specified name. public virtual void SetAttribute(string name, string? value) { XmlAttribute? attr = GetAttributeNode(name); if (attr == null) { attr = OwnerDocument.CreateAttribute(name); attr.Value = value; Attributes.InternalAppendAttribute(attr); } else { attr.Value = value; } } // Removes an attribute by name. public virtual void RemoveAttribute(string name) { if (HasAttributes) Attributes.RemoveNamedItem(name); } // Returns the XmlAttribute with the specified name. public virtual XmlAttribute? GetAttributeNode(string name) { if (HasAttributes) return Attributes[name]; return null; } // Adds the specified XmlAttribute. public virtual XmlAttribute? SetAttributeNode(XmlAttribute newAttr) { if (newAttr.OwnerElement != null) throw new InvalidOperationException(SR.Xdom_Attr_InUse); return (XmlAttribute)Attributes.SetNamedItem(newAttr); } // Removes the specified XmlAttribute. public virtual XmlAttribute? RemoveAttributeNode(XmlAttribute oldAttr) { if (HasAttributes) return (XmlAttribute?)Attributes.Remove(oldAttr); return null; } // Returns a XmlNodeList containing // a list of all descendant elements that match the specified name. public virtual XmlNodeList GetElementsByTagName(string name) { return new XmlElementList(this, name); } // // DOM Level 2 // // Returns the value for the attribute with the specified LocalName and NamespaceURI. public virtual string GetAttribute(string localName, string? namespaceURI) { XmlAttribute? attr = GetAttributeNode(localName, namespaceURI); if (attr != null) return attr.Value; return string.Empty; } // Sets the value of the attribute with the specified name // and namespace. [return: NotNullIfNotNull("value")] public virtual string? SetAttribute(string localName, string? namespaceURI, string? value) { XmlAttribute? attr = GetAttributeNode(localName, namespaceURI); if (attr == null) { attr = OwnerDocument.CreateAttribute(string.Empty, localName, namespaceURI); attr.Value = value; Attributes.InternalAppendAttribute(attr); } else { attr.Value = value; } return value; } // Removes an attribute specified by LocalName and NamespaceURI. public virtual void RemoveAttribute(string localName, string? namespaceURI) { RemoveAttributeNode(localName, namespaceURI); } // Returns the XmlAttribute with the specified LocalName and NamespaceURI. public virtual XmlAttribute? GetAttributeNode(string localName, string? namespaceURI) { if (HasAttributes) return Attributes[localName, namespaceURI]; return null; } // Adds the specified XmlAttribute. public virtual XmlAttribute SetAttributeNode(string localName, string? namespaceURI) { XmlAttribute? attr = GetAttributeNode(localName, namespaceURI); if (attr == null) { attr = OwnerDocument.CreateAttribute(string.Empty, localName, namespaceURI); Attributes.InternalAppendAttribute(attr); } return attr; } // Removes the XmlAttribute specified by LocalName and NamespaceURI. public virtual XmlAttribute? RemoveAttributeNode(string localName, string? namespaceURI) { if (HasAttributes) { XmlAttribute? attr = GetAttributeNode(localName, namespaceURI); Attributes.Remove(attr); return attr; } return null; } // Returns a XmlNodeList containing // a list of all descendant elements that match the specified name. public virtual XmlNodeList GetElementsByTagName(string localName, string namespaceURI) { return new XmlElementList(this, localName, namespaceURI); } // Determines whether the current node has the specified attribute. public virtual bool HasAttribute(string name) { return GetAttributeNode(name) != null; } // Determines whether the current node has the specified // attribute from the specified namespace. public virtual bool HasAttribute(string localName, string? namespaceURI) { return GetAttributeNode(localName, namespaceURI) != null; } // Saves the current node to the specified XmlWriter. public override void WriteTo(XmlWriter w) { if (GetType() == typeof(XmlElement)) { // Use the non-recursive version (for XmlElement only) WriteElementTo(w, this); } else { // Use the (potentially) recursive version WriteStartElement(w); if (IsEmpty) { w.WriteEndElement(); } else { WriteContentTo(w); w.WriteFullEndElement(); } } } // This method is copied from System.Xml.Linq.ElementWriter.WriteElement but adapted to DOM private static void WriteElementTo(XmlWriter writer, XmlElement el) { XmlElement? e = el; XmlNode root = e; XmlNode? n = e; while (true) { e = n as XmlElement; // Only use the inlined write logic for XmlElement, not for derived classes if (e != null && e.GetType() == typeof(XmlElement)) { // Write the element e.WriteStartElement(writer); // Write the element's content if (e.IsEmpty) { // No content; use a short end element <a /> writer.WriteEndElement(); } else if (e._lastChild == null) { // No actual content; use a full end element <a></a> writer.WriteFullEndElement(); } else { // There are child node(s); move to first child n = e.FirstChild; Debug.Assert(n != null); continue; } } else { // Use virtual dispatch (might recurse) n.WriteTo(writer); } // Go back to the parent after writing the last child while (n != root && n == n.ParentNode!.LastChild) { n = n.ParentNode; Debug.Assert(n != null); writer.WriteFullEndElement(); } if (n == root) break; n = n.NextSibling; Debug.Assert(n != null); } } // Writes the start of the element (and its attributes) to the specified writer private void WriteStartElement(XmlWriter w) { w.WriteStartElement(Prefix, LocalName, NamespaceURI); if (HasAttributes) { XmlAttributeCollection attrs = Attributes; for (int i = 0; i < attrs.Count; i += 1) { XmlAttribute attr = attrs[i]; attr.WriteTo(w); } } } // Saves all the children of the node to the specified XmlWriter. public override void WriteContentTo(XmlWriter w) { for (XmlNode? node = FirstChild; node != null; node = node.NextSibling) { node.WriteTo(w); } } // Removes the attribute node with the specified index from the attribute collection. public virtual XmlNode? RemoveAttributeAt(int i) { if (HasAttributes) return _attributes!.RemoveAt(i); return null; } // Removes all attributes from the element. public virtual void RemoveAllAttributes() { if (HasAttributes) { _attributes!.RemoveAll(); } } // Removes all the children and/or attributes // of the current node. public override void RemoveAll() { //remove all the children base.RemoveAll(); //remove all the attributes RemoveAllAttributes(); } internal void RemoveAllChildren() { base.RemoveAll(); } public override IXmlSchemaInfo SchemaInfo { get { return _name; } } // Gets or sets the markup representing just // the children of this node. public override string InnerXml { get { return base.InnerXml; } set { RemoveAllChildren(); XmlLoader loader = new XmlLoader(); loader.LoadInnerXmlElement(this, value); } } // Gets or sets the concatenated values of the // node and all its children. public override string InnerText { get { return base.InnerText; } set { XmlLinkedNode? linkedNode = LastNode; if (linkedNode != null && //there is one child linkedNode.NodeType == XmlNodeType.Text && //which is text node linkedNode.next == linkedNode) // and it is the only child { //this branch is for perf reason, event fired when TextNode.Value is changed. linkedNode.Value = value; } else { RemoveAllChildren(); AppendChild(OwnerDocument.CreateTextNode(value)); } } } public override XmlNode? NextSibling { get { if (this.parentNode != null && this.parentNode.LastNode != this) return next; return null; } } internal override void SetParent(XmlNode? node) { this.parentNode = node; } internal override XPathNodeType XPNodeType { get { return XPathNodeType.Element; } } internal override string XPLocalName { get { return LocalName; } } internal override string GetXPAttribute(string localName, string ns) { if (ns == OwnerDocument.strReservedXmlns) return string.Empty; XmlAttribute? attr = GetAttributeNode(localName, ns); if (attr != null) return attr.Value; return 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.Xml.Schema; using System.Xml.XPath; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Diagnostics.CodeAnalysis; namespace System.Xml { // Represents an element. public class XmlElement : XmlLinkedNode { private XmlName _name; private XmlAttributeCollection? _attributes; private XmlLinkedNode? _lastChild; // == this for empty elements otherwise it is the last child internal XmlElement(XmlName name, bool empty, XmlDocument doc) : base(doc) { Debug.Assert(name != null); this.parentNode = null; if (!doc.IsLoading) { XmlDocument.CheckName(name.Prefix); XmlDocument.CheckName(name.LocalName); } if (name.LocalName.Length == 0) throw new ArgumentException(SR.Xdom_Empty_LocalName); _name = name; if (empty) { _lastChild = this; } } protected internal XmlElement(string prefix, string localName, string? namespaceURI, XmlDocument doc) : this(doc.AddXmlName(prefix, localName, namespaceURI, null), true, doc) { } internal XmlName XmlName { get { return _name; } set { _name = value; } } // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { Debug.Assert(OwnerDocument != null); XmlDocument doc = OwnerDocument; bool OrigLoadingStatus = doc.IsLoading; doc.IsLoading = true; XmlElement element = doc.CreateElement(Prefix, LocalName, NamespaceURI); doc.IsLoading = OrigLoadingStatus; if (element.IsEmpty != this.IsEmpty) element.IsEmpty = this.IsEmpty; if (HasAttributes) { foreach (XmlAttribute attr in Attributes) { XmlAttribute newAttr = (XmlAttribute)(attr.CloneNode(true)); XmlUnspecifiedAttribute? unspecAttr = newAttr as XmlUnspecifiedAttribute; if (unspecAttr != null && attr.Specified == false) { unspecAttr.SetSpecified(false); } element.Attributes.InternalAppendAttribute(newAttr); } } if (deep) element.CopyChildren(doc, this, deep); return element; } // Gets the name of the node. public override string Name { get { return _name.Name; } } // Gets the name of the current node without the namespace prefix. public override string LocalName { get { return _name.LocalName; } } // Gets the namespace URI of this node. public override string NamespaceURI { get { return _name.NamespaceURI; } } // Gets or sets the namespace prefix of this node. public override string Prefix { get { return _name.Prefix; } set { _name = _name.OwnerDocument.AddXmlName(value, LocalName, NamespaceURI, SchemaInfo); } } // Gets the type of the current node. public override XmlNodeType NodeType { get { return XmlNodeType.Element; } } public override XmlNode? ParentNode { get { return this.parentNode; } } // Gets the XmlDocument that contains this node. public override XmlDocument OwnerDocument { get { return _name.OwnerDocument; } } internal override bool IsContainer { get { return true; } } //the function is provided only at Load time to speed up Load process internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { XmlNodeChangedEventArgs? args = doc.GetInsertEventArgsForLoad(newChild, this); if (args != null) doc.BeforeEvent(args); XmlLinkedNode newNode = (XmlLinkedNode)newChild; if (_lastChild == null || _lastChild == this) { // if LastNode == null newNode.next = newNode; _lastChild = newNode; // LastNode = newNode; newNode.SetParentForLoad(this); } else { XmlLinkedNode refNode = _lastChild; // refNode = LastNode; newNode.next = refNode.next; refNode.next = newNode; _lastChild = newNode; // LastNode = newNode; if (refNode.IsText && newNode.IsText) { NestTextNodes(refNode, newNode); } else { newNode.SetParentForLoad(this); } } if (args != null) doc.AfterEvent(args); return newNode; } // Gets or sets whether the element does not have any children. public bool IsEmpty { get { return _lastChild == this; } set { if (value) { if (_lastChild != this) { RemoveAllChildren(); _lastChild = this; } } else { if (_lastChild == this) { _lastChild = null; } } } } internal override XmlLinkedNode? LastNode { get { return _lastChild == this ? null : _lastChild; } set { _lastChild = value; } } internal override bool IsValidChildType(XmlNodeType type) { switch (type) { case XmlNodeType.Element: case XmlNodeType.Text: case XmlNodeType.EntityReference: case XmlNodeType.Comment: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.ProcessingInstruction: case XmlNodeType.CDATA: return true; default: return false; } } // Gets a XmlAttributeCollection containing the list of attributes for this node. public override XmlAttributeCollection Attributes { get { if (_attributes == null) { lock (OwnerDocument.objLock) { if (_attributes == null) { _attributes = new XmlAttributeCollection(this); } } } return _attributes; } } // Gets a value indicating whether the current node // has any attributes. public virtual bool HasAttributes { get { if (_attributes == null) return false; else return _attributes.Count > 0; } } // Returns the value for the attribute with the specified name. public virtual string GetAttribute(string name) { XmlAttribute? attr = GetAttributeNode(name); if (attr != null) return attr.Value; return string.Empty; } // Sets the value of the attribute // with the specified name. public virtual void SetAttribute(string name, string? value) { XmlAttribute? attr = GetAttributeNode(name); if (attr == null) { attr = OwnerDocument.CreateAttribute(name); attr.Value = value; Attributes.InternalAppendAttribute(attr); } else { attr.Value = value; } } // Removes an attribute by name. public virtual void RemoveAttribute(string name) { if (HasAttributes) Attributes.RemoveNamedItem(name); } // Returns the XmlAttribute with the specified name. public virtual XmlAttribute? GetAttributeNode(string name) { if (HasAttributes) return Attributes[name]; return null; } // Adds the specified XmlAttribute. public virtual XmlAttribute? SetAttributeNode(XmlAttribute newAttr) { if (newAttr.OwnerElement != null) throw new InvalidOperationException(SR.Xdom_Attr_InUse); return (XmlAttribute)Attributes.SetNamedItem(newAttr); } // Removes the specified XmlAttribute. public virtual XmlAttribute? RemoveAttributeNode(XmlAttribute oldAttr) { if (HasAttributes) return (XmlAttribute?)Attributes.Remove(oldAttr); return null; } // Returns a XmlNodeList containing // a list of all descendant elements that match the specified name. public virtual XmlNodeList GetElementsByTagName(string name) { return new XmlElementList(this, name); } // // DOM Level 2 // // Returns the value for the attribute with the specified LocalName and NamespaceURI. public virtual string GetAttribute(string localName, string? namespaceURI) { XmlAttribute? attr = GetAttributeNode(localName, namespaceURI); if (attr != null) return attr.Value; return string.Empty; } // Sets the value of the attribute with the specified name // and namespace. [return: NotNullIfNotNull("value")] public virtual string? SetAttribute(string localName, string? namespaceURI, string? value) { XmlAttribute? attr = GetAttributeNode(localName, namespaceURI); if (attr == null) { attr = OwnerDocument.CreateAttribute(string.Empty, localName, namespaceURI); attr.Value = value; Attributes.InternalAppendAttribute(attr); } else { attr.Value = value; } return value; } // Removes an attribute specified by LocalName and NamespaceURI. public virtual void RemoveAttribute(string localName, string? namespaceURI) { RemoveAttributeNode(localName, namespaceURI); } // Returns the XmlAttribute with the specified LocalName and NamespaceURI. public virtual XmlAttribute? GetAttributeNode(string localName, string? namespaceURI) { if (HasAttributes) return Attributes[localName, namespaceURI]; return null; } // Adds the specified XmlAttribute. public virtual XmlAttribute SetAttributeNode(string localName, string? namespaceURI) { XmlAttribute? attr = GetAttributeNode(localName, namespaceURI); if (attr == null) { attr = OwnerDocument.CreateAttribute(string.Empty, localName, namespaceURI); Attributes.InternalAppendAttribute(attr); } return attr; } // Removes the XmlAttribute specified by LocalName and NamespaceURI. public virtual XmlAttribute? RemoveAttributeNode(string localName, string? namespaceURI) { if (HasAttributes) { XmlAttribute? attr = GetAttributeNode(localName, namespaceURI); Attributes.Remove(attr); return attr; } return null; } // Returns a XmlNodeList containing // a list of all descendant elements that match the specified name. public virtual XmlNodeList GetElementsByTagName(string localName, string namespaceURI) { return new XmlElementList(this, localName, namespaceURI); } // Determines whether the current node has the specified attribute. public virtual bool HasAttribute(string name) { return GetAttributeNode(name) != null; } // Determines whether the current node has the specified // attribute from the specified namespace. public virtual bool HasAttribute(string localName, string? namespaceURI) { return GetAttributeNode(localName, namespaceURI) != null; } // Saves the current node to the specified XmlWriter. public override void WriteTo(XmlWriter w) { if (GetType() == typeof(XmlElement)) { // Use the non-recursive version (for XmlElement only) WriteElementTo(w, this); } else { // Use the (potentially) recursive version WriteStartElement(w); if (IsEmpty) { w.WriteEndElement(); } else { WriteContentTo(w); w.WriteFullEndElement(); } } } // This method is copied from System.Xml.Linq.ElementWriter.WriteElement but adapted to DOM private static void WriteElementTo(XmlWriter writer, XmlElement el) { XmlElement? e = el; XmlNode root = e; XmlNode? n = e; while (true) { e = n as XmlElement; // Only use the inlined write logic for XmlElement, not for derived classes if (e != null && e.GetType() == typeof(XmlElement)) { // Write the element e.WriteStartElement(writer); // Write the element's content if (e.IsEmpty) { // No content; use a short end element <a /> writer.WriteEndElement(); } else if (e._lastChild == null) { // No actual content; use a full end element <a></a> writer.WriteFullEndElement(); } else { // There are child node(s); move to first child n = e.FirstChild; Debug.Assert(n != null); continue; } } else { // Use virtual dispatch (might recurse) n.WriteTo(writer); } // Go back to the parent after writing the last child while (n != root && n == n.ParentNode!.LastChild) { n = n.ParentNode; Debug.Assert(n != null); writer.WriteFullEndElement(); } if (n == root) break; n = n.NextSibling; Debug.Assert(n != null); } } // Writes the start of the element (and its attributes) to the specified writer private void WriteStartElement(XmlWriter w) { w.WriteStartElement(Prefix, LocalName, NamespaceURI); if (HasAttributes) { XmlAttributeCollection attrs = Attributes; for (int i = 0; i < attrs.Count; i += 1) { XmlAttribute attr = attrs[i]; attr.WriteTo(w); } } } // Saves all the children of the node to the specified XmlWriter. public override void WriteContentTo(XmlWriter w) { for (XmlNode? node = FirstChild; node != null; node = node.NextSibling) { node.WriteTo(w); } } // Removes the attribute node with the specified index from the attribute collection. public virtual XmlNode? RemoveAttributeAt(int i) { if (HasAttributes) return _attributes!.RemoveAt(i); return null; } // Removes all attributes from the element. public virtual void RemoveAllAttributes() { if (HasAttributes) { _attributes!.RemoveAll(); } } // Removes all the children and/or attributes // of the current node. public override void RemoveAll() { //remove all the children base.RemoveAll(); //remove all the attributes RemoveAllAttributes(); } internal void RemoveAllChildren() { base.RemoveAll(); } public override IXmlSchemaInfo SchemaInfo { get { return _name; } } // Gets or sets the markup representing just // the children of this node. public override string InnerXml { get { return base.InnerXml; } set { RemoveAllChildren(); XmlLoader loader = new XmlLoader(); loader.LoadInnerXmlElement(this, value); } } // Gets or sets the concatenated values of the // node and all its children. public override string InnerText { get { return base.InnerText; } set { XmlLinkedNode? linkedNode = LastNode; if (linkedNode != null && //there is one child linkedNode.NodeType == XmlNodeType.Text && //which is text node linkedNode.next == linkedNode) // and it is the only child { //this branch is for perf reason, event fired when TextNode.Value is changed. linkedNode.Value = value; } else { RemoveAllChildren(); AppendChild(OwnerDocument.CreateTextNode(value)); } } } public override XmlNode? NextSibling { get { if (this.parentNode != null && this.parentNode.LastNode != this) return next; return null; } } internal override void SetParent(XmlNode? node) { this.parentNode = node; } internal override XPathNodeType XPNodeType { get { return XPathNodeType.Element; } } internal override string XPLocalName { get { return LocalName; } } internal override string GetXPAttribute(string localName, string ns) { if (ns == OwnerDocument.strReservedXmlns) return string.Empty; XmlAttribute? attr = GetAttributeNode(localName, ns); if (attr != null) return attr.Value; return string.Empty; } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/RSAPssX509SignatureGenerator.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.Formats.Asn1; using System.Security.Cryptography.Asn1; namespace System.Security.Cryptography.X509Certificates { internal sealed class RSAPssX509SignatureGenerator : X509SignatureGenerator { private readonly RSA _key; private readonly RSASignaturePadding _padding; internal RSAPssX509SignatureGenerator(RSA key, RSASignaturePadding padding) { Debug.Assert(key != null); Debug.Assert(padding != null); Debug.Assert(padding.Mode == RSASignaturePaddingMode.Pss); // Currently we don't accept options in PSS mode, but we could, so store the padding here. _key = key; _padding = padding; } public override byte[] GetSignatureAlgorithmIdentifier(HashAlgorithmName hashAlgorithm) { // If we ever support options in PSS (like MGF-2, if such an MGF is ever invented) // Or, more reasonably, supporting a custom value for the salt size. if (_padding != RSASignaturePadding.Pss) { throw new CryptographicException(SR.Cryptography_InvalidPaddingMode); } int cbSalt; string digestOid; if (hashAlgorithm == HashAlgorithmName.SHA256) { cbSalt = SHA256.HashSizeInBytes; digestOid = Oids.Sha256; } else if (hashAlgorithm == HashAlgorithmName.SHA384) { cbSalt = SHA384.HashSizeInBytes; digestOid = Oids.Sha384; } else if (hashAlgorithm == HashAlgorithmName.SHA512) { cbSalt = SHA512.HashSizeInBytes; digestOid = Oids.Sha512; } else { throw new ArgumentOutOfRangeException( nameof(hashAlgorithm), hashAlgorithm, SR.Format(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name)); } // RFC 5754 says that the NULL for SHA2 (256/384/512) MUST be omitted // (https://tools.ietf.org/html/rfc5754#section-2) (and that you MUST // be able to read it even if someone wrote it down) // // Since we // * don't support SHA-1 in this class // * only support MGF-1 // * don't support the MGF PRF being different than hashAlgorithm // * use saltLength==hashLength // * don't allow custom trailer // we don't have to worry about any of the DEFAULTs. (specify, specify, specify, omit). PssParamsAsn parameters = new PssParamsAsn { HashAlgorithm = new AlgorithmIdentifierAsn { Algorithm = digestOid }, MaskGenAlgorithm = new AlgorithmIdentifierAsn { Algorithm = Oids.Mgf1 }, SaltLength = cbSalt, TrailerField = 1, }; AsnWriter writer = new AsnWriter(AsnEncodingRules.DER); using (writer.PushSequence()) { writer.WriteObjectIdentifierForCrypto(digestOid); } parameters.MaskGenAlgorithm.Parameters = writer.Encode(); writer.Reset(); parameters.Encode(writer); AlgorithmIdentifierAsn identifier = new AlgorithmIdentifierAsn { Algorithm = Oids.RsaPss, Parameters = writer.Encode(), }; writer.Reset(); identifier.Encode(writer); return writer.Encode(); } public override byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm) { return _key.SignData(data, hashAlgorithm, _padding); } protected override PublicKey BuildPublicKey() { // RFC 4055 (https://tools.ietf.org/html/rfc4055) recommends using a different // key format for 'PSS keys'. RFC 5756 (https://tools.ietf.org/html/rfc5756) says // that almost no one did that, and that it goes against the general guidance of // SubjectPublicKeyInfo, so RSA keys should use the existing form always and the // PSS-specific key algorithm ID is deprecated (as a key ID). return RSAPkcs1X509SignatureGenerator.BuildPublicKey(_key); } } }
// 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.Formats.Asn1; using System.Security.Cryptography.Asn1; namespace System.Security.Cryptography.X509Certificates { internal sealed class RSAPssX509SignatureGenerator : X509SignatureGenerator { private readonly RSA _key; private readonly RSASignaturePadding _padding; internal RSAPssX509SignatureGenerator(RSA key, RSASignaturePadding padding) { Debug.Assert(key != null); Debug.Assert(padding != null); Debug.Assert(padding.Mode == RSASignaturePaddingMode.Pss); // Currently we don't accept options in PSS mode, but we could, so store the padding here. _key = key; _padding = padding; } public override byte[] GetSignatureAlgorithmIdentifier(HashAlgorithmName hashAlgorithm) { // If we ever support options in PSS (like MGF-2, if such an MGF is ever invented) // Or, more reasonably, supporting a custom value for the salt size. if (_padding != RSASignaturePadding.Pss) { throw new CryptographicException(SR.Cryptography_InvalidPaddingMode); } int cbSalt; string digestOid; if (hashAlgorithm == HashAlgorithmName.SHA256) { cbSalt = SHA256.HashSizeInBytes; digestOid = Oids.Sha256; } else if (hashAlgorithm == HashAlgorithmName.SHA384) { cbSalt = SHA384.HashSizeInBytes; digestOid = Oids.Sha384; } else if (hashAlgorithm == HashAlgorithmName.SHA512) { cbSalt = SHA512.HashSizeInBytes; digestOid = Oids.Sha512; } else { throw new ArgumentOutOfRangeException( nameof(hashAlgorithm), hashAlgorithm, SR.Format(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name)); } // RFC 5754 says that the NULL for SHA2 (256/384/512) MUST be omitted // (https://tools.ietf.org/html/rfc5754#section-2) (and that you MUST // be able to read it even if someone wrote it down) // // Since we // * don't support SHA-1 in this class // * only support MGF-1 // * don't support the MGF PRF being different than hashAlgorithm // * use saltLength==hashLength // * don't allow custom trailer // we don't have to worry about any of the DEFAULTs. (specify, specify, specify, omit). PssParamsAsn parameters = new PssParamsAsn { HashAlgorithm = new AlgorithmIdentifierAsn { Algorithm = digestOid }, MaskGenAlgorithm = new AlgorithmIdentifierAsn { Algorithm = Oids.Mgf1 }, SaltLength = cbSalt, TrailerField = 1, }; AsnWriter writer = new AsnWriter(AsnEncodingRules.DER); using (writer.PushSequence()) { writer.WriteObjectIdentifierForCrypto(digestOid); } parameters.MaskGenAlgorithm.Parameters = writer.Encode(); writer.Reset(); parameters.Encode(writer); AlgorithmIdentifierAsn identifier = new AlgorithmIdentifierAsn { Algorithm = Oids.RsaPss, Parameters = writer.Encode(), }; writer.Reset(); identifier.Encode(writer); return writer.Encode(); } public override byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm) { return _key.SignData(data, hashAlgorithm, _padding); } protected override PublicKey BuildPublicKey() { // RFC 4055 (https://tools.ietf.org/html/rfc4055) recommends using a different // key format for 'PSS keys'. RFC 5756 (https://tools.ietf.org/html/rfc5756) says // that almost no one did that, and that it goes against the general guidance of // SubjectPublicKeyInfo, so RSA keys should use the existing form always and the // PSS-specific key algorithm ID is deprecated (as a key ID). return RSAPkcs1X509SignatureGenerator.BuildPublicKey(_key); } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/readytorun/crossboundarylayout/e/e.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace CrossBoundaryLayout { public struct ByteStructE { public byte _eVal; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace CrossBoundaryLayout { public struct ByteStructE { public byte _eVal; } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/Interop/COM/NETClients/ConsumeNETServer/Program.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace NetClient { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using TestLibrary; using Xunit; using Server.Contract; using CoClass = Server.Contract.Servers; class Program { static void Validate_Activation() { Console.WriteLine($"{nameof(Validate_Activation)}..."); var test = new CoClass.ConsumeNETServerTesting(); test.ReleaseResources(); // The CoClass should be the activated type, _not_ the activation interface. Assert.Equal(test.GetType(), typeof(CoClass.ConsumeNETServerTestingClass)); Assert.True(typeof(CoClass.ConsumeNETServerTestingClass).IsCOMObject); Assert.False(typeof(CoClass.ConsumeNETServerTesting).IsCOMObject); Assert.True(Marshal.IsComObject(test)); } static void Validate_Activation_CreateInstance() { Console.WriteLine($"{nameof(Validate_Activation_CreateInstance)}..."); Type t = Type.GetTypeFromCLSID(Guid.Parse(Guids.ConsumeNETServerTesting)); Assert.True(t.IsCOMObject); object obj = Activator.CreateInstance(t); var test = (CoClass.ConsumeNETServerTesting)obj; test.ReleaseResources(); Assert.True(Marshal.IsComObject(test)); // Use the overload that takes constructor arguments. This tests the path where the runtime searches for the // constructor to use (which has some special-casing for COM) instead of just always using the default. obj = Activator.CreateInstance(t, Array.Empty<object>()); test = (CoClass.ConsumeNETServerTesting)obj; test.ReleaseResources(); Assert.True(Marshal.IsComObject(test)); } static void Validate_CCW_Wasnt_Unwrapped() { Console.WriteLine($"{nameof(Validate_CCW_Wasnt_Unwrapped)}..."); var test = new CoClass.ConsumeNETServerTesting(); test.ReleaseResources(); // The CoClass should be the activated type, _not_ the implementation class. // This indicates the real implementation class is wrapped in its CCW and exposed // to the runtime as an RCW. Assert.NotEqual(test.GetType(), typeof(ConsumeNETServerTesting)); } static void Validate_Client_CCW_RCW() { Console.WriteLine($"{nameof(Validate_Client_CCW_RCW)}..."); IntPtr ccw = IntPtr.Zero; // Validate the client side view is consistent var test = new CoClass.ConsumeNETServerTesting(); try { ccw = test.GetCCW(); object rcw = Marshal.GetObjectForIUnknown(ccw); object inst = test.GetRCW(); Assert.Equal(rcw, inst); } finally { test.ReleaseResources(); } } static void Validate_Server_CCW_RCW() { Console.WriteLine($"{nameof(Validate_Server_CCW_RCW)}..."); // Validate the server side view is consistent var test = new CoClass.ConsumeNETServerTesting(); try { Assert.True(test.EqualByCCW(test)); Assert.True(test.NotEqualByRCW(test)); } finally { test.ReleaseResources(); } } static int Main(string[] doNotUse) { // RegFree COM is not supported on Windows Nano if (Utilities.IsWindowsNanoServer) { return 100; } // Initialize CoreShim and hostpolicymock HostPolicyMock.Initialize(Environment.CurrentDirectory, null); Environment.SetEnvironmentVariable("CORESHIM_COMACT_ASSEMBLYNAME", "NETServer"); Environment.SetEnvironmentVariable("CORESHIM_COMACT_TYPENAME", "ConsumeNETServerTesting"); try { using (HostPolicyMock.Mock_corehost_resolve_component_dependencies( 0, string.Empty, string.Empty, string.Empty)) { Validate_Activation(); Validate_Activation_CreateInstance(); Validate_CCW_Wasnt_Unwrapped(); Validate_Client_CCW_RCW(); Validate_Server_CCW_RCW(); } } catch (Exception e) { Console.WriteLine($"Test Failure: {e}"); return 101; } return 100; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace NetClient { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using TestLibrary; using Xunit; using Server.Contract; using CoClass = Server.Contract.Servers; class Program { static void Validate_Activation() { Console.WriteLine($"{nameof(Validate_Activation)}..."); var test = new CoClass.ConsumeNETServerTesting(); test.ReleaseResources(); // The CoClass should be the activated type, _not_ the activation interface. Assert.Equal(test.GetType(), typeof(CoClass.ConsumeNETServerTestingClass)); Assert.True(typeof(CoClass.ConsumeNETServerTestingClass).IsCOMObject); Assert.False(typeof(CoClass.ConsumeNETServerTesting).IsCOMObject); Assert.True(Marshal.IsComObject(test)); } static void Validate_Activation_CreateInstance() { Console.WriteLine($"{nameof(Validate_Activation_CreateInstance)}..."); Type t = Type.GetTypeFromCLSID(Guid.Parse(Guids.ConsumeNETServerTesting)); Assert.True(t.IsCOMObject); object obj = Activator.CreateInstance(t); var test = (CoClass.ConsumeNETServerTesting)obj; test.ReleaseResources(); Assert.True(Marshal.IsComObject(test)); // Use the overload that takes constructor arguments. This tests the path where the runtime searches for the // constructor to use (which has some special-casing for COM) instead of just always using the default. obj = Activator.CreateInstance(t, Array.Empty<object>()); test = (CoClass.ConsumeNETServerTesting)obj; test.ReleaseResources(); Assert.True(Marshal.IsComObject(test)); } static void Validate_CCW_Wasnt_Unwrapped() { Console.WriteLine($"{nameof(Validate_CCW_Wasnt_Unwrapped)}..."); var test = new CoClass.ConsumeNETServerTesting(); test.ReleaseResources(); // The CoClass should be the activated type, _not_ the implementation class. // This indicates the real implementation class is wrapped in its CCW and exposed // to the runtime as an RCW. Assert.NotEqual(test.GetType(), typeof(ConsumeNETServerTesting)); } static void Validate_Client_CCW_RCW() { Console.WriteLine($"{nameof(Validate_Client_CCW_RCW)}..."); IntPtr ccw = IntPtr.Zero; // Validate the client side view is consistent var test = new CoClass.ConsumeNETServerTesting(); try { ccw = test.GetCCW(); object rcw = Marshal.GetObjectForIUnknown(ccw); object inst = test.GetRCW(); Assert.Equal(rcw, inst); } finally { test.ReleaseResources(); } } static void Validate_Server_CCW_RCW() { Console.WriteLine($"{nameof(Validate_Server_CCW_RCW)}..."); // Validate the server side view is consistent var test = new CoClass.ConsumeNETServerTesting(); try { Assert.True(test.EqualByCCW(test)); Assert.True(test.NotEqualByRCW(test)); } finally { test.ReleaseResources(); } } static int Main(string[] doNotUse) { // RegFree COM is not supported on Windows Nano if (Utilities.IsWindowsNanoServer) { return 100; } // Initialize CoreShim and hostpolicymock HostPolicyMock.Initialize(Environment.CurrentDirectory, null); Environment.SetEnvironmentVariable("CORESHIM_COMACT_ASSEMBLYNAME", "NETServer"); Environment.SetEnvironmentVariable("CORESHIM_COMACT_TYPENAME", "ConsumeNETServerTesting"); try { using (HostPolicyMock.Mock_corehost_resolve_component_dependencies( 0, string.Empty, string.Empty, string.Empty)) { Validate_Activation(); Validate_Activation_CreateInstance(); Validate_CCW_Wasnt_Unwrapped(); Validate_Client_CCW_RCW(); Validate_Server_CCW_RCW(); } } catch (Exception e) { Console.WriteLine($"Test Failure: {e}"); return 101; } return 100; } } }
-1