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,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/jit/typeinfo.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX typeInfo XX XX XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif #include "_typeinfo.h" bool Compiler::tiCompatibleWith(const typeInfo& child, const typeInfo& parent, bool normalisedForStack) const { return typeInfo::tiCompatibleWith(info.compCompHnd, child, parent, normalisedForStack); } bool Compiler::tiMergeCompatibleWith(const typeInfo& child, const typeInfo& parent, bool normalisedForStack) const { return typeInfo::tiMergeCompatibleWith(info.compCompHnd, child, parent, normalisedForStack); } bool Compiler::tiMergeToCommonParent(typeInfo* pDest, const typeInfo* pSrc, bool* changed) const { return typeInfo::tiMergeToCommonParent(info.compCompHnd, pDest, pSrc, changed); } static bool tiCompatibleWithByRef(COMP_HANDLE CompHnd, const typeInfo& child, const typeInfo& parent) { assert(parent.IsByRef()); if (!child.IsByRef()) { return false; } if (child.IsReadonlyByRef() && !parent.IsReadonlyByRef()) { return false; } // Byrefs are compatible if the underlying types are equivalent typeInfo childTarget = ::DereferenceByRef(child); typeInfo parentTarget = ::DereferenceByRef(parent); if (typeInfo::AreEquivalent(childTarget, parentTarget)) { return true; } // Make sure that both types have a valid m_cls if ((childTarget.IsType(TI_REF) || childTarget.IsType(TI_STRUCT)) && (parentTarget.IsType(TI_REF) || parentTarget.IsType(TI_STRUCT))) { return CompHnd->areTypesEquivalent(childTarget.GetClassHandle(), parentTarget.GetClassHandle()); } return false; } /***************************************************************************** * Verify child is compatible with the template parent. Basically, that * child is a "subclass" of parent -it can be substituted for parent * anywhere. Note that if parent contains fancy flags, such as "uninitialized" * , "is this ptr", or "has byref local/field" info, then child must also * contain those flags, otherwise FALSE will be returned ! * * Rules for determining compatibility: * * If parent is a primitive type or value class, then child must be the * same primitive type or value class. The exception is that the built in * value classes System/Boolean etc. are treated as synonyms for * TI_BYTE etc. * * If parent is a byref of a primitive type or value class, then child * must be a byref of the same (rules same as above case). * * Byrefs are compatible only with byrefs. * * If parent is an object, child must be a subclass of it, implement it * (if it is an interface), or be null. * * If parent is an array, child must be the same or subclassed array. * * If parent is a null objref, only null is compatible with it. * * If the "uninitialized", "by ref local/field", "this pointer" or other flags * are different, the items are incompatible. * * parent CANNOT be an undefined (dead) item. * */ bool typeInfo::tiCompatibleWith(COMP_HANDLE CompHnd, const typeInfo& child, const typeInfo& parent, bool normalisedForStack) { assert(child.IsDead() || !normalisedForStack || typeInfo::AreEquivalent(::NormaliseForStack(child), child)); assert(parent.IsDead() || !normalisedForStack || typeInfo::AreEquivalent(::NormaliseForStack(parent), parent)); if (typeInfo::AreEquivalent(child, parent)) { return true; } if (parent.IsUnboxedGenericTypeVar() || child.IsUnboxedGenericTypeVar()) { return false; // need to have had child == parent } else if (parent.IsType(TI_REF)) { // An uninitialized objRef is not compatible to initialized. if (child.IsUninitialisedObjRef() && !parent.IsUninitialisedObjRef()) { return false; } if (child.IsNullObjRef()) { // NULL can be any reference type return true; } if (!child.IsType(TI_REF)) { return false; } return CompHnd->canCast(child.m_cls, parent.m_cls); } else if (parent.IsType(TI_METHOD)) { if (!child.IsType(TI_METHOD)) { return false; } // Right now we don't bother merging method handles return false; } else if (parent.IsType(TI_STRUCT)) { if (!child.IsType(TI_STRUCT)) { return false; } // Structures are compatible if they are equivalent return CompHnd->areTypesEquivalent(child.m_cls, parent.m_cls); } else if (parent.IsByRef()) { return tiCompatibleWithByRef(CompHnd, child, parent); } #ifdef TARGET_64BIT // On 64-bit targets we have precise representation for native int, so these rules // represent the fact that the ECMA spec permits the implicit conversion // between an int32 and a native int. else if (parent.IsType(TI_INT) && typeInfo::AreEquivalent(nativeInt(), child)) { return true; } else if (typeInfo::AreEquivalent(nativeInt(), parent) && child.IsType(TI_INT)) { return true; } #endif // TARGET_64BIT return false; } bool typeInfo::tiMergeCompatibleWith(COMP_HANDLE CompHnd, const typeInfo& child, const typeInfo& parent, bool normalisedForStack) { if (!child.IsPermanentHomeByRef() && parent.IsPermanentHomeByRef()) { return false; } return typeInfo::tiCompatibleWith(CompHnd, child, parent, normalisedForStack); } /***************************************************************************** * Merge pDest and pSrc to find some commonality (e.g. a common parent). * Copy the result to pDest, marking it dead if no commonality can be found. * * null ^ null -> null * Object ^ null -> Object * [I4 ^ null -> [I4 * InputStream ^ OutputStream -> Stream * InputStream ^ NULL -> InputStream * [I4 ^ Object -> Object * [I4 ^ [Object -> Array * [I4 ^ [R8 -> Array * [Foo ^ I4 -> DEAD * [Foo ^ [I1 -> Array * [InputStream ^ [OutputStream -> Array * DEAD ^ X -> DEAD * [Intfc ^ [OutputStream -> Array * Intf ^ [OutputStream -> Object * [[InStream ^ [[OutStream -> Array * [[InStream ^ [OutStream -> Array * [[Foo ^ [Object -> Array * * Importantly: * [I1 ^ [U1 -> either [I1 or [U1 * etc. * * Also, System/Int32 and I4 merge -> I4, etc. * * Returns FALSE if the merge was completely incompatible (i.e. the item became * dead). * */ bool typeInfo::tiMergeToCommonParent(COMP_HANDLE CompHnd, typeInfo* pDest, const typeInfo* pSrc, bool* changed) { assert(pSrc->IsDead() || typeInfo::AreEquivalent(::NormaliseForStack(*pSrc), *pSrc)); assert(pDest->IsDead() || typeInfo::AreEquivalent(::NormaliseForStack(*pDest), *pDest)); // Merge the auxiliary information like "this" pointer tracking, etc... // Remember the pre-state, so we can tell if it changed. *changed = false; DWORD destFlagsBefore = pDest->m_flags; // This bit is only set if both pDest and pSrc have it set pDest->m_flags &= (pSrc->m_flags | ~TI_FLAG_THIS_PTR); // This bit is set if either pDest or pSrc have it set pDest->m_flags |= (pSrc->m_flags & TI_FLAG_UNINIT_OBJREF); // This bit is set if either pDest or pSrc have it set pDest->m_flags |= (pSrc->m_flags & TI_FLAG_BYREF_READONLY); // If the byref wasn't permanent home in both sides, then merge won't have the bit set pDest->m_flags &= (pSrc->m_flags | ~TI_FLAG_BYREF_PERMANENT_HOME); if (pDest->m_flags != destFlagsBefore) { *changed = true; } // OK the main event. Merge the main types if (typeInfo::AreEquivalent(*pDest, *pSrc)) { return true; } if (pDest->IsUnboxedGenericTypeVar() || pSrc->IsUnboxedGenericTypeVar()) { // Should have had *pDest == *pSrc goto FAIL; } if (pDest->IsType(TI_REF)) { if (pSrc->IsType(TI_NULL)) { // NULL can be any reference type return true; } if (!pSrc->IsType(TI_REF)) { goto FAIL; } // Ask the EE to find the common parent, This always succeeds since System.Object always works CORINFO_CLASS_HANDLE pDestClsBefore = pDest->m_cls; pDest->m_cls = CompHnd->mergeClasses(pDest->GetClassHandle(), pSrc->GetClassHandle()); if (pDestClsBefore != pDest->m_cls) { *changed = true; } return true; } else if (pDest->IsType(TI_NULL)) { if (pSrc->IsType(TI_REF)) // NULL can be any reference type { *pDest = *pSrc; *changed = true; return true; } goto FAIL; } else if (pDest->IsType(TI_STRUCT)) { if (pSrc->IsType(TI_STRUCT) && CompHnd->areTypesEquivalent(pDest->GetClassHandle(), pSrc->GetClassHandle())) { return true; } goto FAIL; } else if (pDest->IsByRef()) { return tiCompatibleWithByRef(CompHnd, *pSrc, *pDest); } #ifdef TARGET_64BIT // On 64-bit targets we have precise representation for native int, so these rules // represent the fact that the ECMA spec permits the implicit conversion // between an int32 and a native int. else if (typeInfo::AreEquivalent(*pDest, typeInfo::nativeInt()) && pSrc->IsType(TI_INT)) { return true; } else if (typeInfo::AreEquivalent(*pSrc, typeInfo::nativeInt()) && pDest->IsType(TI_INT)) { *pDest = *pSrc; *changed = true; return true; } #endif // TARGET_64BIT FAIL: *pDest = typeInfo(); return false; } #ifdef DEBUG #if VERBOSE_VERIFY // Utility method to have a detailed dump of a TypeInfo object void typeInfo::Dump() const { char flagsStr[8]; flagsStr[0] = ((m_flags & TI_FLAG_UNINIT_OBJREF) != 0) ? 'U' : '-'; flagsStr[1] = ((m_flags & TI_FLAG_BYREF) != 0) ? 'B' : '-'; flagsStr[2] = ((m_flags & TI_FLAG_BYREF_READONLY) != 0) ? 'R' : '-'; flagsStr[3] = ((m_flags & TI_FLAG_NATIVE_INT) != 0) ? 'N' : '-'; flagsStr[4] = ((m_flags & TI_FLAG_THIS_PTR) != 0) ? 'T' : '-'; flagsStr[5] = ((m_flags & TI_FLAG_BYREF_PERMANENT_HOME) != 0) ? 'P' : '-'; flagsStr[6] = ((m_flags & TI_FLAG_GENERIC_TYPE_VAR) != 0) ? 'G' : '-'; flagsStr[7] = '\0'; printf("[%s(%X) {%s}]", tiType2Str(m_bits.type), m_cls, flagsStr); } #endif // VERBOSE_VERIFY #endif // DEBUG
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX typeInfo XX XX XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif #include "_typeinfo.h" bool Compiler::tiCompatibleWith(const typeInfo& child, const typeInfo& parent, bool normalisedForStack) const { return typeInfo::tiCompatibleWith(info.compCompHnd, child, parent, normalisedForStack); } bool Compiler::tiMergeCompatibleWith(const typeInfo& child, const typeInfo& parent, bool normalisedForStack) const { return typeInfo::tiMergeCompatibleWith(info.compCompHnd, child, parent, normalisedForStack); } bool Compiler::tiMergeToCommonParent(typeInfo* pDest, const typeInfo* pSrc, bool* changed) const { return typeInfo::tiMergeToCommonParent(info.compCompHnd, pDest, pSrc, changed); } static bool tiCompatibleWithByRef(COMP_HANDLE CompHnd, const typeInfo& child, const typeInfo& parent) { assert(parent.IsByRef()); if (!child.IsByRef()) { return false; } if (child.IsReadonlyByRef() && !parent.IsReadonlyByRef()) { return false; } // Byrefs are compatible if the underlying types are equivalent typeInfo childTarget = ::DereferenceByRef(child); typeInfo parentTarget = ::DereferenceByRef(parent); if (typeInfo::AreEquivalent(childTarget, parentTarget)) { return true; } // Make sure that both types have a valid m_cls if ((childTarget.IsType(TI_REF) || childTarget.IsType(TI_STRUCT)) && (parentTarget.IsType(TI_REF) || parentTarget.IsType(TI_STRUCT))) { return CompHnd->areTypesEquivalent(childTarget.GetClassHandle(), parentTarget.GetClassHandle()); } return false; } /***************************************************************************** * Verify child is compatible with the template parent. Basically, that * child is a "subclass" of parent -it can be substituted for parent * anywhere. Note that if parent contains fancy flags, such as "uninitialized" * , "is this ptr", or "has byref local/field" info, then child must also * contain those flags, otherwise FALSE will be returned ! * * Rules for determining compatibility: * * If parent is a primitive type or value class, then child must be the * same primitive type or value class. The exception is that the built in * value classes System/Boolean etc. are treated as synonyms for * TI_BYTE etc. * * If parent is a byref of a primitive type or value class, then child * must be a byref of the same (rules same as above case). * * Byrefs are compatible only with byrefs. * * If parent is an object, child must be a subclass of it, implement it * (if it is an interface), or be null. * * If parent is an array, child must be the same or subclassed array. * * If parent is a null objref, only null is compatible with it. * * If the "uninitialized", "by ref local/field", "this pointer" or other flags * are different, the items are incompatible. * * parent CANNOT be an undefined (dead) item. * */ bool typeInfo::tiCompatibleWith(COMP_HANDLE CompHnd, const typeInfo& child, const typeInfo& parent, bool normalisedForStack) { assert(child.IsDead() || !normalisedForStack || typeInfo::AreEquivalent(::NormaliseForStack(child), child)); assert(parent.IsDead() || !normalisedForStack || typeInfo::AreEquivalent(::NormaliseForStack(parent), parent)); if (typeInfo::AreEquivalent(child, parent)) { return true; } if (parent.IsUnboxedGenericTypeVar() || child.IsUnboxedGenericTypeVar()) { return false; // need to have had child == parent } else if (parent.IsType(TI_REF)) { // An uninitialized objRef is not compatible to initialized. if (child.IsUninitialisedObjRef() && !parent.IsUninitialisedObjRef()) { return false; } if (child.IsNullObjRef()) { // NULL can be any reference type return true; } if (!child.IsType(TI_REF)) { return false; } return CompHnd->canCast(child.m_cls, parent.m_cls); } else if (parent.IsType(TI_METHOD)) { if (!child.IsType(TI_METHOD)) { return false; } // Right now we don't bother merging method handles return false; } else if (parent.IsType(TI_STRUCT)) { if (!child.IsType(TI_STRUCT)) { return false; } // Structures are compatible if they are equivalent return CompHnd->areTypesEquivalent(child.m_cls, parent.m_cls); } else if (parent.IsByRef()) { return tiCompatibleWithByRef(CompHnd, child, parent); } #ifdef TARGET_64BIT // On 64-bit targets we have precise representation for native int, so these rules // represent the fact that the ECMA spec permits the implicit conversion // between an int32 and a native int. else if (parent.IsType(TI_INT) && typeInfo::AreEquivalent(nativeInt(), child)) { return true; } else if (typeInfo::AreEquivalent(nativeInt(), parent) && child.IsType(TI_INT)) { return true; } #endif // TARGET_64BIT return false; } bool typeInfo::tiMergeCompatibleWith(COMP_HANDLE CompHnd, const typeInfo& child, const typeInfo& parent, bool normalisedForStack) { if (!child.IsPermanentHomeByRef() && parent.IsPermanentHomeByRef()) { return false; } return typeInfo::tiCompatibleWith(CompHnd, child, parent, normalisedForStack); } /***************************************************************************** * Merge pDest and pSrc to find some commonality (e.g. a common parent). * Copy the result to pDest, marking it dead if no commonality can be found. * * null ^ null -> null * Object ^ null -> Object * [I4 ^ null -> [I4 * InputStream ^ OutputStream -> Stream * InputStream ^ NULL -> InputStream * [I4 ^ Object -> Object * [I4 ^ [Object -> Array * [I4 ^ [R8 -> Array * [Foo ^ I4 -> DEAD * [Foo ^ [I1 -> Array * [InputStream ^ [OutputStream -> Array * DEAD ^ X -> DEAD * [Intfc ^ [OutputStream -> Array * Intf ^ [OutputStream -> Object * [[InStream ^ [[OutStream -> Array * [[InStream ^ [OutStream -> Array * [[Foo ^ [Object -> Array * * Importantly: * [I1 ^ [U1 -> either [I1 or [U1 * etc. * * Also, System/Int32 and I4 merge -> I4, etc. * * Returns FALSE if the merge was completely incompatible (i.e. the item became * dead). * */ bool typeInfo::tiMergeToCommonParent(COMP_HANDLE CompHnd, typeInfo* pDest, const typeInfo* pSrc, bool* changed) { assert(pSrc->IsDead() || typeInfo::AreEquivalent(::NormaliseForStack(*pSrc), *pSrc)); assert(pDest->IsDead() || typeInfo::AreEquivalent(::NormaliseForStack(*pDest), *pDest)); // Merge the auxiliary information like "this" pointer tracking, etc... // Remember the pre-state, so we can tell if it changed. *changed = false; DWORD destFlagsBefore = pDest->m_flags; // This bit is only set if both pDest and pSrc have it set pDest->m_flags &= (pSrc->m_flags | ~TI_FLAG_THIS_PTR); // This bit is set if either pDest or pSrc have it set pDest->m_flags |= (pSrc->m_flags & TI_FLAG_UNINIT_OBJREF); // This bit is set if either pDest or pSrc have it set pDest->m_flags |= (pSrc->m_flags & TI_FLAG_BYREF_READONLY); // If the byref wasn't permanent home in both sides, then merge won't have the bit set pDest->m_flags &= (pSrc->m_flags | ~TI_FLAG_BYREF_PERMANENT_HOME); if (pDest->m_flags != destFlagsBefore) { *changed = true; } // OK the main event. Merge the main types if (typeInfo::AreEquivalent(*pDest, *pSrc)) { return true; } if (pDest->IsUnboxedGenericTypeVar() || pSrc->IsUnboxedGenericTypeVar()) { // Should have had *pDest == *pSrc goto FAIL; } if (pDest->IsType(TI_REF)) { if (pSrc->IsType(TI_NULL)) { // NULL can be any reference type return true; } if (!pSrc->IsType(TI_REF)) { goto FAIL; } // Ask the EE to find the common parent, This always succeeds since System.Object always works CORINFO_CLASS_HANDLE pDestClsBefore = pDest->m_cls; pDest->m_cls = CompHnd->mergeClasses(pDest->GetClassHandle(), pSrc->GetClassHandle()); if (pDestClsBefore != pDest->m_cls) { *changed = true; } return true; } else if (pDest->IsType(TI_NULL)) { if (pSrc->IsType(TI_REF)) // NULL can be any reference type { *pDest = *pSrc; *changed = true; return true; } goto FAIL; } else if (pDest->IsType(TI_STRUCT)) { if (pSrc->IsType(TI_STRUCT) && CompHnd->areTypesEquivalent(pDest->GetClassHandle(), pSrc->GetClassHandle())) { return true; } goto FAIL; } else if (pDest->IsByRef()) { return tiCompatibleWithByRef(CompHnd, *pSrc, *pDest); } #ifdef TARGET_64BIT // On 64-bit targets we have precise representation for native int, so these rules // represent the fact that the ECMA spec permits the implicit conversion // between an int32 and a native int. else if (typeInfo::AreEquivalent(*pDest, typeInfo::nativeInt()) && pSrc->IsType(TI_INT)) { return true; } else if (typeInfo::AreEquivalent(*pSrc, typeInfo::nativeInt()) && pDest->IsType(TI_INT)) { *pDest = *pSrc; *changed = true; return true; } #endif // TARGET_64BIT FAIL: *pDest = typeInfo(); return false; } #ifdef DEBUG #if VERBOSE_VERIFY // Utility method to have a detailed dump of a TypeInfo object void typeInfo::Dump() const { char flagsStr[8]; flagsStr[0] = ((m_flags & TI_FLAG_UNINIT_OBJREF) != 0) ? 'U' : '-'; flagsStr[1] = ((m_flags & TI_FLAG_BYREF) != 0) ? 'B' : '-'; flagsStr[2] = ((m_flags & TI_FLAG_BYREF_READONLY) != 0) ? 'R' : '-'; flagsStr[3] = ((m_flags & TI_FLAG_NATIVE_INT) != 0) ? 'N' : '-'; flagsStr[4] = ((m_flags & TI_FLAG_THIS_PTR) != 0) ? 'T' : '-'; flagsStr[5] = ((m_flags & TI_FLAG_BYREF_PERMANENT_HOME) != 0) ? 'P' : '-'; flagsStr[6] = ((m_flags & TI_FLAG_GENERIC_TYPE_VAR) != 0) ? 'G' : '-'; flagsStr[7] = '\0'; printf("[%s(%X) {%s}]", tiType2Str(m_bits.type), m_cls, flagsStr); } #endif // VERBOSE_VERIFY #endif // DEBUG
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/pal/tests/palsuite/c_runtime/bsearch/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: Calls bsearch to find a character in a sorted buffer, and ** verifies that the correct position is returned. ** ** **==========================================================================*/ #include <palsuite.h> int __cdecl charcmp_bsearch_test1(const void *pa, const void *pb) { return memcmp(pa, pb, 1); } PALTEST(c_runtime_bsearch_test1_paltest_bsearch_test1, "c_runtime/bsearch/test1/paltest_bsearch_test1") { const char array[] = "abcdefghij"; char * found=NULL; /* * Initialize the PAL and return FAIL if this fails */ if (0 != (PAL_Initialize(argc, argv))) { return FAIL; } found = (char *)bsearch(&"d", array, sizeof(array) - 1, (sizeof(char)) , charcmp_bsearch_test1); if (found != array + 3) { Fail ("bsearch was unable to find a specified character in a " "sorted list.\n"); } 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: Calls bsearch to find a character in a sorted buffer, and ** verifies that the correct position is returned. ** ** **==========================================================================*/ #include <palsuite.h> int __cdecl charcmp_bsearch_test1(const void *pa, const void *pb) { return memcmp(pa, pb, 1); } PALTEST(c_runtime_bsearch_test1_paltest_bsearch_test1, "c_runtime/bsearch/test1/paltest_bsearch_test1") { const char array[] = "abcdefghij"; char * found=NULL; /* * Initialize the PAL and return FAIL if this fails */ if (0 != (PAL_Initialize(argc, argv))) { return FAIL; } found = (char *)bsearch(&"d", array, sizeof(array) - 1, (sizeof(char)) , charcmp_bsearch_test1); if (found != array + 3) { Fail ("bsearch was unable to find a specified character in a " "sorted list.\n"); } PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/jit/sm.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX State machine used in the JIT XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif #include "smcommon.cpp" // // The array to map from EE opcodes (i.e. CEE_ ) to state machine opcodes (i.e. SM_ ) // const SM_OPCODE smOpcodeMap[] = { #define OPCODEMAP(eename, eestring, smname) smname, #include "smopcodemap.def" #undef OPCODEMAP }; // ????????? How to make this method inlinable, since it refers to smOpcodeMap???? /* static */ SM_OPCODE CodeSeqSM::MapToSMOpcode(OPCODE opcode) { assert(opcode < CEE_COUNT); SM_OPCODE smOpcode = smOpcodeMap[opcode]; assert(smOpcode < SM_COUNT); return smOpcode; } void CodeSeqSM::Start(Compiler* comp) { pComp = comp; States = gp_SMStates; JumpTableCells = gp_SMJumpTableCells; StateWeights = gp_StateWeights; NativeSize = 0; Reset(); } void CodeSeqSM::Reset() { curState = SM_STATE_ID_START; } void CodeSeqSM::End() { if (States[curState].term) { TermStateMatch(curState DEBUGARG(pComp->verbose)); } } void CodeSeqSM::Run(SM_OPCODE opcode DEBUGARG(int level)) { SM_STATE_ID nextState; SM_STATE_ID rollbackState; SM_OPCODE opcodesToRevisit[MAX_CODE_SEQUENCE_LENGTH]; assert(level <= MAX_CODE_SEQUENCE_LENGTH); _Next: nextState = GetDestState(curState, opcode); if (nextState != 0) { // This is easy, Just go to the next state. curState = nextState; return; } assert(curState != SM_STATE_ID_START); if (States[curState].term) { TermStateMatch(curState DEBUGARG(pComp->verbose)); curState = SM_STATE_ID_START; goto _Next; } // This is hard. We need to rollback to the longest matched term state and restart from there. rollbackState = States[curState].longestTermState; TermStateMatch(rollbackState DEBUGARG(pComp->verbose)); assert(States[curState].length > States[rollbackState].length); unsigned numOfOpcodesToRevisit = States[curState].length - States[rollbackState].length + 1; assert(numOfOpcodesToRevisit > 1 && numOfOpcodesToRevisit <= MAX_CODE_SEQUENCE_LENGTH); // So it can fit in the local array opcodesToRevisit[] SM_OPCODE* p = opcodesToRevisit + (numOfOpcodesToRevisit - 1); *p = opcode; // Fill in the local array: for (unsigned i = 0; i < numOfOpcodesToRevisit - 1; ++i) { *(--p) = States[curState].opc; curState = States[curState].prevState; } assert(curState == rollbackState); // Now revisit these opcodes, starting from SM_STATE_ID_START. curState = SM_STATE_ID_START; for (p = opcodesToRevisit; p < opcodesToRevisit + numOfOpcodesToRevisit; ++p) { Run(*p DEBUGARG(level + 1)); } } SM_STATE_ID CodeSeqSM::GetDestState(SM_STATE_ID srcState, SM_OPCODE opcode) { assert(opcode < SM_COUNT); JumpTableCell* pThisJumpTable = (JumpTableCell*)(((PBYTE)JumpTableCells) + States[srcState].jumpTableByteOffset); JumpTableCell* cell = pThisJumpTable + opcode; if (cell->srcState != srcState) { assert(cell->srcState == 0 || cell->srcState != srcState); // Either way means there is not outgoing edge from srcState. return 0; } else { return cell->destState; } } #ifdef DEBUG const char* CodeSeqSM::StateDesc(SM_STATE_ID stateID) { static char s_StateDesc[500]; static SM_OPCODE s_StateDescOpcodes[MAX_CODE_SEQUENCE_LENGTH]; if (stateID == 0) { return "invalid"; } if (stateID == SM_STATE_ID_START) { return "start"; } unsigned i = 0; SM_STATE_ID b = stateID; while (States[b].prevState != 0) { s_StateDescOpcodes[i] = States[b].opc; b = States[b].prevState; ++i; } assert(i == States[stateID].length && i > 0); *s_StateDesc = 0; while (--i > 0) { strcat(s_StateDesc, smOpcodeNames[s_StateDescOpcodes[i]]); strcat(s_StateDesc, " -> "); } strcat(s_StateDesc, smOpcodeNames[s_StateDescOpcodes[0]]); return s_StateDesc; } #endif // DEBUG
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX State machine used in the JIT XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif #include "smcommon.cpp" // // The array to map from EE opcodes (i.e. CEE_ ) to state machine opcodes (i.e. SM_ ) // const SM_OPCODE smOpcodeMap[] = { #define OPCODEMAP(eename, eestring, smname) smname, #include "smopcodemap.def" #undef OPCODEMAP }; // ????????? How to make this method inlinable, since it refers to smOpcodeMap???? /* static */ SM_OPCODE CodeSeqSM::MapToSMOpcode(OPCODE opcode) { assert(opcode < CEE_COUNT); SM_OPCODE smOpcode = smOpcodeMap[opcode]; assert(smOpcode < SM_COUNT); return smOpcode; } void CodeSeqSM::Start(Compiler* comp) { pComp = comp; States = gp_SMStates; JumpTableCells = gp_SMJumpTableCells; StateWeights = gp_StateWeights; NativeSize = 0; Reset(); } void CodeSeqSM::Reset() { curState = SM_STATE_ID_START; } void CodeSeqSM::End() { if (States[curState].term) { TermStateMatch(curState DEBUGARG(pComp->verbose)); } } void CodeSeqSM::Run(SM_OPCODE opcode DEBUGARG(int level)) { SM_STATE_ID nextState; SM_STATE_ID rollbackState; SM_OPCODE opcodesToRevisit[MAX_CODE_SEQUENCE_LENGTH]; assert(level <= MAX_CODE_SEQUENCE_LENGTH); _Next: nextState = GetDestState(curState, opcode); if (nextState != 0) { // This is easy, Just go to the next state. curState = nextState; return; } assert(curState != SM_STATE_ID_START); if (States[curState].term) { TermStateMatch(curState DEBUGARG(pComp->verbose)); curState = SM_STATE_ID_START; goto _Next; } // This is hard. We need to rollback to the longest matched term state and restart from there. rollbackState = States[curState].longestTermState; TermStateMatch(rollbackState DEBUGARG(pComp->verbose)); assert(States[curState].length > States[rollbackState].length); unsigned numOfOpcodesToRevisit = States[curState].length - States[rollbackState].length + 1; assert(numOfOpcodesToRevisit > 1 && numOfOpcodesToRevisit <= MAX_CODE_SEQUENCE_LENGTH); // So it can fit in the local array opcodesToRevisit[] SM_OPCODE* p = opcodesToRevisit + (numOfOpcodesToRevisit - 1); *p = opcode; // Fill in the local array: for (unsigned i = 0; i < numOfOpcodesToRevisit - 1; ++i) { *(--p) = States[curState].opc; curState = States[curState].prevState; } assert(curState == rollbackState); // Now revisit these opcodes, starting from SM_STATE_ID_START. curState = SM_STATE_ID_START; for (p = opcodesToRevisit; p < opcodesToRevisit + numOfOpcodesToRevisit; ++p) { Run(*p DEBUGARG(level + 1)); } } SM_STATE_ID CodeSeqSM::GetDestState(SM_STATE_ID srcState, SM_OPCODE opcode) { assert(opcode < SM_COUNT); JumpTableCell* pThisJumpTable = (JumpTableCell*)(((PBYTE)JumpTableCells) + States[srcState].jumpTableByteOffset); JumpTableCell* cell = pThisJumpTable + opcode; if (cell->srcState != srcState) { assert(cell->srcState == 0 || cell->srcState != srcState); // Either way means there is not outgoing edge from srcState. return 0; } else { return cell->destState; } } #ifdef DEBUG const char* CodeSeqSM::StateDesc(SM_STATE_ID stateID) { static char s_StateDesc[500]; static SM_OPCODE s_StateDescOpcodes[MAX_CODE_SEQUENCE_LENGTH]; if (stateID == 0) { return "invalid"; } if (stateID == SM_STATE_ID_START) { return "start"; } unsigned i = 0; SM_STATE_ID b = stateID; while (States[b].prevState != 0) { s_StateDescOpcodes[i] = States[b].opc; b = States[b].prevState; ++i; } assert(i == States[stateID].length && i > 0); *s_StateDesc = 0; while (--i > 0) { strcat(s_StateDesc, smOpcodeNames[s_StateDescOpcodes[i]]); strcat(s_StateDesc, " -> "); } strcat(s_StateDesc, smOpcodeNames[s_StateDescOpcodes[0]]); return s_StateDesc; } #endif // DEBUG
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/pal/tests/palsuite/c_runtime/logf/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: Tests logf with a normal set of values. ** **===================================================================*/ #include <palsuite.h> // binary32 (float) has a machine epsilon of 2^-23 (approx. 1.19e-07). However, this // is slightly too accurate when writing tests meant to run against libm implementations // for various platforms. 2^-21 (approx. 4.76e-07) seems to be as accurate as we can get. // // The tests themselves will take PAL_EPSILON and adjust it according to the expected result // so that the delta used for comparison will compare the most significant digits and ignore // any digits that are outside the double precision range (6-9 digits). // For example, a test with an expect result in the format of 0.xxxxxxxxx will use PAL_EPSILON // for the variance, while an expected result in the format of 0.0xxxxxxxxx will use // PAL_EPSILON / 10 and and expected result in the format of x.xxxxxx will use PAL_EPSILON * 10. #define PAL_EPSILON 4.76837158e-07 #define PAL_NAN sqrtf(-1.0f) #define PAL_POSINF -logf(0.0f) #define PAL_NEGINF logf(0.0f) /** * Helper test structure */ struct test { float value; /* value to test the function with */ float expected; /* expected result */ float variance; /* maximum delta between the expected and actual result */ }; /** * logf_test1_validate * * test validation function */ void __cdecl logf_test1_validate(float value, float expected, float variance) { float result = logf(value); /* * The test is valid when the difference between result * and expected is less than or equal to variance */ float delta = fabsf(result - expected); if (delta > variance) { Fail("logf(%g) returned %10.9g when it should have returned %10.9g", value, result, expected); } } /** * logf_test1_validate * * test validation function for values returning NaN */ void __cdecl logf_test1_validate_isnan(float value) { float result = logf(value); if (!_isnanf(result)) { Fail("logf(%g) returned %10.9g when it should have returned %10.9g", value, result, PAL_NAN); } } /** * main * * executable entry point */ PALTEST(c_runtime_logf_test1_paltest_logf_test1, "c_runtime/logf/test1/paltest_logf_test1") { struct test tests[] = { /* value expected variance */ { 0, PAL_NEGINF, 0 }, { 0.0432139183f, -3.14159265f, PAL_EPSILON * 10 }, // expected: -(pi) { 0.0659880358f, -2.71828183f, PAL_EPSILON * 10 }, // expected: -(e) { 0.1f, -2.30258509f, PAL_EPSILON * 10 }, // expected: -(ln(10)) { 0.207879576f, -1.57079633f, PAL_EPSILON * 10 }, // expected: -(pi / 2) { 0.236290088f, -1.44269504f, PAL_EPSILON * 10 }, // expected: -(logf2(e)) { 0.243116734f, -1.41421356f, PAL_EPSILON * 10 }, // expected: -(sqrtf(2)) { 0.323557264f, -1.12837917f, PAL_EPSILON * 10 }, // expected: -(2 / sqrtf(pi)) { 0.367879441f, -1, PAL_EPSILON * 10 }, // expected: -(1) { 0.455938128f, -0.785398163f, PAL_EPSILON }, // expected: -(pi / 4) { 0.493068691f, -0.707106781f, PAL_EPSILON }, // expected: -(1 / sqrtf(2)) { 0.5f, -0.693147181f, PAL_EPSILON }, // expected: -(ln(2)) { 0.529077808f, -0.636619772f, PAL_EPSILON }, // expected: -(2 / pi) { 0.647721485f, -0.434294482f, PAL_EPSILON }, // expected: -(log10f(e)) { 0.727377349f, -0.318309886f, PAL_EPSILON }, // expected: -(1 / pi) { 1, 0, PAL_EPSILON }, { 1.37480223f, 0.318309886f, PAL_EPSILON }, // expected: 1 / pi { 1.54387344f, 0.434294482f, PAL_EPSILON }, // expected: log10f(e) { 1.89008116f, 0.636619772f, PAL_EPSILON }, // expected: 2 / pi { 2, 0.693147181f, PAL_EPSILON }, // expected: ln(2) { 2.02811498f, 0.707106781f, PAL_EPSILON }, // expected: 1 / sqrtf(2) { 2.19328005f, 0.785398163f, PAL_EPSILON }, // expected: pi / 4 { 2.71828183f, 1, PAL_EPSILON * 10 }, // value: e { 3.09064302f, 1.12837917f, PAL_EPSILON * 10 }, // expected: 2 / sqrtf(pi) { 4.11325038f, 1.41421356f, PAL_EPSILON * 10 }, // expected: sqrtf(2) { 4.23208611f, 1.44269504f, PAL_EPSILON * 10 }, // expected: logf2(e) { 4.81047738f, 1.57079633f, PAL_EPSILON * 10 }, // expected: pi / 2 { 10, 2.30258509f, PAL_EPSILON * 10 }, // expected: ln(10) { 15.1542622f, 2.71828183f, PAL_EPSILON * 10 }, // expected: e { 23.1406926f, 3.14159265f, PAL_EPSILON * 10 }, // expected: pi { PAL_POSINF, PAL_POSINF, 0 }, }; if (PAL_Initialize(argc, argv) != 0) { return FAIL; } for (int i = 0; i < (sizeof(tests) / sizeof(struct test)); i++) { logf_test1_validate(tests[i].value, tests[i].expected, tests[i].variance); } logf_test1_validate_isnan(PAL_NEGINF); logf_test1_validate_isnan(PAL_NAN); 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: Tests logf with a normal set of values. ** **===================================================================*/ #include <palsuite.h> // binary32 (float) has a machine epsilon of 2^-23 (approx. 1.19e-07). However, this // is slightly too accurate when writing tests meant to run against libm implementations // for various platforms. 2^-21 (approx. 4.76e-07) seems to be as accurate as we can get. // // The tests themselves will take PAL_EPSILON and adjust it according to the expected result // so that the delta used for comparison will compare the most significant digits and ignore // any digits that are outside the double precision range (6-9 digits). // For example, a test with an expect result in the format of 0.xxxxxxxxx will use PAL_EPSILON // for the variance, while an expected result in the format of 0.0xxxxxxxxx will use // PAL_EPSILON / 10 and and expected result in the format of x.xxxxxx will use PAL_EPSILON * 10. #define PAL_EPSILON 4.76837158e-07 #define PAL_NAN sqrtf(-1.0f) #define PAL_POSINF -logf(0.0f) #define PAL_NEGINF logf(0.0f) /** * Helper test structure */ struct test { float value; /* value to test the function with */ float expected; /* expected result */ float variance; /* maximum delta between the expected and actual result */ }; /** * logf_test1_validate * * test validation function */ void __cdecl logf_test1_validate(float value, float expected, float variance) { float result = logf(value); /* * The test is valid when the difference between result * and expected is less than or equal to variance */ float delta = fabsf(result - expected); if (delta > variance) { Fail("logf(%g) returned %10.9g when it should have returned %10.9g", value, result, expected); } } /** * logf_test1_validate * * test validation function for values returning NaN */ void __cdecl logf_test1_validate_isnan(float value) { float result = logf(value); if (!_isnanf(result)) { Fail("logf(%g) returned %10.9g when it should have returned %10.9g", value, result, PAL_NAN); } } /** * main * * executable entry point */ PALTEST(c_runtime_logf_test1_paltest_logf_test1, "c_runtime/logf/test1/paltest_logf_test1") { struct test tests[] = { /* value expected variance */ { 0, PAL_NEGINF, 0 }, { 0.0432139183f, -3.14159265f, PAL_EPSILON * 10 }, // expected: -(pi) { 0.0659880358f, -2.71828183f, PAL_EPSILON * 10 }, // expected: -(e) { 0.1f, -2.30258509f, PAL_EPSILON * 10 }, // expected: -(ln(10)) { 0.207879576f, -1.57079633f, PAL_EPSILON * 10 }, // expected: -(pi / 2) { 0.236290088f, -1.44269504f, PAL_EPSILON * 10 }, // expected: -(logf2(e)) { 0.243116734f, -1.41421356f, PAL_EPSILON * 10 }, // expected: -(sqrtf(2)) { 0.323557264f, -1.12837917f, PAL_EPSILON * 10 }, // expected: -(2 / sqrtf(pi)) { 0.367879441f, -1, PAL_EPSILON * 10 }, // expected: -(1) { 0.455938128f, -0.785398163f, PAL_EPSILON }, // expected: -(pi / 4) { 0.493068691f, -0.707106781f, PAL_EPSILON }, // expected: -(1 / sqrtf(2)) { 0.5f, -0.693147181f, PAL_EPSILON }, // expected: -(ln(2)) { 0.529077808f, -0.636619772f, PAL_EPSILON }, // expected: -(2 / pi) { 0.647721485f, -0.434294482f, PAL_EPSILON }, // expected: -(log10f(e)) { 0.727377349f, -0.318309886f, PAL_EPSILON }, // expected: -(1 / pi) { 1, 0, PAL_EPSILON }, { 1.37480223f, 0.318309886f, PAL_EPSILON }, // expected: 1 / pi { 1.54387344f, 0.434294482f, PAL_EPSILON }, // expected: log10f(e) { 1.89008116f, 0.636619772f, PAL_EPSILON }, // expected: 2 / pi { 2, 0.693147181f, PAL_EPSILON }, // expected: ln(2) { 2.02811498f, 0.707106781f, PAL_EPSILON }, // expected: 1 / sqrtf(2) { 2.19328005f, 0.785398163f, PAL_EPSILON }, // expected: pi / 4 { 2.71828183f, 1, PAL_EPSILON * 10 }, // value: e { 3.09064302f, 1.12837917f, PAL_EPSILON * 10 }, // expected: 2 / sqrtf(pi) { 4.11325038f, 1.41421356f, PAL_EPSILON * 10 }, // expected: sqrtf(2) { 4.23208611f, 1.44269504f, PAL_EPSILON * 10 }, // expected: logf2(e) { 4.81047738f, 1.57079633f, PAL_EPSILON * 10 }, // expected: pi / 2 { 10, 2.30258509f, PAL_EPSILON * 10 }, // expected: ln(10) { 15.1542622f, 2.71828183f, PAL_EPSILON * 10 }, // expected: e { 23.1406926f, 3.14159265f, PAL_EPSILON * 10 }, // expected: pi { PAL_POSINF, PAL_POSINF, 0 }, }; if (PAL_Initialize(argc, argv) != 0) { return FAIL; } for (int i = 0; i < (sizeof(tests) / sizeof(struct test)); i++) { logf_test1_validate(tests[i].value, tests[i].expected, tests[i].variance); } logf_test1_validate_isnan(PAL_NEGINF); logf_test1_validate_isnan(PAL_NAN); PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/pal/tests/palsuite/locale_info/GetLocaleInfoW/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: Tests that GetLocaleInfoW gives the correction information for ** LOCALE_NEUTRAL. ** ** **==========================================================================*/ #include <palsuite.h> int Types[] = { LOCALE_SDECIMAL, LOCALE_STHOUSAND, LOCALE_ILZERO, LOCALE_SCURRENCY, LOCALE_SMONDECIMALSEP, LOCALE_SMONTHOUSANDSEP }; char *TypeStrings[] = { "LOCALE_SDECIMAL", "LOCALE_STHOUSAND", "LOCALE_ILZERO", "LOCALE_SCURRENCY", "LOCALE_SMONDECIMALSEP", "LOCALE_SMONTHOUSANDSEP" }; typedef WCHAR InfoStrings[ARRAY_SIZE(Types)][4]; typedef struct { LCID lcid; InfoStrings Strings; } LocalInfoType; LocalInfoType Locales[] = { {LOCALE_NEUTRAL, {{'.',0}, {',',0}, {'1',0}, {'$',0}, {'.',0}, {',',0}}}, }; int NumLocales = sizeof(Locales) / sizeof(Locales[0]); PALTEST(locale_info_GetLocaleInfoW_test1_paltest_getlocaleinfow_test1, "locale_info/GetLocaleInfoW/test1/paltest_getlocaleinfow_test1") { WCHAR buffer[256] = { 0 }; int ret; int i,j; if (PAL_Initialize(argc, argv)) { return FAIL; } for (i=0; i<NumLocales; i++) { for (j=0; j < ARRAY_SIZE(Types); j++) { ret = GetLocaleInfoW(Locales[i].lcid, Types[j], buffer, 256); if (ret == 0) { Fail("GetLocaleInfoW returned an unexpected error!\n"); } if (wcscmp(buffer, Locales[i].Strings[j]) != 0) { Fail("GetLocaleInfoW gave incorrect result for %s, " "locale %#x:\nExpected \"%S\", got \"%S\"!\n", TypeStrings[j], Locales[i].lcid, Locales[i].Strings[j], buffer); } if (ret != wcslen(Locales[i].Strings[j]) + 1) { Fail("GetLocaleInfoW returned incorrect value for %s, " "locale %#x:\nExpected %d, got %d!\n", TypeStrings[j], Locales[i].lcid, wcslen(Locales[i].Strings[j])+1, ret); } } } 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: Tests that GetLocaleInfoW gives the correction information for ** LOCALE_NEUTRAL. ** ** **==========================================================================*/ #include <palsuite.h> int Types[] = { LOCALE_SDECIMAL, LOCALE_STHOUSAND, LOCALE_ILZERO, LOCALE_SCURRENCY, LOCALE_SMONDECIMALSEP, LOCALE_SMONTHOUSANDSEP }; char *TypeStrings[] = { "LOCALE_SDECIMAL", "LOCALE_STHOUSAND", "LOCALE_ILZERO", "LOCALE_SCURRENCY", "LOCALE_SMONDECIMALSEP", "LOCALE_SMONTHOUSANDSEP" }; typedef WCHAR InfoStrings[ARRAY_SIZE(Types)][4]; typedef struct { LCID lcid; InfoStrings Strings; } LocalInfoType; LocalInfoType Locales[] = { {LOCALE_NEUTRAL, {{'.',0}, {',',0}, {'1',0}, {'$',0}, {'.',0}, {',',0}}}, }; int NumLocales = sizeof(Locales) / sizeof(Locales[0]); PALTEST(locale_info_GetLocaleInfoW_test1_paltest_getlocaleinfow_test1, "locale_info/GetLocaleInfoW/test1/paltest_getlocaleinfow_test1") { WCHAR buffer[256] = { 0 }; int ret; int i,j; if (PAL_Initialize(argc, argv)) { return FAIL; } for (i=0; i<NumLocales; i++) { for (j=0; j < ARRAY_SIZE(Types); j++) { ret = GetLocaleInfoW(Locales[i].lcid, Types[j], buffer, 256); if (ret == 0) { Fail("GetLocaleInfoW returned an unexpected error!\n"); } if (wcscmp(buffer, Locales[i].Strings[j]) != 0) { Fail("GetLocaleInfoW gave incorrect result for %s, " "locale %#x:\nExpected \"%S\", got \"%S\"!\n", TypeStrings[j], Locales[i].lcid, Locales[i].Strings[j], buffer); } if (ret != wcslen(Locales[i].Strings[j]) + 1) { Fail("GetLocaleInfoW returned incorrect value for %s, " "locale %#x:\nExpected %d, got %d!\n", TypeStrings[j], Locales[i].lcid, wcslen(Locales[i].Strings[j])+1, ret); } } } PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/unwinder/loongarch64/unwinder_loongarch64.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // #include "stdafx.h" #include "utilcode.h" #include "crosscomp.h" #include "unwinder_loongarch64.h" typedef struct _LOONGARCH64_KTRAP_FRAME { // // Exception active indicator. // // 0 - interrupt frame. // 1 - exception frame. // 2 - service frame. // /* +0x000 */ UCHAR ExceptionActive; // always valid /* +0x001 */ UCHAR ContextFromKFramesUnwound; // set if KeContextFromKFrames created this frame /* +0x002 */ UCHAR DebugRegistersValid; // always valid /* +0x003 */ union { UCHAR PreviousMode; // system services only UCHAR PreviousIrql; // interrupts only }; // // Page fault information (page faults only) // Previous trap frame address (system services only) // // Organized this way to allow first couple words to be used // for scratch space in the general case // /* +0x004 */ ULONG FaultStatus; // page faults only /* +0x008 */ union { ULONG64 FaultAddress; // page faults only ULONG64 TrapFrame; // system services only }; // // The LOONGARCH architecture does not have an architectural trap frame. On // an exception or interrupt, the processor switches to an // exception-specific processor mode in which at least the RA and SP // registers are banked. Software is responsible for preserving // registers which reflect the processor state in which the // exception occurred rather than any intermediate processor modes. // // // Volatile floating point state is dynamically allocated; this // pointer may be NULL if the FPU was not enabled at the time the // trap was taken. // /* +0x010 */ PVOID VfpState; // // Volatile registers // ULONG64 R[19]; ULONG64 Tp; ULONG64 Sp; ULONG64 Fp; ULONG64 Ra; ULONG64 Pc; } LOONGARCH64_KTRAP_FRAME, *PLOONGARCH64_KTRAP_FRAME; typedef struct _LOONGARCH64_VFP_STATE { struct _LOONGARCH64_VFP_STATE *Link; // link to next state entry ULONG Fcsr; // FCSR register ULONG64 F[32]; // All F registers (0-31) } LOONGARCH64_VFP_STATE, *PLOONGARCH64_VFP_STATE, KLOONGARCH64_VFP_STATE, *PKLOONGARCH64_VFP_STATE; // // Parameters describing the unwind codes. // #define STATUS_UNWIND_UNSUPPORTED_VERSION STATUS_UNSUCCESSFUL #define STATUS_UNWIND_NOT_IN_FUNCTION STATUS_UNSUCCESSFUL #define STATUS_UNWIND_INVALID_SEQUENCE STATUS_UNSUCCESSFUL // // Macros for accessing memory. These can be overridden if other code // (in particular the debugger) needs to use them. #define MEMORY_READ_BYTE(params, addr) (*dac_cast<PTR_BYTE>(addr)) #define MEMORY_READ_DWORD(params, addr) (*dac_cast<PTR_DWORD>(addr)) #define MEMORY_READ_QWORD(params, addr) (*dac_cast<PTR_UINT64>(addr)) typedef struct _LOONGARCH64_UNWIND_PARAMS { PT_KNONVOLATILE_CONTEXT_POINTERS ContextPointers; } LOONGARCH64_UNWIND_PARAMS, *PLOONGARCH64_UNWIND_PARAMS; #define UNWIND_PARAMS_SET_TRAP_FRAME(Params, Address, Size) #define UPDATE_CONTEXT_POINTERS(Params, RegisterNumber, Address) \ do { \ if (ARGUMENT_PRESENT(Params)) { \ PT_KNONVOLATILE_CONTEXT_POINTERS ContextPointers = (Params)->ContextPointers; \ if (ARGUMENT_PRESENT(ContextPointers)) { \ if (RegisterNumber == 22) \ ContextPointers->Fp = (PDWORD64)Address; \ else if (RegisterNumber >= 23 && RegisterNumber <= 31) { \ (&ContextPointers->S0)[RegisterNumber - 23] = (PDWORD64)Address; \ } \ } \ } \ } while (0) #define UPDATE_FP_CONTEXT_POINTERS(Params, RegisterNumber, Address) \ do { \ if (ARGUMENT_PRESENT(Params)) { \ PT_KNONVOLATILE_CONTEXT_POINTERS ContextPointers = (Params)->ContextPointers; \ if (ARGUMENT_PRESENT(ContextPointers) && \ (RegisterNumber >= 24) && \ (RegisterNumber <= 31)) { \ \ (&ContextPointers->F24)[RegisterNumber - 24] = (PDWORD64)Address; \ } \ } \ } while (0) #define VALIDATE_STACK_ADDRESS_EX(Params, Context, Address, DataSize, Alignment, OutStatus) #define VALIDATE_STACK_ADDRESS(Params, Context, DataSize, Alignment, OutStatus) // // Macros to clarify opcode parsing // #define OPCODE_IS_END(Op) (((Op) & 0xfe) == 0xe4) // // This table describes the size of each unwind code, in bytes // static const BYTE UnwindCodeSizeTable[256] = { 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2, 3,2,2,2,3,2,2,2, 3,2,2,2,2,2,3,2, 3,2,3,2,3,2,2,2, 4,1,3,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1 }; NTSTATUS RtlpUnwindCustom( __inout PT_CONTEXT ContextRecord, _In_ BYTE Opcode, _In_ PLOONGARCH64_UNWIND_PARAMS UnwindParams ) /*++ Routine Description: Handles custom unwinding operations involving machine-specific frames. Arguments: ContextRecord - Supplies the address of a context record. Opcode - The opcode to decode. UnwindParams - Additional parameters shared with caller. Return Value: An NTSTATUS indicating either STATUS_SUCCESS if everything went ok, or another status code if there were problems. --*/ { ULONG Fcsr; ULONG RegIndex; ULONG_PTR SourceAddress; ULONG_PTR StartingSp; NTSTATUS Status; ULONG_PTR VfpStateAddress; StartingSp = ContextRecord->Sp; Status = STATUS_SUCCESS; // // The opcode describes the special-case stack // switch (Opcode) { // // Trap frame case // case 0xe8: // MSFT_OP_TRAP_FRAME: // // Ensure there is enough valid space for the trap frame // VALIDATE_STACK_ADDRESS(UnwindParams, ContextRecord, sizeof(LOONGARCH64_KTRAP_FRAME), 16, &Status); if (!NT_SUCCESS(Status)) { return Status; } // // Restore R0-R15, and F0-F32 // SourceAddress = StartingSp + FIELD_OFFSET(LOONGARCH64_KTRAP_FRAME, R); for (RegIndex = 0; RegIndex < 16; RegIndex++) { UPDATE_CONTEXT_POINTERS(UnwindParams, RegIndex, SourceAddress); #ifdef __GNUC__ *(&ContextRecord->R0 + RegIndex) = MEMORY_READ_QWORD(UnwindParams, SourceAddress); #else ContextRecord->R[RegIndex] = MEMORY_READ_QWORD(UnwindParams, SourceAddress); #endif SourceAddress += sizeof(ULONG_PTR); } SourceAddress = StartingSp + FIELD_OFFSET(LOONGARCH64_KTRAP_FRAME, VfpState); VfpStateAddress = MEMORY_READ_QWORD(UnwindParams, SourceAddress); if (VfpStateAddress != 0) { SourceAddress = VfpStateAddress + FIELD_OFFSET(KLOONGARCH64_VFP_STATE, Fcsr); Fcsr = MEMORY_READ_DWORD(UnwindParams, SourceAddress); if (Fcsr != (ULONG)-1) { ContextRecord->Fcsr = Fcsr; SourceAddress = VfpStateAddress + FIELD_OFFSET(KLOONGARCH64_VFP_STATE, F); for (RegIndex = 0; RegIndex < 32; RegIndex++) { UPDATE_FP_CONTEXT_POINTERS(UnwindParams, RegIndex, SourceAddress); ContextRecord->F[RegIndex] = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress += 2 * sizeof(ULONGLONG); } } } // // Restore SP, RA, PC, and the status registers // //SourceAddress = StartingSp + FIELD_OFFSET(LOONGARCH64_KTRAP_FRAME, Tp);//TP //ContextRecord->Tp = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress = StartingSp + FIELD_OFFSET(LOONGARCH64_KTRAP_FRAME, Sp); ContextRecord->Sp = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress = StartingSp + FIELD_OFFSET(LOONGARCH64_KTRAP_FRAME, Fp); ContextRecord->Fp = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress = StartingSp + FIELD_OFFSET(LOONGARCH64_KTRAP_FRAME, Ra); ContextRecord->Ra = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress = StartingSp + FIELD_OFFSET(LOONGARCH64_KTRAP_FRAME, Pc); ContextRecord->Pc = MEMORY_READ_QWORD(UnwindParams, SourceAddress); // // Set the trap frame and clear the unwound-to-call flag // UNWIND_PARAMS_SET_TRAP_FRAME(UnwindParams, StartingSp, sizeof(LOONGARCH64_KTRAP_FRAME)); ContextRecord->ContextFlags &= ~CONTEXT_UNWOUND_TO_CALL; break; // // Context case // case 0xea: // MSFT_OP_CONTEXT: // // Ensure there is enough valid space for the full CONTEXT structure // VALIDATE_STACK_ADDRESS(UnwindParams, ContextRecord, sizeof(CONTEXT), 16, &Status); if (!NT_SUCCESS(Status)) { return Status; } // // Restore R0-R23, and F0-F31 // SourceAddress = StartingSp + FIELD_OFFSET(T_CONTEXT, R0); for (RegIndex = 0; RegIndex < 23; RegIndex++) { UPDATE_CONTEXT_POINTERS(UnwindParams, RegIndex, SourceAddress); #ifdef __GNUC__ *(&ContextRecord->R0 + RegIndex) = MEMORY_READ_QWORD(UnwindParams, SourceAddress); #else ContextRecord->R[RegIndex] = MEMORY_READ_QWORD(UnwindParams, SourceAddress); #endif SourceAddress += sizeof(ULONG_PTR); } SourceAddress = StartingSp + FIELD_OFFSET(T_CONTEXT, F); for (RegIndex = 0; RegIndex < 32; RegIndex++) { UPDATE_FP_CONTEXT_POINTERS(UnwindParams, RegIndex, SourceAddress); ContextRecord->F[RegIndex] = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress += 2 * sizeof(ULONGLONG); } // // Restore SP, RA, PC, and the status registers // SourceAddress = StartingSp + FIELD_OFFSET(T_CONTEXT, Fp); ContextRecord->Fp = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress = StartingSp + FIELD_OFFSET(T_CONTEXT, Sp); ContextRecord->Sp = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress = StartingSp + FIELD_OFFSET(T_CONTEXT, Pc); ContextRecord->Pc = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress = StartingSp + FIELD_OFFSET(T_CONTEXT, Fcsr); ContextRecord->Fcsr = MEMORY_READ_DWORD(UnwindParams, SourceAddress); // // Inherit the unwound-to-call flag from this context // SourceAddress = StartingSp + FIELD_OFFSET(T_CONTEXT, ContextFlags); ContextRecord->ContextFlags &= ~CONTEXT_UNWOUND_TO_CALL; ContextRecord->ContextFlags |= MEMORY_READ_DWORD(UnwindParams, SourceAddress) & CONTEXT_UNWOUND_TO_CALL; break; default: return STATUS_UNSUCCESSFUL; } return STATUS_SUCCESS; } ULONG RtlpComputeScopeSize( _In_ ULONG_PTR UnwindCodePtr, _In_ ULONG_PTR UnwindCodesEndPtr, _In_ BOOLEAN IsEpilog, _In_ PLOONGARCH64_UNWIND_PARAMS UnwindParams ) /*++ Routine Description: Computes the size of an prolog or epilog, in words. Arguments: UnwindCodePtr - Supplies a pointer to the start of the unwind code sequence. UnwindCodesEndPtr - Supplies a pointer to the byte immediately following the unwind code table, as described by the header. IsEpilog - Specifies TRUE if the scope describes an epilog, or FALSE if it describes a prolog. UnwindParams - Additional parameters shared with caller. Return Value: The size of the scope described by the unwind codes, in halfword units. --*/ { ULONG ScopeSize; BYTE Opcode; // // Iterate through the unwind codes until we hit an end marker. // While iterating, accumulate the total scope size. // ScopeSize = 0; Opcode = 0; while (UnwindCodePtr < UnwindCodesEndPtr) { Opcode = MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); if (OPCODE_IS_END(Opcode)) { break; } UnwindCodePtr += UnwindCodeSizeTable[Opcode]; ScopeSize++; } // // Epilogs have one extra instruction at the end that needs to be // accounted for. // if (IsEpilog) { ScopeSize++; } return ScopeSize; } NTSTATUS RtlpUnwindRestoreRegisterRange( __inout PT_CONTEXT ContextRecord, _In_ LONG SpOffset, _In_ ULONG FirstRegister, _In_ ULONG RegisterCount, _In_ PLOONGARCH64_UNWIND_PARAMS UnwindParams ) /*++ Routine Description: Restores a series of integer registers from the stack. Arguments: ContextRecord - Supplies the address of a context record. SpOffset - Specifies a stack offset. Positive values are simply used as a base offset. Negative values assume a predecrement behavior: a 0 offset is used for restoration, but the absolute value of the offset is added to the final Sp. FirstRegister - Specifies the index of the first register to restore. RegisterCount - Specifies the number of registers to restore. UnwindParams - Additional parameters shared with caller. Return Value: None. --*/ { ULONG_PTR CurAddress; ULONG RegIndex; NTSTATUS Status; // // Compute the source address and validate it. // CurAddress = ContextRecord->Sp; if (SpOffset >= 0) { CurAddress += SpOffset; } Status = STATUS_SUCCESS; VALIDATE_STACK_ADDRESS(UnwindParams, ContextRecord, 8 * RegisterCount, 8, &Status); if (Status != STATUS_SUCCESS) { return Status; } // // Restore the registers // for (RegIndex = 0; RegIndex < RegisterCount; RegIndex++) { UPDATE_CONTEXT_POINTERS(UnwindParams, FirstRegister + RegIndex, CurAddress); #ifdef __GNUC__ *(&ContextRecord->R0 + FirstRegister + RegIndex) = MEMORY_READ_QWORD(UnwindParams, CurAddress); #else ContextRecord->R[FirstRegister + RegIndex] = MEMORY_READ_QWORD(UnwindParams, CurAddress); #endif CurAddress += 8; } if (SpOffset < 0) { ContextRecord->Sp -= SpOffset; } return STATUS_SUCCESS; } NTSTATUS RtlpUnwindRestoreFpRegisterRange( __inout PT_CONTEXT ContextRecord, _In_ LONG SpOffset, _In_ ULONG FirstRegister, _In_ ULONG RegisterCount, _In_ PLOONGARCH64_UNWIND_PARAMS UnwindParams ) /*++ Routine Description: Restores a series of floating-point registers from the stack. Arguments: ContextRecord - Supplies the address of a context record. SpOffset - Specifies a stack offset. Positive values are simply used as a base offset. Negative values assume a predecrement behavior: a 0 offset is used for restoration, but the absolute value of the offset is added to the final Sp. FirstRegister - Specifies the index of the first register to restore. RegisterCount - Specifies the number of registers to restore. UnwindParams - Additional parameters shared with caller. Return Value: None. --*/ { ULONG_PTR CurAddress; ULONG RegIndex; NTSTATUS Status; // // Compute the source address and validate it. // CurAddress = ContextRecord->Sp; if (SpOffset >= 0) { CurAddress += SpOffset; } Status = STATUS_SUCCESS; VALIDATE_STACK_ADDRESS(UnwindParams, ContextRecord, 8 * RegisterCount, 8, &Status); if (Status != STATUS_SUCCESS) { return Status; } // // Restore the registers // for (RegIndex = 0; RegIndex < RegisterCount; RegIndex++) { UPDATE_FP_CONTEXT_POINTERS(UnwindParams, FirstRegister + RegIndex, CurAddress); ContextRecord->F[FirstRegister + RegIndex] = MEMORY_READ_QWORD(UnwindParams, CurAddress); CurAddress += 8; } if (SpOffset < 0) { ContextRecord->Sp -= SpOffset; } return STATUS_SUCCESS; } NTSTATUS RtlpUnwindFunctionFull( _In_ DWORD64 ControlPcRva, _In_ ULONG_PTR ImageBase, _In_ PT_RUNTIME_FUNCTION FunctionEntry, __inout T_CONTEXT *ContextRecord, _Out_ PDWORD64 EstablisherFrame, __deref_opt_out_opt PEXCEPTION_ROUTINE *HandlerRoutine, _Out_ PVOID *HandlerData, _In_ PLOONGARCH64_UNWIND_PARAMS UnwindParams ) /*++ Routine Description: This function virtually unwinds the specified function by parsing the .xdata record to determine where in the function the provided ControlPc is, and then executing unwind codes that map to the function's prolog or epilog behavior. If a context pointers record is specified (in the UnwindParams), then the address where each nonvolatile register is restored from is recorded in the appropriate element of the context pointers record. Arguments: ControlPcRva - Supplies the address where control left the specified function, as an offset relative to the IamgeBase. ImageBase - Supplies the base address of the image that contains the function being unwound. FunctionEntry - Supplies the address of the function table entry for the specified function. If appropriate, this should have already been probed. ContextRecord - Supplies the address of a context record. EstablisherFrame - Supplies a pointer to a variable that receives the the establisher frame pointer value. HandlerRoutine - Supplies an optional pointer to a variable that receives the handler routine address. If control did not leave the specified function in either the prolog or an epilog and a handler of the proper type is associated with the function, then the address of the language specific exception handler is returned. Otherwise, NULL is returned. HandlerData - Supplies a pointer to a variable that receives a pointer the the language handler data. UnwindParams - Additional parameters shared with caller. Return Value: STATUS_SUCCESS if the unwind could be completed, a failure status otherwise. Unwind can only fail when validation bounds are specified. --*/ { ULONG AccumulatedSaveNexts; ULONG CurCode; ULONG EpilogScopeCount; PEXCEPTION_ROUTINE ExceptionHandler; PVOID ExceptionHandlerData; BOOLEAN FinalPcFromRa; ULONG FunctionLength; ULONG HeaderWord; ULONG NextCode, NextCode1, NextCode2; DWORD64 OffsetInFunction; ULONG ScopeNum; ULONG ScopeSize; ULONG ScopeStart; DWORD64 SkipWords; NTSTATUS Status; ULONG_PTR UnwindCodePtr; ULONG_PTR UnwindCodesEndPtr; ULONG_PTR UnwindDataPtr; ULONG UnwindIndex; ULONG UnwindWords; // // Unless a special frame is enountered, assume that any unwinding // will return us to the return address of a call and set the flag // appropriately (it will be cleared again if the special cases apply). // ContextRecord->ContextFlags |= CONTEXT_UNWOUND_TO_CALL; // // By default, unwinding is done by popping to the RA, then copying // that RA to the PC. However, some special opcodes require different // behavior. // FinalPcFromRa = TRUE; // // Fetch the header word from the .xdata blob // UnwindDataPtr = ImageBase + FunctionEntry->UnwindData; HeaderWord = MEMORY_READ_DWORD(UnwindParams, UnwindDataPtr); UnwindDataPtr += 4; // // Verify the version before we do anything else // if (((HeaderWord >> 18) & 3) != 0) { assert(!"ShouldNotReachHere"); return STATUS_UNWIND_UNSUPPORTED_VERSION; } FunctionLength = HeaderWord & 0x3ffff; OffsetInFunction = (ControlPcRva - FunctionEntry->BeginAddress) / 4; // // Determine the number of epilog scope records and the maximum number // of unwind codes. // UnwindWords = (HeaderWord >> 27) & 31; EpilogScopeCount = (HeaderWord >> 22) & 31; if (EpilogScopeCount == 0 && UnwindWords == 0) { EpilogScopeCount = MEMORY_READ_DWORD(UnwindParams, UnwindDataPtr); UnwindDataPtr += 4; UnwindWords = (EpilogScopeCount >> 16) & 0xff; EpilogScopeCount &= 0xffff; } if ((HeaderWord & (1 << 21)) != 0) { UnwindIndex = EpilogScopeCount; EpilogScopeCount = 0; } // // If exception data is present, extract it now. // ExceptionHandler = NULL; ExceptionHandlerData = NULL; if ((HeaderWord & (1 << 20)) != 0) { ExceptionHandler = (PEXCEPTION_ROUTINE)(ImageBase + MEMORY_READ_DWORD(UnwindParams, UnwindDataPtr + 4 * (EpilogScopeCount + UnwindWords))); ExceptionHandlerData = (PVOID)(UnwindDataPtr + 4 * (EpilogScopeCount + UnwindWords + 1)); } // // Unless we are in a prolog/epilog, we execute the unwind codes // that immediately follow the epilog scope list. // UnwindCodePtr = UnwindDataPtr + 4 * EpilogScopeCount; UnwindCodesEndPtr = UnwindCodePtr + 4 * UnwindWords; SkipWords = 0; // // If we're near the start of the function, and this function has a prolog, // compute the size of the prolog from the unwind codes. If we're in the // midst of it, we still execute starting at unwind code index 0, but we may // need to skip some to account for partial execution of the prolog. // // N.B. As an optimization here, note that each byte of unwind codes can // describe at most one 32-bit instruction. Thus, the largest prologue // that could possibly be described by UnwindWords (which is 4 * the // number of unwind code bytes) is 4 * UnwindWords words. If // OffsetInFunction is larger than this value, it is guaranteed to be // in the body of the function. // if (OffsetInFunction < 4 * UnwindWords) { ScopeSize = RtlpComputeScopeSize(UnwindCodePtr, UnwindCodesEndPtr, FALSE, UnwindParams); if (OffsetInFunction < ScopeSize) { SkipWords = ScopeSize - OffsetInFunction; ExceptionHandler = NULL; ExceptionHandlerData = NULL; goto ExecuteCodes; } } // // We're not in the prolog, now check to see if we are in the epilog. // In the simple case, the 'E' bit is set indicating there is a single // epilog that lives at the end of the function. If we're near the end // of the function, compute the actual size of the epilog from the // unwind codes. If we're in the midst of it, adjust the unwind code // pointer to the start of the codes and determine how many we need to skip. // // N.B. Similar to the prolog case above, the maximum number of halfwords // that an epilog can cover is limited by UnwindWords. In the epilog // case, however, the starting index within the unwind code table is // non-zero, and so the maximum number of unwind codes that can pertain // to an epilog is (UnwindWords * 4 - UnwindIndex), thus further // constraining the bounds of the epilog. // if ((HeaderWord & (1 << 21)) != 0) { if (OffsetInFunction + (4 * UnwindWords - UnwindIndex) >= FunctionLength) { ScopeSize = RtlpComputeScopeSize(UnwindCodePtr + UnwindIndex, UnwindCodesEndPtr, TRUE, UnwindParams); ScopeStart = FunctionLength - ScopeSize; if (OffsetInFunction >= ScopeStart) { UnwindCodePtr += UnwindIndex; SkipWords = OffsetInFunction - ScopeStart; ExceptionHandler = NULL; ExceptionHandlerData = NULL; } } } // // In the multiple-epilog case, we scan forward to see if we are within // shooting distance of any of the epilogs. If we are, we compute the // actual size of the epilog from the unwind codes and proceed like the // simple case above. // else { for (ScopeNum = 0; ScopeNum < EpilogScopeCount; ScopeNum++) { HeaderWord = MEMORY_READ_DWORD(UnwindParams, UnwindDataPtr); UnwindDataPtr += 4; // // The scope records are stored in order. If we hit a record that // starts after our current position, we must not be in an epilog. // ScopeStart = HeaderWord & 0x3ffff; if (OffsetInFunction < ScopeStart) { break; } UnwindIndex = HeaderWord >> 22; if (OffsetInFunction < ScopeStart + (4 * UnwindWords - UnwindIndex)) { ScopeSize = RtlpComputeScopeSize(UnwindCodePtr + UnwindIndex, UnwindCodesEndPtr, TRUE, UnwindParams); if (OffsetInFunction < ScopeStart + ScopeSize) { UnwindCodePtr += UnwindIndex; SkipWords = OffsetInFunction - ScopeStart; ExceptionHandler = NULL; ExceptionHandlerData = NULL; break; } } } } ExecuteCodes: // // Skip over unwind codes until we account for the number of halfwords // to skip. // while (UnwindCodePtr < UnwindCodesEndPtr && SkipWords > 0) { CurCode = MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); if (OPCODE_IS_END(CurCode)) { break; } UnwindCodePtr += UnwindCodeSizeTable[CurCode]; SkipWords--; } // // Now execute codes until we hit the end. // Status = STATUS_SUCCESS; AccumulatedSaveNexts = 0; while (UnwindCodePtr < UnwindCodesEndPtr && Status == STATUS_SUCCESS) { CurCode = MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr += 1; // // alloc_s (000xxxxx): allocate small stack with size < 1024 (2^5 * 16) // if (CurCode <= 0x1f) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } ContextRecord->Sp += 16 * (CurCode & 0x1f); } // // alloc_m (11000xxx|xxxxxxxx): allocate large stack with size < 32k (2^11 * 16). // else if (CurCode <= 0xc7) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } ContextRecord->Sp += 16 * ((CurCode & 7) << 8); ContextRecord->Sp += 16 * MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr++; } // // save_reg (11010000|000xxxxx|zzzzzzzz): save reg r(1+#X) at [sp+#Z*8], offset <= 2047 // else if (CurCode == 0xd0) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } NextCode = MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr++; NextCode1 = (uint8_t)MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr++; Status = RtlpUnwindRestoreRegisterRange( ContextRecord, 8 * NextCode1, 1 + NextCode, 1, UnwindParams); } // // save_freg (11011100|0xxxzzzz|zzzzzzzz): save reg f(24+#X) at [sp+#Z*8], offset <= 32767 // else if (CurCode == 0xdc) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } NextCode = MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr++; NextCode1 = MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr++; Status = RtlpUnwindRestoreFpRegisterRange( ContextRecord, 8 * (((NextCode & 0xf) << 8) + NextCode1), 24 + (NextCode >> 4), 1, UnwindParams); } // // alloc_l (11100000|xxxxxxxx|xxxxxxxx|xxxxxxxx): allocate large stack with size < 256M // else if (CurCode == 0xe0) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } ContextRecord->Sp += 16 * (MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr) << 16); UnwindCodePtr++; ContextRecord->Sp += 16 * (MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr) << 8); UnwindCodePtr++; ContextRecord->Sp += 16 * MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr++; } // // set_fp (11100001): set up fp: with: ori fp,sp,0 // else if (CurCode == 0xe1) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } ContextRecord->Sp = ContextRecord->Fp; } // // add_fp (11100010|000xxxxx|xxxxxxxx): set up fp with: addi.d fp,sp,#x*8 // else if (CurCode == 0xe2) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } NextCode = MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr++; NextCode1 = MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr++; ContextRecord->Sp = ContextRecord->Fp - 8 * ((NextCode << 8) | NextCode1); } // // nop (11100011): no unwind operation is required // else if (CurCode == 0xe3) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } } // // end (11100100): end of unwind code // else if (CurCode == 0xe4) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } goto finished; } // // end_c (11100101): end of unwind code in current chained scope // else if (CurCode == 0xe5) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } goto finished; } // // custom_0 (111010xx): restore custom structure // else if (CurCode >= 0xe8 && CurCode <= 0xeb) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } Status = RtlpUnwindCustom(ContextRecord, (BYTE) CurCode, UnwindParams); FinalPcFromRa = FALSE; } // // Anything else is invalid // else { return STATUS_UNWIND_INVALID_SEQUENCE; } } // // If we succeeded, post-process the results a bit // finished: if (Status == STATUS_SUCCESS) { // // Since we always POP to the RA, recover the final PC from there, unless // it was overwritten due to a special case custom unwinding operation. // Also set the establisher frame equal to the final stack pointer. // if (FinalPcFromRa) { ContextRecord->Pc = ContextRecord->Ra; } *EstablisherFrame = ContextRecord->Sp; if (ARGUMENT_PRESENT(HandlerRoutine)) { *HandlerRoutine = ExceptionHandler; } *HandlerData = ExceptionHandlerData; } return Status; } NTSTATUS RtlpUnwindFunctionCompact( _In_ DWORD64 ControlPcRva, _In_ PT_RUNTIME_FUNCTION FunctionEntry, __inout T_CONTEXT *ContextRecord, _Out_ PDWORD64 EstablisherFrame, __deref_opt_out_opt PEXCEPTION_ROUTINE *HandlerRoutine, _Out_ PVOID *HandlerData, _In_ PLOONGARCH64_UNWIND_PARAMS UnwindParams ) /*++ Routine Description: This function virtually unwinds the specified function by parsing the compact .pdata record to determine where in the function the provided ControlPc is, and then executing a standard, well-defined set of operations. If a context pointers record is specified (in the UnwindParams), then the address where each nonvolatile register is restored from is recorded in the appropriate element of the context pointers record. Arguments: ControlPcRva - Supplies the address where control left the specified function, as an offset relative to the IamgeBase. FunctionEntry - Supplies the address of the function table entry for the specified function. If appropriate, this should have already been probed. ContextRecord - Supplies the address of a context record. EstablisherFrame - Supplies a pointer to a variable that receives the the establisher frame pointer value. HandlerRoutine - Supplies an optional pointer to a variable that receives the handler routine address. If control did not leave the specified function in either the prolog or an epilog and a handler of the proper type is associated with the function, then the address of the language specific exception handler is returned. Otherwise, NULL is returned. HandlerData - Supplies a pointer to a variable that receives a pointer the the language handler data. UnwindParams - Additional parameters shared with caller. Return Value: STATUS_SUCCESS if the unwind could be completed, a failure status otherwise. Unwind can only fail when validation bounds are specified. --*/ { ULONG Count; ULONG Cr; ULONG CurrentOffset; ULONG EpilogLength; ULONG Flag; ULONG FloatSize; ULONG FrameSize; ULONG FRegOpcodes; ULONG FunctionLength; ULONG HBit; ULONG HOpcodes; ULONG IRegOpcodes; ULONG IntSize; ULONG LocalSize; DWORD64 OffsetInFunction; DWORD64 OffsetInScope; ULONG PrologLength; ULONG RegF; ULONG RegI; ULONG RegSize; ULONG ScopeStart; ULONG StackAdjustOpcodes; NTSTATUS Status; ULONG UnwindData; UnwindData = FunctionEntry->UnwindData; Status = STATUS_SUCCESS; // // Compact records always describe an unwind to a call. // ContextRecord->ContextFlags |= CONTEXT_UNWOUND_TO_CALL; // // Extract the basic information about how to do a full unwind. // Flag = UnwindData & 3; FunctionLength = (UnwindData >> 2) & 0x7ff; RegF = (UnwindData >> 13) & 7; RegI = (UnwindData >> 16) & 0xf; HBit = (UnwindData >> 20) & 1; Cr = (UnwindData >> 21) & 3; FrameSize = (UnwindData >> 23) & 0x1ff; assert(!"---------------LOONGARCH64 ShouldNotReachHere"); if (Flag == 3) { return STATUS_UNWIND_INVALID_SEQUENCE; } if (Cr == 2) { return STATUS_UNWIND_INVALID_SEQUENCE; } // // Determine the size of the locals // IntSize = RegI * 8; if (Cr == 1) { IntSize += 8; } FloatSize = (RegF == 0) ? 0 : (RegF + 1) * 8; RegSize = (IntSize + FloatSize + 8*8 * HBit + 0xf) & ~0xf; if (RegSize > 16 * FrameSize) { return STATUS_UNWIND_INVALID_SEQUENCE; } LocalSize = 16 * FrameSize - RegSize; // // If we're near the start of the function (within 17 words), // see if we are within the prolog. // // N.B. If the low 2 bits of the UnwindData are 2, then we have // no prolog. // OffsetInFunction = (ControlPcRva - FunctionEntry->BeginAddress) / 4; OffsetInScope = 0; if (OffsetInFunction < 17 && Flag != 2) { // // Compute sizes for each opcode in the prolog. // IRegOpcodes = (IntSize + 8) / 16; FRegOpcodes = (FloatSize + 8) / 16; HOpcodes = 4 * HBit; StackAdjustOpcodes = (Cr == 3) ? 1 : 0; if (Cr != 3 || LocalSize > 512) { StackAdjustOpcodes += (LocalSize > 4088) ? 2 : (LocalSize > 0) ? 1 : 0; } // // Compute the total prolog length and determine if we are within // its scope. // // N.B. We must execute prolog operations backwards to unwind, so // our final scope offset in this case is the distance from the end. // PrologLength = IRegOpcodes + FRegOpcodes + HOpcodes + StackAdjustOpcodes; if (OffsetInFunction < PrologLength) { OffsetInScope = PrologLength - OffsetInFunction; } } // // If we're near the end of the function (within 15 words), see if // we are within the epilog. // // N.B. If the low 2 bits of the UnwindData are 2, then we have // no epilog. // if (OffsetInScope == 0 && OffsetInFunction + 15 >= FunctionLength && Flag != 2) { // // Compute sizes for each opcode in the epilog. // IRegOpcodes = (IntSize + 8) / 16; FRegOpcodes = (FloatSize + 8) / 16; HOpcodes = HBit; StackAdjustOpcodes = (Cr == 3) ? 1 : 0; if (Cr != 3 || LocalSize > 512) { StackAdjustOpcodes += (LocalSize > 4088) ? 2 : (LocalSize > 0) ? 1 : 0; } // // Compute the total epilog length and determine if we are within // its scope. // EpilogLength = IRegOpcodes + FRegOpcodes + HOpcodes + StackAdjustOpcodes + 1; ScopeStart = FunctionLength - EpilogLength; if (OffsetInFunction > ScopeStart) { OffsetInScope = OffsetInFunction - ScopeStart; } } // // Process operations backwards, in the order: stack/frame deallocation, // VFP register popping, integer register popping, parameter home // area recovery. // // First case is simple: we process everything with no regard for // the current offset within the scope. // Status = STATUS_SUCCESS; if (OffsetInScope == 0) { if (Cr == 3) { Status = RtlpUnwindRestoreRegisterRange(ContextRecord, 0, 22, 1, UnwindParams);///fp assert(Status == STATUS_SUCCESS); Status = RtlpUnwindRestoreRegisterRange(ContextRecord, 0, 1, 1, UnwindParams);//ra } ContextRecord->Sp += LocalSize; if (RegF != 0 && Status == STATUS_SUCCESS) { Status = RtlpUnwindRestoreFpRegisterRange(ContextRecord, IntSize, 24, RegF + 1, UnwindParams);//fs0 } if (Cr == 1 && Status == STATUS_SUCCESS) { Status = RtlpUnwindRestoreRegisterRange(ContextRecord, IntSize - 8, 1, 1, UnwindParams);//ra } if (RegI > 0 && Status == STATUS_SUCCESS) { Status = RtlpUnwindRestoreRegisterRange(ContextRecord, 0, 23, RegI, UnwindParams);//s0 } ContextRecord->Sp += RegSize; } // // Second case is more complex: we must step along each operation // to ensure it should be executed. // else { CurrentOffset = 0; if (Cr == 3) { if (LocalSize <= 512) { if (CurrentOffset++ >= OffsetInScope) { Status = RtlpUnwindRestoreRegisterRange(ContextRecord, -(LONG)LocalSize, 22, 1, UnwindParams); Status = RtlpUnwindRestoreRegisterRange(ContextRecord, -(LONG)LocalSize, 1, 1, UnwindParams); } LocalSize = 0; } } while (LocalSize != 0) { Count = (LocalSize + 4087) % 4088 + 1; if (CurrentOffset++ >= OffsetInScope) { ContextRecord->Sp += Count; } LocalSize -= Count; } if (HBit != 0) { CurrentOffset += 4; } if (RegF != 0 && Status == STATUS_SUCCESS) { RegF++; while (RegF != 0) { Count = 2 - (RegF & 1); RegF -= Count; if (CurrentOffset++ >= OffsetInScope) { Status = RtlpUnwindRestoreFpRegisterRange( ContextRecord, (RegF == 0 && RegI == 0) ? (-(LONG)RegSize) : (IntSize + 8 * RegF), 24 + RegF, Count, UnwindParams); } } } if (Cr == 1 && Status == STATUS_SUCCESS) { if (RegI % 2 == 0) { if (CurrentOffset++ >= OffsetInScope) { Status = RtlpUnwindRestoreRegisterRange(ContextRecord, IntSize - 8, 31, 1, UnwindParams);//s8 ? } } else { if (CurrentOffset++ >= OffsetInScope) { RegI--; Status = RtlpUnwindRestoreRegisterRange(ContextRecord, IntSize - 8, 2, 1, UnwindParams);//tp ? if (Status == STATUS_SUCCESS) { Status = RtlpUnwindRestoreRegisterRange(ContextRecord, IntSize - 16, 23 + RegI, 1, UnwindParams); } } } } while (RegI != 0 && Status == STATUS_SUCCESS) { Count = 2 - (RegI & 1); RegI -= Count; if (CurrentOffset++ >= OffsetInScope) { Status = RtlpUnwindRestoreRegisterRange( ContextRecord, (RegI == 0) ? (-(LONG)RegSize) : (8 * RegI), 23 + RegI, Count, UnwindParams); } } } // // If we succeeded, post-process the results a bit // if (Status == STATUS_SUCCESS) { ContextRecord->Pc = ContextRecord->Ra; *EstablisherFrame = ContextRecord->Sp; if (ARGUMENT_PRESENT(HandlerRoutine)) { *HandlerRoutine = NULL; } *HandlerData = NULL; } return Status; } BOOL OOPStackUnwinderLoongarch64::Unwind(T_CONTEXT * pContext) { DWORD64 ImageBase = 0; HRESULT hr = GetModuleBase(pContext->Pc, &ImageBase); if (hr != S_OK) return FALSE; PEXCEPTION_ROUTINE DummyHandlerRoutine; PVOID DummyHandlerData; DWORD64 DummyEstablisherFrame; DWORD64 startingPc = pContext->Pc; DWORD64 startingSp = pContext->Sp; T_RUNTIME_FUNCTION Rfe; if (FAILED(GetFunctionEntry(pContext->Pc, &Rfe, sizeof(Rfe)))) return FALSE; if ((Rfe.UnwindData & 3) != 0) { hr = RtlpUnwindFunctionCompact(pContext->Pc - ImageBase, &Rfe, pContext, &DummyEstablisherFrame, &DummyHandlerRoutine, &DummyHandlerData, NULL); } else { hr = RtlpUnwindFunctionFull(pContext->Pc - ImageBase, ImageBase, &Rfe, pContext, &DummyEstablisherFrame, &DummyHandlerRoutine, &DummyHandlerData, NULL); } // PC == 0 means unwinding is finished. // Same if no forward progress is made if (pContext->Pc == 0 || (startingPc == pContext->Pc && startingSp == pContext->Sp)) return FALSE; return TRUE; } BOOL DacUnwindStackFrame(T_CONTEXT *pContext, T_KNONVOLATILE_CONTEXT_POINTERS* pContextPointers) { OOPStackUnwinderLoongarch64 unwinder; BOOL res = unwinder.Unwind(pContext); if (res && pContextPointers) { for (int i = 0; i < 9; i++) { *(&pContextPointers->S0 + i) = &pContext->S0 + i; } pContextPointers->Fp = &pContext->Fp; pContextPointers->Ra = &pContext->Ra; } return res; } #if defined(HOST_UNIX) PEXCEPTION_ROUTINE RtlVirtualUnwind( IN ULONG HandlerType, IN ULONG64 ImageBase, IN ULONG64 ControlPc, IN PT_RUNTIME_FUNCTION FunctionEntry, IN OUT PCONTEXT ContextRecord, OUT PVOID *HandlerData, OUT PULONG64 EstablisherFrame, IN OUT PT_KNONVOLATILE_CONTEXT_POINTERS ContextPointers OPTIONAL ) { PEXCEPTION_ROUTINE handlerRoutine; HRESULT hr; DWORD64 startingPc = ControlPc; DWORD64 startingSp = ContextRecord->Sp; T_RUNTIME_FUNCTION rfe; rfe.BeginAddress = FunctionEntry->BeginAddress; rfe.UnwindData = FunctionEntry->UnwindData; LOONGARCH64_UNWIND_PARAMS unwindParams; unwindParams.ContextPointers = ContextPointers; if ((rfe.UnwindData & 3) != 0) { hr = RtlpUnwindFunctionCompact(ControlPc - ImageBase, &rfe, ContextRecord, EstablisherFrame, &handlerRoutine, HandlerData, &unwindParams); } else { hr = RtlpUnwindFunctionFull(ControlPc - ImageBase, ImageBase, &rfe, ContextRecord, EstablisherFrame, &handlerRoutine, HandlerData, &unwindParams); } return handlerRoutine; } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // #include "stdafx.h" #include "utilcode.h" #include "crosscomp.h" #include "unwinder_loongarch64.h" typedef struct _LOONGARCH64_KTRAP_FRAME { // // Exception active indicator. // // 0 - interrupt frame. // 1 - exception frame. // 2 - service frame. // /* +0x000 */ UCHAR ExceptionActive; // always valid /* +0x001 */ UCHAR ContextFromKFramesUnwound; // set if KeContextFromKFrames created this frame /* +0x002 */ UCHAR DebugRegistersValid; // always valid /* +0x003 */ union { UCHAR PreviousMode; // system services only UCHAR PreviousIrql; // interrupts only }; // // Page fault information (page faults only) // Previous trap frame address (system services only) // // Organized this way to allow first couple words to be used // for scratch space in the general case // /* +0x004 */ ULONG FaultStatus; // page faults only /* +0x008 */ union { ULONG64 FaultAddress; // page faults only ULONG64 TrapFrame; // system services only }; // // The LOONGARCH architecture does not have an architectural trap frame. On // an exception or interrupt, the processor switches to an // exception-specific processor mode in which at least the RA and SP // registers are banked. Software is responsible for preserving // registers which reflect the processor state in which the // exception occurred rather than any intermediate processor modes. // // // Volatile floating point state is dynamically allocated; this // pointer may be NULL if the FPU was not enabled at the time the // trap was taken. // /* +0x010 */ PVOID VfpState; // // Volatile registers // ULONG64 R[19]; ULONG64 Tp; ULONG64 Sp; ULONG64 Fp; ULONG64 Ra; ULONG64 Pc; } LOONGARCH64_KTRAP_FRAME, *PLOONGARCH64_KTRAP_FRAME; typedef struct _LOONGARCH64_VFP_STATE { struct _LOONGARCH64_VFP_STATE *Link; // link to next state entry ULONG Fcsr; // FCSR register ULONG64 F[32]; // All F registers (0-31) } LOONGARCH64_VFP_STATE, *PLOONGARCH64_VFP_STATE, KLOONGARCH64_VFP_STATE, *PKLOONGARCH64_VFP_STATE; // // Parameters describing the unwind codes. // #define STATUS_UNWIND_UNSUPPORTED_VERSION STATUS_UNSUCCESSFUL #define STATUS_UNWIND_NOT_IN_FUNCTION STATUS_UNSUCCESSFUL #define STATUS_UNWIND_INVALID_SEQUENCE STATUS_UNSUCCESSFUL // // Macros for accessing memory. These can be overridden if other code // (in particular the debugger) needs to use them. #define MEMORY_READ_BYTE(params, addr) (*dac_cast<PTR_BYTE>(addr)) #define MEMORY_READ_DWORD(params, addr) (*dac_cast<PTR_DWORD>(addr)) #define MEMORY_READ_QWORD(params, addr) (*dac_cast<PTR_UINT64>(addr)) typedef struct _LOONGARCH64_UNWIND_PARAMS { PT_KNONVOLATILE_CONTEXT_POINTERS ContextPointers; } LOONGARCH64_UNWIND_PARAMS, *PLOONGARCH64_UNWIND_PARAMS; #define UNWIND_PARAMS_SET_TRAP_FRAME(Params, Address, Size) #define UPDATE_CONTEXT_POINTERS(Params, RegisterNumber, Address) \ do { \ if (ARGUMENT_PRESENT(Params)) { \ PT_KNONVOLATILE_CONTEXT_POINTERS ContextPointers = (Params)->ContextPointers; \ if (ARGUMENT_PRESENT(ContextPointers)) { \ if (RegisterNumber == 22) \ ContextPointers->Fp = (PDWORD64)Address; \ else if (RegisterNumber >= 23 && RegisterNumber <= 31) { \ (&ContextPointers->S0)[RegisterNumber - 23] = (PDWORD64)Address; \ } \ } \ } \ } while (0) #define UPDATE_FP_CONTEXT_POINTERS(Params, RegisterNumber, Address) \ do { \ if (ARGUMENT_PRESENT(Params)) { \ PT_KNONVOLATILE_CONTEXT_POINTERS ContextPointers = (Params)->ContextPointers; \ if (ARGUMENT_PRESENT(ContextPointers) && \ (RegisterNumber >= 24) && \ (RegisterNumber <= 31)) { \ \ (&ContextPointers->F24)[RegisterNumber - 24] = (PDWORD64)Address; \ } \ } \ } while (0) #define VALIDATE_STACK_ADDRESS_EX(Params, Context, Address, DataSize, Alignment, OutStatus) #define VALIDATE_STACK_ADDRESS(Params, Context, DataSize, Alignment, OutStatus) // // Macros to clarify opcode parsing // #define OPCODE_IS_END(Op) (((Op) & 0xfe) == 0xe4) // // This table describes the size of each unwind code, in bytes // static const BYTE UnwindCodeSizeTable[256] = { 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2, 3,2,2,2,3,2,2,2, 3,2,2,2,2,2,3,2, 3,2,3,2,3,2,2,2, 4,1,3,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1 }; NTSTATUS RtlpUnwindCustom( __inout PT_CONTEXT ContextRecord, _In_ BYTE Opcode, _In_ PLOONGARCH64_UNWIND_PARAMS UnwindParams ) /*++ Routine Description: Handles custom unwinding operations involving machine-specific frames. Arguments: ContextRecord - Supplies the address of a context record. Opcode - The opcode to decode. UnwindParams - Additional parameters shared with caller. Return Value: An NTSTATUS indicating either STATUS_SUCCESS if everything went ok, or another status code if there were problems. --*/ { ULONG Fcsr; ULONG RegIndex; ULONG_PTR SourceAddress; ULONG_PTR StartingSp; NTSTATUS Status; ULONG_PTR VfpStateAddress; StartingSp = ContextRecord->Sp; Status = STATUS_SUCCESS; // // The opcode describes the special-case stack // switch (Opcode) { // // Trap frame case // case 0xe8: // MSFT_OP_TRAP_FRAME: // // Ensure there is enough valid space for the trap frame // VALIDATE_STACK_ADDRESS(UnwindParams, ContextRecord, sizeof(LOONGARCH64_KTRAP_FRAME), 16, &Status); if (!NT_SUCCESS(Status)) { return Status; } // // Restore R0-R15, and F0-F32 // SourceAddress = StartingSp + FIELD_OFFSET(LOONGARCH64_KTRAP_FRAME, R); for (RegIndex = 0; RegIndex < 16; RegIndex++) { UPDATE_CONTEXT_POINTERS(UnwindParams, RegIndex, SourceAddress); #ifdef __GNUC__ *(&ContextRecord->R0 + RegIndex) = MEMORY_READ_QWORD(UnwindParams, SourceAddress); #else ContextRecord->R[RegIndex] = MEMORY_READ_QWORD(UnwindParams, SourceAddress); #endif SourceAddress += sizeof(ULONG_PTR); } SourceAddress = StartingSp + FIELD_OFFSET(LOONGARCH64_KTRAP_FRAME, VfpState); VfpStateAddress = MEMORY_READ_QWORD(UnwindParams, SourceAddress); if (VfpStateAddress != 0) { SourceAddress = VfpStateAddress + FIELD_OFFSET(KLOONGARCH64_VFP_STATE, Fcsr); Fcsr = MEMORY_READ_DWORD(UnwindParams, SourceAddress); if (Fcsr != (ULONG)-1) { ContextRecord->Fcsr = Fcsr; SourceAddress = VfpStateAddress + FIELD_OFFSET(KLOONGARCH64_VFP_STATE, F); for (RegIndex = 0; RegIndex < 32; RegIndex++) { UPDATE_FP_CONTEXT_POINTERS(UnwindParams, RegIndex, SourceAddress); ContextRecord->F[RegIndex] = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress += 2 * sizeof(ULONGLONG); } } } // // Restore SP, RA, PC, and the status registers // //SourceAddress = StartingSp + FIELD_OFFSET(LOONGARCH64_KTRAP_FRAME, Tp);//TP //ContextRecord->Tp = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress = StartingSp + FIELD_OFFSET(LOONGARCH64_KTRAP_FRAME, Sp); ContextRecord->Sp = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress = StartingSp + FIELD_OFFSET(LOONGARCH64_KTRAP_FRAME, Fp); ContextRecord->Fp = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress = StartingSp + FIELD_OFFSET(LOONGARCH64_KTRAP_FRAME, Ra); ContextRecord->Ra = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress = StartingSp + FIELD_OFFSET(LOONGARCH64_KTRAP_FRAME, Pc); ContextRecord->Pc = MEMORY_READ_QWORD(UnwindParams, SourceAddress); // // Set the trap frame and clear the unwound-to-call flag // UNWIND_PARAMS_SET_TRAP_FRAME(UnwindParams, StartingSp, sizeof(LOONGARCH64_KTRAP_FRAME)); ContextRecord->ContextFlags &= ~CONTEXT_UNWOUND_TO_CALL; break; // // Context case // case 0xea: // MSFT_OP_CONTEXT: // // Ensure there is enough valid space for the full CONTEXT structure // VALIDATE_STACK_ADDRESS(UnwindParams, ContextRecord, sizeof(CONTEXT), 16, &Status); if (!NT_SUCCESS(Status)) { return Status; } // // Restore R0-R23, and F0-F31 // SourceAddress = StartingSp + FIELD_OFFSET(T_CONTEXT, R0); for (RegIndex = 0; RegIndex < 23; RegIndex++) { UPDATE_CONTEXT_POINTERS(UnwindParams, RegIndex, SourceAddress); #ifdef __GNUC__ *(&ContextRecord->R0 + RegIndex) = MEMORY_READ_QWORD(UnwindParams, SourceAddress); #else ContextRecord->R[RegIndex] = MEMORY_READ_QWORD(UnwindParams, SourceAddress); #endif SourceAddress += sizeof(ULONG_PTR); } SourceAddress = StartingSp + FIELD_OFFSET(T_CONTEXT, F); for (RegIndex = 0; RegIndex < 32; RegIndex++) { UPDATE_FP_CONTEXT_POINTERS(UnwindParams, RegIndex, SourceAddress); ContextRecord->F[RegIndex] = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress += 2 * sizeof(ULONGLONG); } // // Restore SP, RA, PC, and the status registers // SourceAddress = StartingSp + FIELD_OFFSET(T_CONTEXT, Fp); ContextRecord->Fp = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress = StartingSp + FIELD_OFFSET(T_CONTEXT, Sp); ContextRecord->Sp = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress = StartingSp + FIELD_OFFSET(T_CONTEXT, Pc); ContextRecord->Pc = MEMORY_READ_QWORD(UnwindParams, SourceAddress); SourceAddress = StartingSp + FIELD_OFFSET(T_CONTEXT, Fcsr); ContextRecord->Fcsr = MEMORY_READ_DWORD(UnwindParams, SourceAddress); // // Inherit the unwound-to-call flag from this context // SourceAddress = StartingSp + FIELD_OFFSET(T_CONTEXT, ContextFlags); ContextRecord->ContextFlags &= ~CONTEXT_UNWOUND_TO_CALL; ContextRecord->ContextFlags |= MEMORY_READ_DWORD(UnwindParams, SourceAddress) & CONTEXT_UNWOUND_TO_CALL; break; default: return STATUS_UNSUCCESSFUL; } return STATUS_SUCCESS; } ULONG RtlpComputeScopeSize( _In_ ULONG_PTR UnwindCodePtr, _In_ ULONG_PTR UnwindCodesEndPtr, _In_ BOOLEAN IsEpilog, _In_ PLOONGARCH64_UNWIND_PARAMS UnwindParams ) /*++ Routine Description: Computes the size of an prolog or epilog, in words. Arguments: UnwindCodePtr - Supplies a pointer to the start of the unwind code sequence. UnwindCodesEndPtr - Supplies a pointer to the byte immediately following the unwind code table, as described by the header. IsEpilog - Specifies TRUE if the scope describes an epilog, or FALSE if it describes a prolog. UnwindParams - Additional parameters shared with caller. Return Value: The size of the scope described by the unwind codes, in halfword units. --*/ { ULONG ScopeSize; BYTE Opcode; // // Iterate through the unwind codes until we hit an end marker. // While iterating, accumulate the total scope size. // ScopeSize = 0; Opcode = 0; while (UnwindCodePtr < UnwindCodesEndPtr) { Opcode = MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); if (OPCODE_IS_END(Opcode)) { break; } UnwindCodePtr += UnwindCodeSizeTable[Opcode]; ScopeSize++; } // // Epilogs have one extra instruction at the end that needs to be // accounted for. // if (IsEpilog) { ScopeSize++; } return ScopeSize; } NTSTATUS RtlpUnwindRestoreRegisterRange( __inout PT_CONTEXT ContextRecord, _In_ LONG SpOffset, _In_ ULONG FirstRegister, _In_ ULONG RegisterCount, _In_ PLOONGARCH64_UNWIND_PARAMS UnwindParams ) /*++ Routine Description: Restores a series of integer registers from the stack. Arguments: ContextRecord - Supplies the address of a context record. SpOffset - Specifies a stack offset. Positive values are simply used as a base offset. Negative values assume a predecrement behavior: a 0 offset is used for restoration, but the absolute value of the offset is added to the final Sp. FirstRegister - Specifies the index of the first register to restore. RegisterCount - Specifies the number of registers to restore. UnwindParams - Additional parameters shared with caller. Return Value: None. --*/ { ULONG_PTR CurAddress; ULONG RegIndex; NTSTATUS Status; // // Compute the source address and validate it. // CurAddress = ContextRecord->Sp; if (SpOffset >= 0) { CurAddress += SpOffset; } Status = STATUS_SUCCESS; VALIDATE_STACK_ADDRESS(UnwindParams, ContextRecord, 8 * RegisterCount, 8, &Status); if (Status != STATUS_SUCCESS) { return Status; } // // Restore the registers // for (RegIndex = 0; RegIndex < RegisterCount; RegIndex++) { UPDATE_CONTEXT_POINTERS(UnwindParams, FirstRegister + RegIndex, CurAddress); #ifdef __GNUC__ *(&ContextRecord->R0 + FirstRegister + RegIndex) = MEMORY_READ_QWORD(UnwindParams, CurAddress); #else ContextRecord->R[FirstRegister + RegIndex] = MEMORY_READ_QWORD(UnwindParams, CurAddress); #endif CurAddress += 8; } if (SpOffset < 0) { ContextRecord->Sp -= SpOffset; } return STATUS_SUCCESS; } NTSTATUS RtlpUnwindRestoreFpRegisterRange( __inout PT_CONTEXT ContextRecord, _In_ LONG SpOffset, _In_ ULONG FirstRegister, _In_ ULONG RegisterCount, _In_ PLOONGARCH64_UNWIND_PARAMS UnwindParams ) /*++ Routine Description: Restores a series of floating-point registers from the stack. Arguments: ContextRecord - Supplies the address of a context record. SpOffset - Specifies a stack offset. Positive values are simply used as a base offset. Negative values assume a predecrement behavior: a 0 offset is used for restoration, but the absolute value of the offset is added to the final Sp. FirstRegister - Specifies the index of the first register to restore. RegisterCount - Specifies the number of registers to restore. UnwindParams - Additional parameters shared with caller. Return Value: None. --*/ { ULONG_PTR CurAddress; ULONG RegIndex; NTSTATUS Status; // // Compute the source address and validate it. // CurAddress = ContextRecord->Sp; if (SpOffset >= 0) { CurAddress += SpOffset; } Status = STATUS_SUCCESS; VALIDATE_STACK_ADDRESS(UnwindParams, ContextRecord, 8 * RegisterCount, 8, &Status); if (Status != STATUS_SUCCESS) { return Status; } // // Restore the registers // for (RegIndex = 0; RegIndex < RegisterCount; RegIndex++) { UPDATE_FP_CONTEXT_POINTERS(UnwindParams, FirstRegister + RegIndex, CurAddress); ContextRecord->F[FirstRegister + RegIndex] = MEMORY_READ_QWORD(UnwindParams, CurAddress); CurAddress += 8; } if (SpOffset < 0) { ContextRecord->Sp -= SpOffset; } return STATUS_SUCCESS; } NTSTATUS RtlpUnwindFunctionFull( _In_ DWORD64 ControlPcRva, _In_ ULONG_PTR ImageBase, _In_ PT_RUNTIME_FUNCTION FunctionEntry, __inout T_CONTEXT *ContextRecord, _Out_ PDWORD64 EstablisherFrame, __deref_opt_out_opt PEXCEPTION_ROUTINE *HandlerRoutine, _Out_ PVOID *HandlerData, _In_ PLOONGARCH64_UNWIND_PARAMS UnwindParams ) /*++ Routine Description: This function virtually unwinds the specified function by parsing the .xdata record to determine where in the function the provided ControlPc is, and then executing unwind codes that map to the function's prolog or epilog behavior. If a context pointers record is specified (in the UnwindParams), then the address where each nonvolatile register is restored from is recorded in the appropriate element of the context pointers record. Arguments: ControlPcRva - Supplies the address where control left the specified function, as an offset relative to the IamgeBase. ImageBase - Supplies the base address of the image that contains the function being unwound. FunctionEntry - Supplies the address of the function table entry for the specified function. If appropriate, this should have already been probed. ContextRecord - Supplies the address of a context record. EstablisherFrame - Supplies a pointer to a variable that receives the the establisher frame pointer value. HandlerRoutine - Supplies an optional pointer to a variable that receives the handler routine address. If control did not leave the specified function in either the prolog or an epilog and a handler of the proper type is associated with the function, then the address of the language specific exception handler is returned. Otherwise, NULL is returned. HandlerData - Supplies a pointer to a variable that receives a pointer the the language handler data. UnwindParams - Additional parameters shared with caller. Return Value: STATUS_SUCCESS if the unwind could be completed, a failure status otherwise. Unwind can only fail when validation bounds are specified. --*/ { ULONG AccumulatedSaveNexts; ULONG CurCode; ULONG EpilogScopeCount; PEXCEPTION_ROUTINE ExceptionHandler; PVOID ExceptionHandlerData; BOOLEAN FinalPcFromRa; ULONG FunctionLength; ULONG HeaderWord; ULONG NextCode, NextCode1, NextCode2; DWORD64 OffsetInFunction; ULONG ScopeNum; ULONG ScopeSize; ULONG ScopeStart; DWORD64 SkipWords; NTSTATUS Status; ULONG_PTR UnwindCodePtr; ULONG_PTR UnwindCodesEndPtr; ULONG_PTR UnwindDataPtr; ULONG UnwindIndex; ULONG UnwindWords; // // Unless a special frame is enountered, assume that any unwinding // will return us to the return address of a call and set the flag // appropriately (it will be cleared again if the special cases apply). // ContextRecord->ContextFlags |= CONTEXT_UNWOUND_TO_CALL; // // By default, unwinding is done by popping to the RA, then copying // that RA to the PC. However, some special opcodes require different // behavior. // FinalPcFromRa = TRUE; // // Fetch the header word from the .xdata blob // UnwindDataPtr = ImageBase + FunctionEntry->UnwindData; HeaderWord = MEMORY_READ_DWORD(UnwindParams, UnwindDataPtr); UnwindDataPtr += 4; // // Verify the version before we do anything else // if (((HeaderWord >> 18) & 3) != 0) { assert(!"ShouldNotReachHere"); return STATUS_UNWIND_UNSUPPORTED_VERSION; } FunctionLength = HeaderWord & 0x3ffff; OffsetInFunction = (ControlPcRva - FunctionEntry->BeginAddress) / 4; // // Determine the number of epilog scope records and the maximum number // of unwind codes. // UnwindWords = (HeaderWord >> 27) & 31; EpilogScopeCount = (HeaderWord >> 22) & 31; if (EpilogScopeCount == 0 && UnwindWords == 0) { EpilogScopeCount = MEMORY_READ_DWORD(UnwindParams, UnwindDataPtr); UnwindDataPtr += 4; UnwindWords = (EpilogScopeCount >> 16) & 0xff; EpilogScopeCount &= 0xffff; } if ((HeaderWord & (1 << 21)) != 0) { UnwindIndex = EpilogScopeCount; EpilogScopeCount = 0; } // // If exception data is present, extract it now. // ExceptionHandler = NULL; ExceptionHandlerData = NULL; if ((HeaderWord & (1 << 20)) != 0) { ExceptionHandler = (PEXCEPTION_ROUTINE)(ImageBase + MEMORY_READ_DWORD(UnwindParams, UnwindDataPtr + 4 * (EpilogScopeCount + UnwindWords))); ExceptionHandlerData = (PVOID)(UnwindDataPtr + 4 * (EpilogScopeCount + UnwindWords + 1)); } // // Unless we are in a prolog/epilog, we execute the unwind codes // that immediately follow the epilog scope list. // UnwindCodePtr = UnwindDataPtr + 4 * EpilogScopeCount; UnwindCodesEndPtr = UnwindCodePtr + 4 * UnwindWords; SkipWords = 0; // // If we're near the start of the function, and this function has a prolog, // compute the size of the prolog from the unwind codes. If we're in the // midst of it, we still execute starting at unwind code index 0, but we may // need to skip some to account for partial execution of the prolog. // // N.B. As an optimization here, note that each byte of unwind codes can // describe at most one 32-bit instruction. Thus, the largest prologue // that could possibly be described by UnwindWords (which is 4 * the // number of unwind code bytes) is 4 * UnwindWords words. If // OffsetInFunction is larger than this value, it is guaranteed to be // in the body of the function. // if (OffsetInFunction < 4 * UnwindWords) { ScopeSize = RtlpComputeScopeSize(UnwindCodePtr, UnwindCodesEndPtr, FALSE, UnwindParams); if (OffsetInFunction < ScopeSize) { SkipWords = ScopeSize - OffsetInFunction; ExceptionHandler = NULL; ExceptionHandlerData = NULL; goto ExecuteCodes; } } // // We're not in the prolog, now check to see if we are in the epilog. // In the simple case, the 'E' bit is set indicating there is a single // epilog that lives at the end of the function. If we're near the end // of the function, compute the actual size of the epilog from the // unwind codes. If we're in the midst of it, adjust the unwind code // pointer to the start of the codes and determine how many we need to skip. // // N.B. Similar to the prolog case above, the maximum number of halfwords // that an epilog can cover is limited by UnwindWords. In the epilog // case, however, the starting index within the unwind code table is // non-zero, and so the maximum number of unwind codes that can pertain // to an epilog is (UnwindWords * 4 - UnwindIndex), thus further // constraining the bounds of the epilog. // if ((HeaderWord & (1 << 21)) != 0) { if (OffsetInFunction + (4 * UnwindWords - UnwindIndex) >= FunctionLength) { ScopeSize = RtlpComputeScopeSize(UnwindCodePtr + UnwindIndex, UnwindCodesEndPtr, TRUE, UnwindParams); ScopeStart = FunctionLength - ScopeSize; if (OffsetInFunction >= ScopeStart) { UnwindCodePtr += UnwindIndex; SkipWords = OffsetInFunction - ScopeStart; ExceptionHandler = NULL; ExceptionHandlerData = NULL; } } } // // In the multiple-epilog case, we scan forward to see if we are within // shooting distance of any of the epilogs. If we are, we compute the // actual size of the epilog from the unwind codes and proceed like the // simple case above. // else { for (ScopeNum = 0; ScopeNum < EpilogScopeCount; ScopeNum++) { HeaderWord = MEMORY_READ_DWORD(UnwindParams, UnwindDataPtr); UnwindDataPtr += 4; // // The scope records are stored in order. If we hit a record that // starts after our current position, we must not be in an epilog. // ScopeStart = HeaderWord & 0x3ffff; if (OffsetInFunction < ScopeStart) { break; } UnwindIndex = HeaderWord >> 22; if (OffsetInFunction < ScopeStart + (4 * UnwindWords - UnwindIndex)) { ScopeSize = RtlpComputeScopeSize(UnwindCodePtr + UnwindIndex, UnwindCodesEndPtr, TRUE, UnwindParams); if (OffsetInFunction < ScopeStart + ScopeSize) { UnwindCodePtr += UnwindIndex; SkipWords = OffsetInFunction - ScopeStart; ExceptionHandler = NULL; ExceptionHandlerData = NULL; break; } } } } ExecuteCodes: // // Skip over unwind codes until we account for the number of halfwords // to skip. // while (UnwindCodePtr < UnwindCodesEndPtr && SkipWords > 0) { CurCode = MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); if (OPCODE_IS_END(CurCode)) { break; } UnwindCodePtr += UnwindCodeSizeTable[CurCode]; SkipWords--; } // // Now execute codes until we hit the end. // Status = STATUS_SUCCESS; AccumulatedSaveNexts = 0; while (UnwindCodePtr < UnwindCodesEndPtr && Status == STATUS_SUCCESS) { CurCode = MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr += 1; // // alloc_s (000xxxxx): allocate small stack with size < 1024 (2^5 * 16) // if (CurCode <= 0x1f) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } ContextRecord->Sp += 16 * (CurCode & 0x1f); } // // alloc_m (11000xxx|xxxxxxxx): allocate large stack with size < 32k (2^11 * 16). // else if (CurCode <= 0xc7) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } ContextRecord->Sp += 16 * ((CurCode & 7) << 8); ContextRecord->Sp += 16 * MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr++; } // // save_reg (11010000|000xxxxx|zzzzzzzz): save reg r(1+#X) at [sp+#Z*8], offset <= 2047 // else if (CurCode == 0xd0) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } NextCode = MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr++; NextCode1 = (uint8_t)MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr++; Status = RtlpUnwindRestoreRegisterRange( ContextRecord, 8 * NextCode1, 1 + NextCode, 1, UnwindParams); } // // save_freg (11011100|0xxxzzzz|zzzzzzzz): save reg f(24+#X) at [sp+#Z*8], offset <= 32767 // else if (CurCode == 0xdc) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } NextCode = MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr++; NextCode1 = MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr++; Status = RtlpUnwindRestoreFpRegisterRange( ContextRecord, 8 * (((NextCode & 0xf) << 8) + NextCode1), 24 + (NextCode >> 4), 1, UnwindParams); } // // alloc_l (11100000|xxxxxxxx|xxxxxxxx|xxxxxxxx): allocate large stack with size < 256M // else if (CurCode == 0xe0) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } ContextRecord->Sp += 16 * (MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr) << 16); UnwindCodePtr++; ContextRecord->Sp += 16 * (MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr) << 8); UnwindCodePtr++; ContextRecord->Sp += 16 * MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr++; } // // set_fp (11100001): set up fp: with: ori fp,sp,0 // else if (CurCode == 0xe1) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } ContextRecord->Sp = ContextRecord->Fp; } // // add_fp (11100010|000xxxxx|xxxxxxxx): set up fp with: addi.d fp,sp,#x*8 // else if (CurCode == 0xe2) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } NextCode = MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr++; NextCode1 = MEMORY_READ_BYTE(UnwindParams, UnwindCodePtr); UnwindCodePtr++; ContextRecord->Sp = ContextRecord->Fp - 8 * ((NextCode << 8) | NextCode1); } // // nop (11100011): no unwind operation is required // else if (CurCode == 0xe3) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } } // // end (11100100): end of unwind code // else if (CurCode == 0xe4) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } goto finished; } // // end_c (11100101): end of unwind code in current chained scope // else if (CurCode == 0xe5) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } goto finished; } // // custom_0 (111010xx): restore custom structure // else if (CurCode >= 0xe8 && CurCode <= 0xeb) { if (AccumulatedSaveNexts != 0) { return STATUS_UNWIND_INVALID_SEQUENCE; } Status = RtlpUnwindCustom(ContextRecord, (BYTE) CurCode, UnwindParams); FinalPcFromRa = FALSE; } // // Anything else is invalid // else { return STATUS_UNWIND_INVALID_SEQUENCE; } } // // If we succeeded, post-process the results a bit // finished: if (Status == STATUS_SUCCESS) { // // Since we always POP to the RA, recover the final PC from there, unless // it was overwritten due to a special case custom unwinding operation. // Also set the establisher frame equal to the final stack pointer. // if (FinalPcFromRa) { ContextRecord->Pc = ContextRecord->Ra; } *EstablisherFrame = ContextRecord->Sp; if (ARGUMENT_PRESENT(HandlerRoutine)) { *HandlerRoutine = ExceptionHandler; } *HandlerData = ExceptionHandlerData; } return Status; } NTSTATUS RtlpUnwindFunctionCompact( _In_ DWORD64 ControlPcRva, _In_ PT_RUNTIME_FUNCTION FunctionEntry, __inout T_CONTEXT *ContextRecord, _Out_ PDWORD64 EstablisherFrame, __deref_opt_out_opt PEXCEPTION_ROUTINE *HandlerRoutine, _Out_ PVOID *HandlerData, _In_ PLOONGARCH64_UNWIND_PARAMS UnwindParams ) /*++ Routine Description: This function virtually unwinds the specified function by parsing the compact .pdata record to determine where in the function the provided ControlPc is, and then executing a standard, well-defined set of operations. If a context pointers record is specified (in the UnwindParams), then the address where each nonvolatile register is restored from is recorded in the appropriate element of the context pointers record. Arguments: ControlPcRva - Supplies the address where control left the specified function, as an offset relative to the IamgeBase. FunctionEntry - Supplies the address of the function table entry for the specified function. If appropriate, this should have already been probed. ContextRecord - Supplies the address of a context record. EstablisherFrame - Supplies a pointer to a variable that receives the the establisher frame pointer value. HandlerRoutine - Supplies an optional pointer to a variable that receives the handler routine address. If control did not leave the specified function in either the prolog or an epilog and a handler of the proper type is associated with the function, then the address of the language specific exception handler is returned. Otherwise, NULL is returned. HandlerData - Supplies a pointer to a variable that receives a pointer the the language handler data. UnwindParams - Additional parameters shared with caller. Return Value: STATUS_SUCCESS if the unwind could be completed, a failure status otherwise. Unwind can only fail when validation bounds are specified. --*/ { ULONG Count; ULONG Cr; ULONG CurrentOffset; ULONG EpilogLength; ULONG Flag; ULONG FloatSize; ULONG FrameSize; ULONG FRegOpcodes; ULONG FunctionLength; ULONG HBit; ULONG HOpcodes; ULONG IRegOpcodes; ULONG IntSize; ULONG LocalSize; DWORD64 OffsetInFunction; DWORD64 OffsetInScope; ULONG PrologLength; ULONG RegF; ULONG RegI; ULONG RegSize; ULONG ScopeStart; ULONG StackAdjustOpcodes; NTSTATUS Status; ULONG UnwindData; UnwindData = FunctionEntry->UnwindData; Status = STATUS_SUCCESS; // // Compact records always describe an unwind to a call. // ContextRecord->ContextFlags |= CONTEXT_UNWOUND_TO_CALL; // // Extract the basic information about how to do a full unwind. // Flag = UnwindData & 3; FunctionLength = (UnwindData >> 2) & 0x7ff; RegF = (UnwindData >> 13) & 7; RegI = (UnwindData >> 16) & 0xf; HBit = (UnwindData >> 20) & 1; Cr = (UnwindData >> 21) & 3; FrameSize = (UnwindData >> 23) & 0x1ff; assert(!"---------------LOONGARCH64 ShouldNotReachHere"); if (Flag == 3) { return STATUS_UNWIND_INVALID_SEQUENCE; } if (Cr == 2) { return STATUS_UNWIND_INVALID_SEQUENCE; } // // Determine the size of the locals // IntSize = RegI * 8; if (Cr == 1) { IntSize += 8; } FloatSize = (RegF == 0) ? 0 : (RegF + 1) * 8; RegSize = (IntSize + FloatSize + 8*8 * HBit + 0xf) & ~0xf; if (RegSize > 16 * FrameSize) { return STATUS_UNWIND_INVALID_SEQUENCE; } LocalSize = 16 * FrameSize - RegSize; // // If we're near the start of the function (within 17 words), // see if we are within the prolog. // // N.B. If the low 2 bits of the UnwindData are 2, then we have // no prolog. // OffsetInFunction = (ControlPcRva - FunctionEntry->BeginAddress) / 4; OffsetInScope = 0; if (OffsetInFunction < 17 && Flag != 2) { // // Compute sizes for each opcode in the prolog. // IRegOpcodes = (IntSize + 8) / 16; FRegOpcodes = (FloatSize + 8) / 16; HOpcodes = 4 * HBit; StackAdjustOpcodes = (Cr == 3) ? 1 : 0; if (Cr != 3 || LocalSize > 512) { StackAdjustOpcodes += (LocalSize > 4088) ? 2 : (LocalSize > 0) ? 1 : 0; } // // Compute the total prolog length and determine if we are within // its scope. // // N.B. We must execute prolog operations backwards to unwind, so // our final scope offset in this case is the distance from the end. // PrologLength = IRegOpcodes + FRegOpcodes + HOpcodes + StackAdjustOpcodes; if (OffsetInFunction < PrologLength) { OffsetInScope = PrologLength - OffsetInFunction; } } // // If we're near the end of the function (within 15 words), see if // we are within the epilog. // // N.B. If the low 2 bits of the UnwindData are 2, then we have // no epilog. // if (OffsetInScope == 0 && OffsetInFunction + 15 >= FunctionLength && Flag != 2) { // // Compute sizes for each opcode in the epilog. // IRegOpcodes = (IntSize + 8) / 16; FRegOpcodes = (FloatSize + 8) / 16; HOpcodes = HBit; StackAdjustOpcodes = (Cr == 3) ? 1 : 0; if (Cr != 3 || LocalSize > 512) { StackAdjustOpcodes += (LocalSize > 4088) ? 2 : (LocalSize > 0) ? 1 : 0; } // // Compute the total epilog length and determine if we are within // its scope. // EpilogLength = IRegOpcodes + FRegOpcodes + HOpcodes + StackAdjustOpcodes + 1; ScopeStart = FunctionLength - EpilogLength; if (OffsetInFunction > ScopeStart) { OffsetInScope = OffsetInFunction - ScopeStart; } } // // Process operations backwards, in the order: stack/frame deallocation, // VFP register popping, integer register popping, parameter home // area recovery. // // First case is simple: we process everything with no regard for // the current offset within the scope. // Status = STATUS_SUCCESS; if (OffsetInScope == 0) { if (Cr == 3) { Status = RtlpUnwindRestoreRegisterRange(ContextRecord, 0, 22, 1, UnwindParams);///fp assert(Status == STATUS_SUCCESS); Status = RtlpUnwindRestoreRegisterRange(ContextRecord, 0, 1, 1, UnwindParams);//ra } ContextRecord->Sp += LocalSize; if (RegF != 0 && Status == STATUS_SUCCESS) { Status = RtlpUnwindRestoreFpRegisterRange(ContextRecord, IntSize, 24, RegF + 1, UnwindParams);//fs0 } if (Cr == 1 && Status == STATUS_SUCCESS) { Status = RtlpUnwindRestoreRegisterRange(ContextRecord, IntSize - 8, 1, 1, UnwindParams);//ra } if (RegI > 0 && Status == STATUS_SUCCESS) { Status = RtlpUnwindRestoreRegisterRange(ContextRecord, 0, 23, RegI, UnwindParams);//s0 } ContextRecord->Sp += RegSize; } // // Second case is more complex: we must step along each operation // to ensure it should be executed. // else { CurrentOffset = 0; if (Cr == 3) { if (LocalSize <= 512) { if (CurrentOffset++ >= OffsetInScope) { Status = RtlpUnwindRestoreRegisterRange(ContextRecord, -(LONG)LocalSize, 22, 1, UnwindParams); Status = RtlpUnwindRestoreRegisterRange(ContextRecord, -(LONG)LocalSize, 1, 1, UnwindParams); } LocalSize = 0; } } while (LocalSize != 0) { Count = (LocalSize + 4087) % 4088 + 1; if (CurrentOffset++ >= OffsetInScope) { ContextRecord->Sp += Count; } LocalSize -= Count; } if (HBit != 0) { CurrentOffset += 4; } if (RegF != 0 && Status == STATUS_SUCCESS) { RegF++; while (RegF != 0) { Count = 2 - (RegF & 1); RegF -= Count; if (CurrentOffset++ >= OffsetInScope) { Status = RtlpUnwindRestoreFpRegisterRange( ContextRecord, (RegF == 0 && RegI == 0) ? (-(LONG)RegSize) : (IntSize + 8 * RegF), 24 + RegF, Count, UnwindParams); } } } if (Cr == 1 && Status == STATUS_SUCCESS) { if (RegI % 2 == 0) { if (CurrentOffset++ >= OffsetInScope) { Status = RtlpUnwindRestoreRegisterRange(ContextRecord, IntSize - 8, 31, 1, UnwindParams);//s8 ? } } else { if (CurrentOffset++ >= OffsetInScope) { RegI--; Status = RtlpUnwindRestoreRegisterRange(ContextRecord, IntSize - 8, 2, 1, UnwindParams);//tp ? if (Status == STATUS_SUCCESS) { Status = RtlpUnwindRestoreRegisterRange(ContextRecord, IntSize - 16, 23 + RegI, 1, UnwindParams); } } } } while (RegI != 0 && Status == STATUS_SUCCESS) { Count = 2 - (RegI & 1); RegI -= Count; if (CurrentOffset++ >= OffsetInScope) { Status = RtlpUnwindRestoreRegisterRange( ContextRecord, (RegI == 0) ? (-(LONG)RegSize) : (8 * RegI), 23 + RegI, Count, UnwindParams); } } } // // If we succeeded, post-process the results a bit // if (Status == STATUS_SUCCESS) { ContextRecord->Pc = ContextRecord->Ra; *EstablisherFrame = ContextRecord->Sp; if (ARGUMENT_PRESENT(HandlerRoutine)) { *HandlerRoutine = NULL; } *HandlerData = NULL; } return Status; } BOOL OOPStackUnwinderLoongarch64::Unwind(T_CONTEXT * pContext) { DWORD64 ImageBase = 0; HRESULT hr = GetModuleBase(pContext->Pc, &ImageBase); if (hr != S_OK) return FALSE; PEXCEPTION_ROUTINE DummyHandlerRoutine; PVOID DummyHandlerData; DWORD64 DummyEstablisherFrame; DWORD64 startingPc = pContext->Pc; DWORD64 startingSp = pContext->Sp; T_RUNTIME_FUNCTION Rfe; if (FAILED(GetFunctionEntry(pContext->Pc, &Rfe, sizeof(Rfe)))) return FALSE; if ((Rfe.UnwindData & 3) != 0) { hr = RtlpUnwindFunctionCompact(pContext->Pc - ImageBase, &Rfe, pContext, &DummyEstablisherFrame, &DummyHandlerRoutine, &DummyHandlerData, NULL); } else { hr = RtlpUnwindFunctionFull(pContext->Pc - ImageBase, ImageBase, &Rfe, pContext, &DummyEstablisherFrame, &DummyHandlerRoutine, &DummyHandlerData, NULL); } // PC == 0 means unwinding is finished. // Same if no forward progress is made if (pContext->Pc == 0 || (startingPc == pContext->Pc && startingSp == pContext->Sp)) return FALSE; return TRUE; } BOOL DacUnwindStackFrame(T_CONTEXT *pContext, T_KNONVOLATILE_CONTEXT_POINTERS* pContextPointers) { OOPStackUnwinderLoongarch64 unwinder; BOOL res = unwinder.Unwind(pContext); if (res && pContextPointers) { for (int i = 0; i < 9; i++) { *(&pContextPointers->S0 + i) = &pContext->S0 + i; } pContextPointers->Fp = &pContext->Fp; pContextPointers->Ra = &pContext->Ra; } return res; } #if defined(HOST_UNIX) PEXCEPTION_ROUTINE RtlVirtualUnwind( IN ULONG HandlerType, IN ULONG64 ImageBase, IN ULONG64 ControlPc, IN PT_RUNTIME_FUNCTION FunctionEntry, IN OUT PCONTEXT ContextRecord, OUT PVOID *HandlerData, OUT PULONG64 EstablisherFrame, IN OUT PT_KNONVOLATILE_CONTEXT_POINTERS ContextPointers OPTIONAL ) { PEXCEPTION_ROUTINE handlerRoutine; HRESULT hr; DWORD64 startingPc = ControlPc; DWORD64 startingSp = ContextRecord->Sp; T_RUNTIME_FUNCTION rfe; rfe.BeginAddress = FunctionEntry->BeginAddress; rfe.UnwindData = FunctionEntry->UnwindData; LOONGARCH64_UNWIND_PARAMS unwindParams; unwindParams.ContextPointers = ContextPointers; if ((rfe.UnwindData & 3) != 0) { hr = RtlpUnwindFunctionCompact(ControlPc - ImageBase, &rfe, ContextRecord, EstablisherFrame, &handlerRoutine, HandlerData, &unwindParams); } else { hr = RtlpUnwindFunctionFull(ControlPc - ImageBase, ImageBase, &rfe, ContextRecord, EstablisherFrame, &handlerRoutine, HandlerData, &unwindParams); } return handlerRoutine; } #endif
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/pal/tests/palsuite/c_runtime/sprintf_s/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 #1 for the sprintf_s function. A single, basic, test ** case with no formatting. ** ** **==========================================================================*/ #include <palsuite.h> #include "../sprintf_s.h" /* * Depends on memcmp and strlen */ PALTEST(c_runtime_sprintf_s_test1_paltest_sprintf_test1, "c_runtime/sprintf_s/test1/paltest_sprintf_test1") { char checkstr[] = "hello world"; char buf[256]; if (PAL_Initialize(argc, argv) != 0) { return FAIL; } sprintf_s(buf, ARRAY_SIZE(buf), "hello world"); if (memcmp(checkstr, buf, strlen(checkstr)+1) != 0) { Fail("ERROR: expected %s, got %s\n", checkstr, buf); } 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 #1 for the sprintf_s function. A single, basic, test ** case with no formatting. ** ** **==========================================================================*/ #include <palsuite.h> #include "../sprintf_s.h" /* * Depends on memcmp and strlen */ PALTEST(c_runtime_sprintf_s_test1_paltest_sprintf_test1, "c_runtime/sprintf_s/test1/paltest_sprintf_test1") { char checkstr[] = "hello world"; char buf[256]; if (PAL_Initialize(argc, argv) != 0) { return FAIL; } sprintf_s(buf, ARRAY_SIZE(buf), "hello world"); if (memcmp(checkstr, buf, strlen(checkstr)+1) != 0) { Fail("ERROR: expected %s, got %s\n", checkstr, buf); } PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/xsltc/baseline/sft35.txt
<?xml version="1.0" encoding="utf-8"?><foo xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:theScript="urn:CustomScript"> Script Result: Hello Foo</foo>
<?xml version="1.0" encoding="utf-8"?><foo xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:theScript="urn:CustomScript"> Script Result: Hello Foo</foo>
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/pal/tests/palsuite/file_io/GetCurrentDirectoryA/test1/GetCurrentDirectoryA.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*===================================================================== ** ** Source: GetCurrentDirectoryA.c (test 1) ** ** Purpose: Tests the PAL implementation of the GetCurrentDirectoryA function. ** ** **===================================================================*/ #include <palsuite.h> PALTEST(file_io_GetCurrentDirectoryA_test1_paltest_getcurrentdirectorya_test1, "file_io/GetCurrentDirectoryA/test1/paltest_getcurrentdirectorya_test1") { const char* szFileName = "blah"; DWORD dwRc = 0; DWORD dwRc2 = 0; char szReturnedPath[_MAX_PATH+1]; char szCurrentDir[_MAX_PATH+1]; LPSTR pPathPtr; size_t nCount = 0; if (0 != PAL_Initialize(argc,argv)) { return FAIL; } // use GetFullPathName to to get the current path by stripping // the file name off the end memset(szReturnedPath, 0, sizeof(char)*(_MAX_PATH+1)); dwRc = GetFullPathNameA(szFileName, _MAX_PATH, szReturnedPath, &pPathPtr); if (dwRc == 0) { // GetFullPathName failed Fail("GetCurrentDirectoryA: ERROR -> GetFullPathNameA failed " "with error code: %ld.\n", GetLastError()); } else if(dwRc > _MAX_PATH) { Fail("GetCurrentDirectoryA: ERROR -> The path name GetFullPathNameA " "returned is longer than _MAX_PATH characters.\n"); } // strip the file name from the full path to get the current path nCount = strlen(szReturnedPath) - strlen(szFileName) - 1; memset(szCurrentDir, 0, sizeof(char)*(_MAX_PATH+1)); strncpy(szCurrentDir, szReturnedPath, nCount); // compare the results of GetCurrentDirectoryA with the above memset(szReturnedPath, 0, sizeof(char)*(_MAX_PATH+1)); dwRc = GetCurrentDirectoryA((sizeof(char)*(_MAX_PATH+1)), szReturnedPath); if (dwRc == 0) { Fail("GetCurrentDirectoryA: ERROR -> GetCurrentDirectoryA failed " "with error code: %ld.\n", GetLastError()); } else if(dwRc > _MAX_PATH) { Fail("GetCurrentDirectoryA: ERROR -> The path name " "returned is longer than _MAX_PATH characters.\n"); } /* test case the passed buffer size is not big enough * function should return the size required + 1 a terminating null character */ /* good buffer size */ dwRc = GetCurrentDirectoryA((sizeof(CHAR)*(_MAX_PATH+1)), szReturnedPath); /* small buffer (0 size)*/ dwRc2 = GetCurrentDirectoryA(0, szReturnedPath); if (dwRc2 != (dwRc+1) ) { Fail("GetCurrentDirectoryA: ERROR -> failed to give the correct " "return value when passed a buffer not big enough. " "Expected %u while result is %u \n",(dwRc+1),dwRc2); } if (strcmp(szReturnedPath, szCurrentDir) != 0) { Fail("GetCurrentDirectoryA: ERROR -> The computed and returned " "directories do not compare.\n"); } 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: GetCurrentDirectoryA.c (test 1) ** ** Purpose: Tests the PAL implementation of the GetCurrentDirectoryA function. ** ** **===================================================================*/ #include <palsuite.h> PALTEST(file_io_GetCurrentDirectoryA_test1_paltest_getcurrentdirectorya_test1, "file_io/GetCurrentDirectoryA/test1/paltest_getcurrentdirectorya_test1") { const char* szFileName = "blah"; DWORD dwRc = 0; DWORD dwRc2 = 0; char szReturnedPath[_MAX_PATH+1]; char szCurrentDir[_MAX_PATH+1]; LPSTR pPathPtr; size_t nCount = 0; if (0 != PAL_Initialize(argc,argv)) { return FAIL; } // use GetFullPathName to to get the current path by stripping // the file name off the end memset(szReturnedPath, 0, sizeof(char)*(_MAX_PATH+1)); dwRc = GetFullPathNameA(szFileName, _MAX_PATH, szReturnedPath, &pPathPtr); if (dwRc == 0) { // GetFullPathName failed Fail("GetCurrentDirectoryA: ERROR -> GetFullPathNameA failed " "with error code: %ld.\n", GetLastError()); } else if(dwRc > _MAX_PATH) { Fail("GetCurrentDirectoryA: ERROR -> The path name GetFullPathNameA " "returned is longer than _MAX_PATH characters.\n"); } // strip the file name from the full path to get the current path nCount = strlen(szReturnedPath) - strlen(szFileName) - 1; memset(szCurrentDir, 0, sizeof(char)*(_MAX_PATH+1)); strncpy(szCurrentDir, szReturnedPath, nCount); // compare the results of GetCurrentDirectoryA with the above memset(szReturnedPath, 0, sizeof(char)*(_MAX_PATH+1)); dwRc = GetCurrentDirectoryA((sizeof(char)*(_MAX_PATH+1)), szReturnedPath); if (dwRc == 0) { Fail("GetCurrentDirectoryA: ERROR -> GetCurrentDirectoryA failed " "with error code: %ld.\n", GetLastError()); } else if(dwRc > _MAX_PATH) { Fail("GetCurrentDirectoryA: ERROR -> The path name " "returned is longer than _MAX_PATH characters.\n"); } /* test case the passed buffer size is not big enough * function should return the size required + 1 a terminating null character */ /* good buffer size */ dwRc = GetCurrentDirectoryA((sizeof(CHAR)*(_MAX_PATH+1)), szReturnedPath); /* small buffer (0 size)*/ dwRc2 = GetCurrentDirectoryA(0, szReturnedPath); if (dwRc2 != (dwRc+1) ) { Fail("GetCurrentDirectoryA: ERROR -> failed to give the correct " "return value when passed a buffer not big enough. " "Expected %u while result is %u \n",(dwRc+1),dwRc2); } if (strcmp(szReturnedPath, szCurrentDir) != 0) { Fail("GetCurrentDirectoryA: ERROR -> The computed and returned " "directories do not compare.\n"); } PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/tools/aot/jitinterface/jitinterface.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <stdarg.h> #include <stdlib.h> #include <stdint.h> #include "dllexport.h" #include "jitinterface.h" static void NotImplemented() { abort(); } int JitInterfaceWrapper::FilterException(struct _EXCEPTION_POINTERS* pExceptionPointers) { NotImplemented(); return 1; // EXCEPTION_EXECUTE_HANDLER } bool JitInterfaceWrapper::runWithErrorTrap(ICorJitInfo::errorTrapFunction function, void* parameter) { try { (*function)(parameter); } catch (CorInfoExceptionClass *) { return false; } return true; } bool JitInterfaceWrapper::runWithSPMIErrorTrap(ICorJitInfo::errorTrapFunction function, void* parameter) { try { (*function)(parameter); } catch (CorInfoExceptionClass *) { return false; } return true; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <stdarg.h> #include <stdlib.h> #include <stdint.h> #include "dllexport.h" #include "jitinterface.h" static void NotImplemented() { abort(); } int JitInterfaceWrapper::FilterException(struct _EXCEPTION_POINTERS* pExceptionPointers) { NotImplemented(); return 1; // EXCEPTION_EXECUTE_HANDLER } bool JitInterfaceWrapper::runWithErrorTrap(ICorJitInfo::errorTrapFunction function, void* parameter) { try { (*function)(parameter); } catch (CorInfoExceptionClass *) { return false; } return true; } bool JitInterfaceWrapper::runWithSPMIErrorTrap(ICorJitInfo::errorTrapFunction function, void* parameter) { try { (*function)(parameter); } catch (CorInfoExceptionClass *) { return false; } return true; }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/tools/superpmi/mcs/verbfracture.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "standardpch.h" #include "verbfracture.h" #include "simpletimer.h" #include "methodcontext.h" #include "methodcontextiterator.h" #include "errorhandling.h" #include "logging.h" int verbFracture::DoWork( const char* nameOfInput, const char* nameOfOutput, int indexCount, const int* indexes, bool stripCR) { int rangeSize = indexes[0]; LogVerbose("Reading from '%s' copying %d MethodContexts files into each output file of '%s'", nameOfInput, rangeSize, nameOfOutput); MethodContextIterator mci(true); if (!mci.Initialize(nameOfInput)) return -1; int fileCount = 0; char fileName[512]; HANDLE hFileOut = INVALID_HANDLE_VALUE; while (mci.MoveNext()) { MethodContext* mc = mci.Current(); if ((hFileOut == INVALID_HANDLE_VALUE) || (((mci.MethodContextNumber() - 1) % rangeSize) == 0)) { if (hFileOut != INVALID_HANDLE_VALUE) { if (!CloseHandle(hFileOut)) { LogError("1st CloseHandle failed. GetLastError()=%u", GetLastError()); return -1; } hFileOut = INVALID_HANDLE_VALUE; } sprintf_s(fileName, 512, "%s-%0*d.mch", nameOfOutput, 5, fileCount++); hFileOut = CreateFileA(fileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (hFileOut == INVALID_HANDLE_VALUE) { LogError("Failed to open output file '%s'. GetLastError()=%u", fileName, GetLastError()); return -1; } } if (stripCR) { delete mc->cr; mc->cr = new CompileResult(); } mc->saveToFile(hFileOut); } if (hFileOut != INVALID_HANDLE_VALUE) { if (!CloseHandle(hFileOut)) { LogError("2nd CloseHandle failed. GetLastError()=%u", GetLastError()); return -1; } } LogInfo("Output fileCount %d", fileCount); if (!mci.Destroy()) return -1; return 0; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "standardpch.h" #include "verbfracture.h" #include "simpletimer.h" #include "methodcontext.h" #include "methodcontextiterator.h" #include "errorhandling.h" #include "logging.h" int verbFracture::DoWork( const char* nameOfInput, const char* nameOfOutput, int indexCount, const int* indexes, bool stripCR) { int rangeSize = indexes[0]; LogVerbose("Reading from '%s' copying %d MethodContexts files into each output file of '%s'", nameOfInput, rangeSize, nameOfOutput); MethodContextIterator mci(true); if (!mci.Initialize(nameOfInput)) return -1; int fileCount = 0; char fileName[512]; HANDLE hFileOut = INVALID_HANDLE_VALUE; while (mci.MoveNext()) { MethodContext* mc = mci.Current(); if ((hFileOut == INVALID_HANDLE_VALUE) || (((mci.MethodContextNumber() - 1) % rangeSize) == 0)) { if (hFileOut != INVALID_HANDLE_VALUE) { if (!CloseHandle(hFileOut)) { LogError("1st CloseHandle failed. GetLastError()=%u", GetLastError()); return -1; } hFileOut = INVALID_HANDLE_VALUE; } sprintf_s(fileName, 512, "%s-%0*d.mch", nameOfOutput, 5, fileCount++); hFileOut = CreateFileA(fileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (hFileOut == INVALID_HANDLE_VALUE) { LogError("Failed to open output file '%s'. GetLastError()=%u", fileName, GetLastError()); return -1; } } if (stripCR) { delete mc->cr; mc->cr = new CompileResult(); } mc->saveToFile(hFileOut); } if (hFileOut != INVALID_HANDLE_VALUE) { if (!CloseHandle(hFileOut)) { LogError("2nd CloseHandle failed. GetLastError()=%u", GetLastError()); return -1; } } LogInfo("Output fileCount %d", fileCount); if (!mci.Destroy()) return -1; return 0; }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/unwinder/s390x/unwinder_s390x.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // #include "stdafx.h" #include "utilcode.h" #include "crosscomp.h" #error Unsupported platform
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // #include "stdafx.h" #include "utilcode.h" #include "crosscomp.h" #error Unsupported platform
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/pal/tests/palsuite/c_runtime/_wfopen/test5/test5.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*===================================================================== ** ** Source: test5.c ** ** Purpose: Tests the PAL implementation of the _wfopen function. ** Test to ensure that you can write to a 'r+' mode file. ** And that you can read from a 'r+' mode file. ** ** Depends: ** fprintf ** fclose ** fgets ** fseek ** ** **===================================================================*/ #define UNICODE #include <palsuite.h> PALTEST(c_runtime__wfopen_test5_paltest_wfopen_test5, "c_runtime/_wfopen/test5/paltest_wfopen_test5") { FILE *fp; char buffer[128]; WCHAR filename[] = {'t','e','s','t','f','i','l','e','\0'}; WCHAR write[] = {'w','\0'}; WCHAR readplus[] = {'r','+','\0'}; if (PAL_Initialize(argc, argv)) { return FAIL; } /* Open a file with 'w' mode */ if( (fp = _wfopen( filename,write )) == NULL ) { Fail( "ERROR: The file failed to open with 'w' mode.\n" ); } if(fclose(fp)) { Fail("ERROR: Attempted to close a file, but fclose failed. " "This test depends upon it."); } if( (fp = _wfopen( filename, readplus )) == NULL ) { Fail( "ERROR: The file failed to open with 'r+' mode.\n" ); } /* Write some text to the file */ if(fprintf(fp,"%s","some text") <= 0) { Fail("ERROR: Attempted to WRITE to a file opened with 'r+' mode " "but fprintf failed. Either fopen or fprintf have problems."); } if(fseek(fp, 0, SEEK_SET)) { Fail("ERROR: fseek failed, and this test depends on it."); } /* Attempt to read from the 'r+' only file, should pass */ if(fgets(buffer,10,fp) == NULL) { Fail("ERROR: Tried to READ from a file with 'r+' mode set. " "This should succeed, but fgets returned NULL. Either fgets " "or fopen is broken."); } 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: test5.c ** ** Purpose: Tests the PAL implementation of the _wfopen function. ** Test to ensure that you can write to a 'r+' mode file. ** And that you can read from a 'r+' mode file. ** ** Depends: ** fprintf ** fclose ** fgets ** fseek ** ** **===================================================================*/ #define UNICODE #include <palsuite.h> PALTEST(c_runtime__wfopen_test5_paltest_wfopen_test5, "c_runtime/_wfopen/test5/paltest_wfopen_test5") { FILE *fp; char buffer[128]; WCHAR filename[] = {'t','e','s','t','f','i','l','e','\0'}; WCHAR write[] = {'w','\0'}; WCHAR readplus[] = {'r','+','\0'}; if (PAL_Initialize(argc, argv)) { return FAIL; } /* Open a file with 'w' mode */ if( (fp = _wfopen( filename,write )) == NULL ) { Fail( "ERROR: The file failed to open with 'w' mode.\n" ); } if(fclose(fp)) { Fail("ERROR: Attempted to close a file, but fclose failed. " "This test depends upon it."); } if( (fp = _wfopen( filename, readplus )) == NULL ) { Fail( "ERROR: The file failed to open with 'r+' mode.\n" ); } /* Write some text to the file */ if(fprintf(fp,"%s","some text") <= 0) { Fail("ERROR: Attempted to WRITE to a file opened with 'r+' mode " "but fprintf failed. Either fopen or fprintf have problems."); } if(fseek(fp, 0, SEEK_SET)) { Fail("ERROR: fseek failed, and this test depends on it."); } /* Attempt to read from the 'r+' only file, should pass */ if(fgets(buffer,10,fp) == NULL) { Fail("ERROR: Tried to READ from a file with 'r+' mode set. " "This should succeed, but fgets returned NULL. Either fgets " "or fopen is broken."); } PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/Interop/PInvoke/CriticalHandles/CMakeLists.txt
project (CriticalHandlesNative) include ("${CLR_INTEROP_TEST_ROOT}/Interop.cmake") set(SOURCES CriticalHandlesNative.cpp ) # add the executable add_library (CriticalHandlesNative SHARED ${SOURCES}) target_link_libraries(CriticalHandlesNative ${LINK_LIBRARIES_ADDITIONAL}) # add the install targets install (TARGETS CriticalHandlesNative DESTINATION bin)
project (CriticalHandlesNative) include ("${CLR_INTEROP_TEST_ROOT}/Interop.cmake") set(SOURCES CriticalHandlesNative.cpp ) # add the executable add_library (CriticalHandlesNative SHARED ${SOURCES}) target_link_libraries(CriticalHandlesNative ${LINK_LIBRARIES_ADDITIONAL}) # add the install targets install (TARGETS CriticalHandlesNative DESTINATION bin)
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/pal/tests/palsuite/miscellaneous/CloseHandle/test2/test.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================ ** ** Source: test.c ** ** Purpose: Test for CloseHandle function, try to close an unopened HANDLE ** ** **=========================================================*/ #include <palsuite.h> PALTEST(miscellaneous_CloseHandle_test2_paltest_closehandle_test2, "miscellaneous/CloseHandle/test2/paltest_closehandle_test2") { HANDLE SomeHandle = NULL; /* * Initialize the PAL and return FAILURE if this fails */ if(0 != (PAL_Initialize(argc, argv))) { return FAIL; } /* If the handle is already closed and you can close it again, * something is wrong. */ if(CloseHandle(SomeHandle) != 0) { Fail("ERROR: Called CloseHandle on an already closed Handle " "and it still returned as a success.\n"); } 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: test.c ** ** Purpose: Test for CloseHandle function, try to close an unopened HANDLE ** ** **=========================================================*/ #include <palsuite.h> PALTEST(miscellaneous_CloseHandle_test2_paltest_closehandle_test2, "miscellaneous/CloseHandle/test2/paltest_closehandle_test2") { HANDLE SomeHandle = NULL; /* * Initialize the PAL and return FAILURE if this fails */ if(0 != (PAL_Initialize(argc, argv))) { return FAIL; } /* If the handle is already closed and you can close it again, * something is wrong. */ if(CloseHandle(SomeHandle) != 0) { Fail("ERROR: Called CloseHandle on an already closed Handle " "and it still returned as a success.\n"); } PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitcompiler.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "standardpch.h" #include "spmiutil.h" #include "icorjitcompiler.h" #include "icorjitinfo.h" #include "jithost.h" #include "superpmi-shim-collector.h" #define fatMC // this is nice to have on so ildump works... void interceptor_ICJC::setTargetOS(CORINFO_OS os) { currentOs = os; original_ICorJitCompiler->setTargetOS(os); } CorJitResult interceptor_ICJC::compileMethod(ICorJitInfo* comp, /* IN */ struct CORINFO_METHOD_INFO* info, /* IN */ unsigned /* code:CorJitFlag */ flags, /* IN */ uint8_t** nativeEntry, /* OUT */ uint32_t* nativeSizeOfCode /* OUT */ ) { interceptor_ICJI our_ICorJitInfo; our_ICorJitInfo.original_ICorJitInfo = comp; auto* mc = new MethodContext(); our_ICorJitInfo.mc = mc; our_ICorJitInfo.mc->cr->recProcessName(GetCommandLineA()); our_ICorJitInfo.mc->recCompileMethod(info, flags, currentOs); // force some extra data into our tables.. // data probably not needed with RyuJIT, but needed in 4.5 and 4.5.1 to help with catching cached values our_ICorJitInfo.getBuiltinClass(CLASSID_SYSTEM_OBJECT); our_ICorJitInfo.getBuiltinClass(CLASSID_TYPED_BYREF); our_ICorJitInfo.getBuiltinClass(CLASSID_TYPE_HANDLE); our_ICorJitInfo.getBuiltinClass(CLASSID_FIELD_HANDLE); our_ICorJitInfo.getBuiltinClass(CLASSID_METHOD_HANDLE); our_ICorJitInfo.getBuiltinClass(CLASSID_STRING); our_ICorJitInfo.getBuiltinClass(CLASSID_RUNTIME_TYPE); #ifdef fatMC // to build up a fat mc CORINFO_CLASS_HANDLE ourClass = our_ICorJitInfo.getMethodClass(info->ftn); our_ICorJitInfo.getClassAttribs(ourClass); our_ICorJitInfo.getClassName(ourClass); our_ICorJitInfo.isValueClass(ourClass); our_ICorJitInfo.asCorInfoType(ourClass); const char* className = nullptr; our_ICorJitInfo.getMethodName(info->ftn, &className); #endif // Record data from the global context, if any if (g_globalContext != nullptr) { our_ICorJitInfo.mc->recGlobalContext(*g_globalContext); } CorJitResult temp = original_ICorJitCompiler->compileMethod(&our_ICorJitInfo, info, flags, nativeEntry, nativeSizeOfCode); if (temp == CORJIT_OK) { // capture the results of compilation our_ICorJitInfo.mc->cr->recCompileMethod(nativeEntry, nativeSizeOfCode, temp); our_ICorJitInfo.mc->cr->recAllocMemCapture(); our_ICorJitInfo.mc->cr->recAllocGCInfoCapture(); our_ICorJitInfo.mc->saveToFile(hFile); } delete mc; return temp; } void interceptor_ICJC::ProcessShutdownWork(ICorStaticInfo* info) { original_ICorJitCompiler->ProcessShutdownWork(info); } void interceptor_ICJC::getVersionIdentifier(GUID* versionIdentifier /* OUT */) { original_ICorJitCompiler->getVersionIdentifier(versionIdentifier); } unsigned interceptor_ICJC::getMaxIntrinsicSIMDVectorLength(CORJIT_FLAGS cpuCompileFlags) { return original_ICorJitCompiler->getMaxIntrinsicSIMDVectorLength(cpuCompileFlags); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "standardpch.h" #include "spmiutil.h" #include "icorjitcompiler.h" #include "icorjitinfo.h" #include "jithost.h" #include "superpmi-shim-collector.h" #define fatMC // this is nice to have on so ildump works... void interceptor_ICJC::setTargetOS(CORINFO_OS os) { currentOs = os; original_ICorJitCompiler->setTargetOS(os); } CorJitResult interceptor_ICJC::compileMethod(ICorJitInfo* comp, /* IN */ struct CORINFO_METHOD_INFO* info, /* IN */ unsigned /* code:CorJitFlag */ flags, /* IN */ uint8_t** nativeEntry, /* OUT */ uint32_t* nativeSizeOfCode /* OUT */ ) { interceptor_ICJI our_ICorJitInfo; our_ICorJitInfo.original_ICorJitInfo = comp; auto* mc = new MethodContext(); our_ICorJitInfo.mc = mc; our_ICorJitInfo.mc->cr->recProcessName(GetCommandLineA()); our_ICorJitInfo.mc->recCompileMethod(info, flags, currentOs); // force some extra data into our tables.. // data probably not needed with RyuJIT, but needed in 4.5 and 4.5.1 to help with catching cached values our_ICorJitInfo.getBuiltinClass(CLASSID_SYSTEM_OBJECT); our_ICorJitInfo.getBuiltinClass(CLASSID_TYPED_BYREF); our_ICorJitInfo.getBuiltinClass(CLASSID_TYPE_HANDLE); our_ICorJitInfo.getBuiltinClass(CLASSID_FIELD_HANDLE); our_ICorJitInfo.getBuiltinClass(CLASSID_METHOD_HANDLE); our_ICorJitInfo.getBuiltinClass(CLASSID_STRING); our_ICorJitInfo.getBuiltinClass(CLASSID_RUNTIME_TYPE); #ifdef fatMC // to build up a fat mc CORINFO_CLASS_HANDLE ourClass = our_ICorJitInfo.getMethodClass(info->ftn); our_ICorJitInfo.getClassAttribs(ourClass); our_ICorJitInfo.getClassName(ourClass); our_ICorJitInfo.isValueClass(ourClass); our_ICorJitInfo.asCorInfoType(ourClass); const char* className = nullptr; our_ICorJitInfo.getMethodName(info->ftn, &className); #endif // Record data from the global context, if any if (g_globalContext != nullptr) { our_ICorJitInfo.mc->recGlobalContext(*g_globalContext); } CorJitResult temp = original_ICorJitCompiler->compileMethod(&our_ICorJitInfo, info, flags, nativeEntry, nativeSizeOfCode); if (temp == CORJIT_OK) { // capture the results of compilation our_ICorJitInfo.mc->cr->recCompileMethod(nativeEntry, nativeSizeOfCode, temp); our_ICorJitInfo.mc->cr->recAllocMemCapture(); our_ICorJitInfo.mc->cr->recAllocGCInfoCapture(); our_ICorJitInfo.mc->saveToFile(hFile); } delete mc; return temp; } void interceptor_ICJC::ProcessShutdownWork(ICorStaticInfo* info) { original_ICorJitCompiler->ProcessShutdownWork(info); } void interceptor_ICJC::getVersionIdentifier(GUID* versionIdentifier /* OUT */) { original_ICorJitCompiler->getVersionIdentifier(versionIdentifier); } unsigned interceptor_ICJC::getMaxIntrinsicSIMDVectorLength(CORJIT_FLAGS cpuCompileFlags) { return original_ICorJitCompiler->getMaxIntrinsicSIMDVectorLength(cpuCompileFlags); }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/xsltc/baseline/sft2.txt
Microsoft (R) XSLT Compiler version 2.0.61009 for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727 Copyright (C) Microsoft Corporation 2007. All rights reserved. sft2.xsl(0,0) : fatal error : Processing DTDs is prohibited. For trusted stylesheets use /settings:dtd option to enable this feature.
Microsoft (R) XSLT Compiler version 2.0.61009 for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727 Copyright (C) Microsoft Corporation 2007. All rights reserved. sft2.xsl(0,0) : fatal error : Processing DTDs is prohibited. For trusted stylesheets use /settings:dtd option to enable this feature.
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/pal/tests/palsuite/c_runtime/sscanf_s/test3/test3.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================================ ** ** Source: test3.c ** ** Purpose: Tests sscanf_s with bracketed set strings ** ** **==========================================================================*/ #include <palsuite.h> #include "../sscanf_s.h" PALTEST(c_runtime_sscanf_s_test3_paltest_sscanf_test3, "c_runtime/sscanf_s/test3/paltest_sscanf_test3") { if (PAL_Initialize(argc, argv)) { return FAIL; } DoStrTest("bar1", "%[a-z]", "bar"); DoStrTest("bar1", "%[z-a]", "bar"); DoStrTest("bar1", "%[ab]", "ba"); DoStrTest("bar1", "%[ar1b]", "bar1"); DoStrTest("bar1", "%[^4]", "bar1"); DoStrTest("bar1", "%[^4a]", "b"); 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: test3.c ** ** Purpose: Tests sscanf_s with bracketed set strings ** ** **==========================================================================*/ #include <palsuite.h> #include "../sscanf_s.h" PALTEST(c_runtime_sscanf_s_test3_paltest_sscanf_test3, "c_runtime/sscanf_s/test3/paltest_sscanf_test3") { if (PAL_Initialize(argc, argv)) { return FAIL; } DoStrTest("bar1", "%[a-z]", "bar"); DoStrTest("bar1", "%[z-a]", "bar"); DoStrTest("bar1", "%[ab]", "ba"); DoStrTest("bar1", "%[ar1b]", "bar1"); DoStrTest("bar1", "%[^4]", "bar1"); DoStrTest("bar1", "%[^4a]", "b"); PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/debug/di/shimremotedatatarget.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //***************************************************************************** // // File: ShimRemoteDataTarget.cpp // //***************************************************************************** #include "stdafx.h" #include "safewrap.h" #include "check.h" #include <limits.h> #include "shimpriv.h" #include "shimdatatarget.h" #include "dbgtransportsession.h" #include "dbgtransportmanager.h" class ShimRemoteDataTarget : public ShimDataTarget { public: ShimRemoteDataTarget(DWORD processId, DbgTransportTarget * pProxy, DbgTransportSession * pTransport); virtual ~ShimRemoteDataTarget(); virtual void Dispose(); // // ICorDebugMutableDataTarget. // virtual HRESULT STDMETHODCALLTYPE GetPlatform( CorDebugPlatform *pPlatform); virtual HRESULT STDMETHODCALLTYPE ReadVirtual( CORDB_ADDRESS address, BYTE * pBuffer, ULONG32 request, ULONG32 *pcbRead); virtual HRESULT STDMETHODCALLTYPE WriteVirtual( CORDB_ADDRESS address, const BYTE * pBuffer, ULONG32 request); virtual HRESULT STDMETHODCALLTYPE GetThreadContext( DWORD dwThreadID, ULONG32 contextFlags, ULONG32 contextSize, BYTE * context); virtual HRESULT STDMETHODCALLTYPE SetThreadContext( DWORD dwThreadID, ULONG32 contextSize, const BYTE * context); virtual HRESULT STDMETHODCALLTYPE ContinueStatusChanged( DWORD dwThreadId, CORDB_CONTINUE_STATUS dwContinueStatus); virtual HRESULT STDMETHODCALLTYPE VirtualUnwind( DWORD threadId, ULONG32 contextSize, PBYTE context); private: DbgTransportTarget * m_pProxy; DbgTransportSession * m_pTransport; #ifdef FEATURE_REMOTE_PROC_MEM DWORD m_memoryHandle; // PAL_ReadProcessMemory handle or UINT32_MAX if fallback #endif }; // Helper macro to check for failure conditions at the start of data-target methods. #define ReturnFailureIfStateNotOk() \ if (m_hr != S_OK) \ { \ return m_hr; \ } //--------------------------------------------------------------------------------------- // // This is the ctor for ShimRemoteDataTarget. // // Arguments: // processId - pid of live process on the remote machine // pProxy - connection to the debugger proxy // pTransport - connection to the debuggee process // ShimRemoteDataTarget::ShimRemoteDataTarget(DWORD processId, DbgTransportTarget * pProxy, DbgTransportSession * pTransport) { m_ref = 0; m_processId = processId; m_pProxy = pProxy; m_pTransport = pTransport; m_hr = S_OK; m_fpContinueStatusChanged = NULL; m_pContinueStatusChangedUserData = NULL; #ifdef FEATURE_REMOTE_PROC_MEM PAL_OpenProcessMemory(m_processId, &m_memoryHandle); #endif } //--------------------------------------------------------------------------------------- // // dtor for ShimRemoteDataTarget // ShimRemoteDataTarget::~ShimRemoteDataTarget() { Dispose(); } //--------------------------------------------------------------------------------------- // // Dispose all resources and neuter the object. // // Notes: // Release all resources (such as the connections to the debugger proxy and the debuggee process). // May be called multiple times. // All other non-trivial APIs (eg, not IUnknown) will fail after this. // void ShimRemoteDataTarget::Dispose() { #ifdef FEATURE_REMOTE_PROC_MEM PAL_CloseProcessMemory(m_memoryHandle); m_memoryHandle = UINT32_MAX; #endif if (m_pTransport != NULL) { m_pProxy->ReleaseTransport(m_pTransport); } m_pTransport = NULL; m_hr = CORDBG_E_OBJECT_NEUTERED; } //--------------------------------------------------------------------------------------- // // Construction method for data-target // // Arguments: // machineInfo - (input) the IP address of the remote machine and the port number of the debugger proxy // processId - (input) live OS process ID to build a data-target for. // ppDataTarget - (output) new data-target instance. This gets addreffed. // // Return Value: // S_OK on success. // // Assumptions: // pid is for a process on the remote machine specified by the IP address in machineInfo // Caller must release *ppDataTarget. // HRESULT BuildPlatformSpecificDataTarget(MachineInfo machineInfo, const ProcessDescriptor * pProcessDescriptor, ShimDataTarget ** ppDataTarget) { HandleHolder hDummy; HRESULT hr = E_FAIL; ShimRemoteDataTarget * pRemoteDataTarget = NULL; DbgTransportTarget * pProxy = g_pDbgTransportTarget; DbgTransportSession * pTransport = NULL; hr = pProxy->GetTransportForProcess(pProcessDescriptor, &pTransport, &hDummy); if (FAILED(hr)) { goto Label_Exit; } if (!pTransport->WaitForSessionToOpen(10000)) { hr = CORDBG_E_TIMEOUT; goto Label_Exit; } pRemoteDataTarget = new (nothrow) ShimRemoteDataTarget(pProcessDescriptor->m_Pid, pProxy, pTransport); if (pRemoteDataTarget == NULL) { hr = E_OUTOFMEMORY; goto Label_Exit; } _ASSERTE(SUCCEEDED(hr)); *ppDataTarget = pRemoteDataTarget; pRemoteDataTarget->AddRef(); // must addref out-parameters Label_Exit: if (FAILED(hr)) { if (pRemoteDataTarget != NULL) { // The ShimRemoteDataTarget has ownership of the proxy and the transport, // so we don't need to clean them up here. delete pRemoteDataTarget; } else { if (pTransport != NULL) { pProxy->ReleaseTransport(pTransport); } } } return hr; } // impl of interface method ICorDebugDataTarget::GetPlatform HRESULT STDMETHODCALLTYPE ShimRemoteDataTarget::GetPlatform( CorDebugPlatform *pPlatform) { #ifdef TARGET_UNIX #if defined(TARGET_X86) *pPlatform = CORDB_PLATFORM_POSIX_X86; #elif defined(TARGET_AMD64) *pPlatform = CORDB_PLATFORM_POSIX_AMD64; #elif defined(TARGET_ARM) *pPlatform = CORDB_PLATFORM_POSIX_ARM; #elif defined(TARGET_ARM64) *pPlatform = CORDB_PLATFORM_POSIX_ARM64; #else #error Unknown Processor. #endif #else #if defined(TARGET_X86) *pPlatform = CORDB_PLATFORM_WINDOWS_X86; #elif defined(TARGET_AMD64) *pPlatform = CORDB_PLATFORM_WINDOWS_AMD64; #elif defined(TARGET_ARM) *pPlatform = CORDB_PLATFORM_WINDOWS_ARM; #elif defined(TARGET_ARM64) *pPlatform = CORDB_PLATFORM_WINDOWS_ARM64; #else #error Unknown Processor. #endif #endif return S_OK; } // impl of interface method ICorDebugDataTarget::ReadVirtual HRESULT STDMETHODCALLTYPE ShimRemoteDataTarget::ReadVirtual( CORDB_ADDRESS address, PBYTE pBuffer, ULONG32 cbRequestSize, ULONG32 *pcbRead) { ReturnFailureIfStateNotOk(); size_t read = cbRequestSize; HRESULT hr = S_OK; #ifdef FEATURE_REMOTE_PROC_MEM if (m_memoryHandle != UINT32_MAX) { if (!PAL_ReadProcessMemory(m_memoryHandle, (ULONG64)address, pBuffer, cbRequestSize, &read)) { hr = E_FAIL; } } else #endif { hr = m_pTransport->ReadMemory(reinterpret_cast<BYTE *>(CORDB_ADDRESS_TO_PTR(address)), pBuffer, cbRequestSize); } if (pcbRead != NULL) { *pcbRead = ULONG32(SUCCEEDED(hr) ? read : 0); } return hr; } // impl of interface method ICorDebugMutableDataTarget::WriteVirtual HRESULT STDMETHODCALLTYPE ShimRemoteDataTarget::WriteVirtual( CORDB_ADDRESS pAddress, const BYTE * pBuffer, ULONG32 cbRequestSize) { ReturnFailureIfStateNotOk(); HRESULT hr = E_FAIL; hr = m_pTransport->WriteMemory(reinterpret_cast<BYTE *>(CORDB_ADDRESS_TO_PTR(pAddress)), const_cast<BYTE *>(pBuffer), cbRequestSize); return hr; } // impl of interface method ICorDebugMutableDataTarget::GetThreadContext HRESULT STDMETHODCALLTYPE ShimRemoteDataTarget::GetThreadContext( DWORD dwThreadID, ULONG32 contextFlags, ULONG32 contextSize, BYTE * pContext) { ReturnFailureIfStateNotOk(); // GetThreadContext() is currently not implemented in ShimRemoteDataTarget, which is used with our pipe transport // (FEATURE_DBGIPC_TRANSPORT_DI). Pipe transport is used on POSIX system, but occasionally we can turn it on for Windows for testing, // and then we'd like to have same behavior as on POSIX system (zero context). // // We don't have a good way to implement GetThreadContext() in ShimRemoteDataTarget yet, because we have no way to convert a thread ID to a // thread handle. The function to do the conversion is OpenThread(), which is not implemented in PAL. Even if we had a handle, PAL implementation // of GetThreadContext() is very limited and doesn't work when we're not attached with ptrace. // Instead, we just zero out the seed CONTEXT for the stackwalk. This tells the stackwalker to // start the stackwalk with the first explicit frame. This won't work when we do native debugging, // but that won't happen on the POSIX systems since they don't support native debugging. ZeroMemory(pContext, contextSize); return E_NOTIMPL; } // impl of interface method ICorDebugMutableDataTarget::SetThreadContext HRESULT STDMETHODCALLTYPE ShimRemoteDataTarget::SetThreadContext( DWORD dwThreadID, ULONG32 contextSize, const BYTE * pContext) { ReturnFailureIfStateNotOk(); // ICorDebugDataTarget::GetThreadContext() and ICorDebugDataTarget::SetThreadContext() are currently only // required for interop-debugging and inspection of floating point registers, both of which are not // implemented on Mac. _ASSERTE(!"The remote data target doesn't know how to set a thread's CONTEXT."); return E_NOTIMPL; } // Public implementation of ICorDebugMutableDataTarget::ContinueStatusChanged HRESULT STDMETHODCALLTYPE ShimRemoteDataTarget::ContinueStatusChanged( DWORD dwThreadId, CORDB_CONTINUE_STATUS dwContinueStatus) { ReturnFailureIfStateNotOk(); _ASSERTE(!"ShimRemoteDataTarget::ContinueStatusChanged() is called unexpectedly"); if (m_fpContinueStatusChanged != NULL) { return m_fpContinueStatusChanged(m_pContinueStatusChangedUserData, dwThreadId, dwContinueStatus); } return E_NOTIMPL; } //--------------------------------------------------------------------------------------- // // Unwind the stack to the next frame. // // Return Value: // context filled in with the next frame // HRESULT STDMETHODCALLTYPE ShimRemoteDataTarget::VirtualUnwind(DWORD threadId, ULONG32 contextSize, PBYTE context) { return m_pTransport->VirtualUnwind(threadId, contextSize, context); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //***************************************************************************** // // File: ShimRemoteDataTarget.cpp // //***************************************************************************** #include "stdafx.h" #include "safewrap.h" #include "check.h" #include <limits.h> #include "shimpriv.h" #include "shimdatatarget.h" #include "dbgtransportsession.h" #include "dbgtransportmanager.h" class ShimRemoteDataTarget : public ShimDataTarget { public: ShimRemoteDataTarget(DWORD processId, DbgTransportTarget * pProxy, DbgTransportSession * pTransport); virtual ~ShimRemoteDataTarget(); virtual void Dispose(); // // ICorDebugMutableDataTarget. // virtual HRESULT STDMETHODCALLTYPE GetPlatform( CorDebugPlatform *pPlatform); virtual HRESULT STDMETHODCALLTYPE ReadVirtual( CORDB_ADDRESS address, BYTE * pBuffer, ULONG32 request, ULONG32 *pcbRead); virtual HRESULT STDMETHODCALLTYPE WriteVirtual( CORDB_ADDRESS address, const BYTE * pBuffer, ULONG32 request); virtual HRESULT STDMETHODCALLTYPE GetThreadContext( DWORD dwThreadID, ULONG32 contextFlags, ULONG32 contextSize, BYTE * context); virtual HRESULT STDMETHODCALLTYPE SetThreadContext( DWORD dwThreadID, ULONG32 contextSize, const BYTE * context); virtual HRESULT STDMETHODCALLTYPE ContinueStatusChanged( DWORD dwThreadId, CORDB_CONTINUE_STATUS dwContinueStatus); virtual HRESULT STDMETHODCALLTYPE VirtualUnwind( DWORD threadId, ULONG32 contextSize, PBYTE context); private: DbgTransportTarget * m_pProxy; DbgTransportSession * m_pTransport; #ifdef FEATURE_REMOTE_PROC_MEM DWORD m_memoryHandle; // PAL_ReadProcessMemory handle or UINT32_MAX if fallback #endif }; // Helper macro to check for failure conditions at the start of data-target methods. #define ReturnFailureIfStateNotOk() \ if (m_hr != S_OK) \ { \ return m_hr; \ } //--------------------------------------------------------------------------------------- // // This is the ctor for ShimRemoteDataTarget. // // Arguments: // processId - pid of live process on the remote machine // pProxy - connection to the debugger proxy // pTransport - connection to the debuggee process // ShimRemoteDataTarget::ShimRemoteDataTarget(DWORD processId, DbgTransportTarget * pProxy, DbgTransportSession * pTransport) { m_ref = 0; m_processId = processId; m_pProxy = pProxy; m_pTransport = pTransport; m_hr = S_OK; m_fpContinueStatusChanged = NULL; m_pContinueStatusChangedUserData = NULL; #ifdef FEATURE_REMOTE_PROC_MEM PAL_OpenProcessMemory(m_processId, &m_memoryHandle); #endif } //--------------------------------------------------------------------------------------- // // dtor for ShimRemoteDataTarget // ShimRemoteDataTarget::~ShimRemoteDataTarget() { Dispose(); } //--------------------------------------------------------------------------------------- // // Dispose all resources and neuter the object. // // Notes: // Release all resources (such as the connections to the debugger proxy and the debuggee process). // May be called multiple times. // All other non-trivial APIs (eg, not IUnknown) will fail after this. // void ShimRemoteDataTarget::Dispose() { #ifdef FEATURE_REMOTE_PROC_MEM PAL_CloseProcessMemory(m_memoryHandle); m_memoryHandle = UINT32_MAX; #endif if (m_pTransport != NULL) { m_pProxy->ReleaseTransport(m_pTransport); } m_pTransport = NULL; m_hr = CORDBG_E_OBJECT_NEUTERED; } //--------------------------------------------------------------------------------------- // // Construction method for data-target // // Arguments: // machineInfo - (input) the IP address of the remote machine and the port number of the debugger proxy // processId - (input) live OS process ID to build a data-target for. // ppDataTarget - (output) new data-target instance. This gets addreffed. // // Return Value: // S_OK on success. // // Assumptions: // pid is for a process on the remote machine specified by the IP address in machineInfo // Caller must release *ppDataTarget. // HRESULT BuildPlatformSpecificDataTarget(MachineInfo machineInfo, const ProcessDescriptor * pProcessDescriptor, ShimDataTarget ** ppDataTarget) { HandleHolder hDummy; HRESULT hr = E_FAIL; ShimRemoteDataTarget * pRemoteDataTarget = NULL; DbgTransportTarget * pProxy = g_pDbgTransportTarget; DbgTransportSession * pTransport = NULL; hr = pProxy->GetTransportForProcess(pProcessDescriptor, &pTransport, &hDummy); if (FAILED(hr)) { goto Label_Exit; } if (!pTransport->WaitForSessionToOpen(10000)) { hr = CORDBG_E_TIMEOUT; goto Label_Exit; } pRemoteDataTarget = new (nothrow) ShimRemoteDataTarget(pProcessDescriptor->m_Pid, pProxy, pTransport); if (pRemoteDataTarget == NULL) { hr = E_OUTOFMEMORY; goto Label_Exit; } _ASSERTE(SUCCEEDED(hr)); *ppDataTarget = pRemoteDataTarget; pRemoteDataTarget->AddRef(); // must addref out-parameters Label_Exit: if (FAILED(hr)) { if (pRemoteDataTarget != NULL) { // The ShimRemoteDataTarget has ownership of the proxy and the transport, // so we don't need to clean them up here. delete pRemoteDataTarget; } else { if (pTransport != NULL) { pProxy->ReleaseTransport(pTransport); } } } return hr; } // impl of interface method ICorDebugDataTarget::GetPlatform HRESULT STDMETHODCALLTYPE ShimRemoteDataTarget::GetPlatform( CorDebugPlatform *pPlatform) { #ifdef TARGET_UNIX #if defined(TARGET_X86) *pPlatform = CORDB_PLATFORM_POSIX_X86; #elif defined(TARGET_AMD64) *pPlatform = CORDB_PLATFORM_POSIX_AMD64; #elif defined(TARGET_ARM) *pPlatform = CORDB_PLATFORM_POSIX_ARM; #elif defined(TARGET_ARM64) *pPlatform = CORDB_PLATFORM_POSIX_ARM64; #else #error Unknown Processor. #endif #else #if defined(TARGET_X86) *pPlatform = CORDB_PLATFORM_WINDOWS_X86; #elif defined(TARGET_AMD64) *pPlatform = CORDB_PLATFORM_WINDOWS_AMD64; #elif defined(TARGET_ARM) *pPlatform = CORDB_PLATFORM_WINDOWS_ARM; #elif defined(TARGET_ARM64) *pPlatform = CORDB_PLATFORM_WINDOWS_ARM64; #else #error Unknown Processor. #endif #endif return S_OK; } // impl of interface method ICorDebugDataTarget::ReadVirtual HRESULT STDMETHODCALLTYPE ShimRemoteDataTarget::ReadVirtual( CORDB_ADDRESS address, PBYTE pBuffer, ULONG32 cbRequestSize, ULONG32 *pcbRead) { ReturnFailureIfStateNotOk(); size_t read = cbRequestSize; HRESULT hr = S_OK; #ifdef FEATURE_REMOTE_PROC_MEM if (m_memoryHandle != UINT32_MAX) { if (!PAL_ReadProcessMemory(m_memoryHandle, (ULONG64)address, pBuffer, cbRequestSize, &read)) { hr = E_FAIL; } } else #endif { hr = m_pTransport->ReadMemory(reinterpret_cast<BYTE *>(CORDB_ADDRESS_TO_PTR(address)), pBuffer, cbRequestSize); } if (pcbRead != NULL) { *pcbRead = ULONG32(SUCCEEDED(hr) ? read : 0); } return hr; } // impl of interface method ICorDebugMutableDataTarget::WriteVirtual HRESULT STDMETHODCALLTYPE ShimRemoteDataTarget::WriteVirtual( CORDB_ADDRESS pAddress, const BYTE * pBuffer, ULONG32 cbRequestSize) { ReturnFailureIfStateNotOk(); HRESULT hr = E_FAIL; hr = m_pTransport->WriteMemory(reinterpret_cast<BYTE *>(CORDB_ADDRESS_TO_PTR(pAddress)), const_cast<BYTE *>(pBuffer), cbRequestSize); return hr; } // impl of interface method ICorDebugMutableDataTarget::GetThreadContext HRESULT STDMETHODCALLTYPE ShimRemoteDataTarget::GetThreadContext( DWORD dwThreadID, ULONG32 contextFlags, ULONG32 contextSize, BYTE * pContext) { ReturnFailureIfStateNotOk(); // GetThreadContext() is currently not implemented in ShimRemoteDataTarget, which is used with our pipe transport // (FEATURE_DBGIPC_TRANSPORT_DI). Pipe transport is used on POSIX system, but occasionally we can turn it on for Windows for testing, // and then we'd like to have same behavior as on POSIX system (zero context). // // We don't have a good way to implement GetThreadContext() in ShimRemoteDataTarget yet, because we have no way to convert a thread ID to a // thread handle. The function to do the conversion is OpenThread(), which is not implemented in PAL. Even if we had a handle, PAL implementation // of GetThreadContext() is very limited and doesn't work when we're not attached with ptrace. // Instead, we just zero out the seed CONTEXT for the stackwalk. This tells the stackwalker to // start the stackwalk with the first explicit frame. This won't work when we do native debugging, // but that won't happen on the POSIX systems since they don't support native debugging. ZeroMemory(pContext, contextSize); return E_NOTIMPL; } // impl of interface method ICorDebugMutableDataTarget::SetThreadContext HRESULT STDMETHODCALLTYPE ShimRemoteDataTarget::SetThreadContext( DWORD dwThreadID, ULONG32 contextSize, const BYTE * pContext) { ReturnFailureIfStateNotOk(); // ICorDebugDataTarget::GetThreadContext() and ICorDebugDataTarget::SetThreadContext() are currently only // required for interop-debugging and inspection of floating point registers, both of which are not // implemented on Mac. _ASSERTE(!"The remote data target doesn't know how to set a thread's CONTEXT."); return E_NOTIMPL; } // Public implementation of ICorDebugMutableDataTarget::ContinueStatusChanged HRESULT STDMETHODCALLTYPE ShimRemoteDataTarget::ContinueStatusChanged( DWORD dwThreadId, CORDB_CONTINUE_STATUS dwContinueStatus) { ReturnFailureIfStateNotOk(); _ASSERTE(!"ShimRemoteDataTarget::ContinueStatusChanged() is called unexpectedly"); if (m_fpContinueStatusChanged != NULL) { return m_fpContinueStatusChanged(m_pContinueStatusChangedUserData, dwThreadId, dwContinueStatus); } return E_NOTIMPL; } //--------------------------------------------------------------------------------------- // // Unwind the stack to the next frame. // // Return Value: // context filled in with the next frame // HRESULT STDMETHODCALLTYPE ShimRemoteDataTarget::VirtualUnwind(DWORD threadId, ULONG32 contextSize, PBYTE context) { return m_pTransport->VirtualUnwind(threadId, contextSize, context); }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/pal/tests/palsuite/c_runtime/_snwprintf_s/test3/test3.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================================ ** ** Source: test3.c ** ** Purpose: Tests swprintf_s with wide strings ** ** **==========================================================================*/ #include <palsuite.h> #include "../_snwprintf_s.h" /* memcmp is used to verify the results, so this test is dependent on it. */ /* ditto with wcslen */ PALTEST(c_runtime__snwprintf_s_test3_paltest_snwprintf_test3, "c_runtime/_snwprintf_s/test3/paltest_snwprintf_test3") { if (PAL_Initialize(argc, argv) != 0) { return FAIL; } DoStrTest(convert("foo %S"), "bar", convert("foo bar")); DoStrTest(convert("foo %hS"), "bar", convert("foo bar")); DoWStrTest(convert("foo %lS"), convert("bar"), convert("foo bar")); DoWStrTest(convert("foo %wS"), convert("bar"), convert("foo bar")); DoStrTest(convert("foo %LS"), "bar", convert("foo bar")); DoStrTest(convert("foo %I64S"), "bar", convert("foo bar")); DoStrTest(convert("foo %5S"), "bar", convert("foo bar")); DoStrTest(convert("foo %.2S"), "bar", convert("foo ba")); DoStrTest(convert("foo %5.2S"), "bar", convert("foo ba")); DoStrTest(convert("foo %-5S"), "bar", convert("foo bar ")); DoStrTest(convert("foo %05S"), "bar", convert("foo 00bar")); DoStrTest(convert("foo %S"), NULL, convert("foo (null)")); DoStrTest(convert("foo %hS"), NULL, convert("foo (null)")); DoWStrTest(convert("foo %lS"), NULL, convert("foo (null)")); DoWStrTest(convert("foo %wS"), NULL, convert("foo (null)")); DoStrTest(convert("foo %LS"), NULL, convert("foo (null)")); DoStrTest(convert("foo %I64S"), NULL, convert("foo (null)")); 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: test3.c ** ** Purpose: Tests swprintf_s with wide strings ** ** **==========================================================================*/ #include <palsuite.h> #include "../_snwprintf_s.h" /* memcmp is used to verify the results, so this test is dependent on it. */ /* ditto with wcslen */ PALTEST(c_runtime__snwprintf_s_test3_paltest_snwprintf_test3, "c_runtime/_snwprintf_s/test3/paltest_snwprintf_test3") { if (PAL_Initialize(argc, argv) != 0) { return FAIL; } DoStrTest(convert("foo %S"), "bar", convert("foo bar")); DoStrTest(convert("foo %hS"), "bar", convert("foo bar")); DoWStrTest(convert("foo %lS"), convert("bar"), convert("foo bar")); DoWStrTest(convert("foo %wS"), convert("bar"), convert("foo bar")); DoStrTest(convert("foo %LS"), "bar", convert("foo bar")); DoStrTest(convert("foo %I64S"), "bar", convert("foo bar")); DoStrTest(convert("foo %5S"), "bar", convert("foo bar")); DoStrTest(convert("foo %.2S"), "bar", convert("foo ba")); DoStrTest(convert("foo %5.2S"), "bar", convert("foo ba")); DoStrTest(convert("foo %-5S"), "bar", convert("foo bar ")); DoStrTest(convert("foo %05S"), "bar", convert("foo 00bar")); DoStrTest(convert("foo %S"), NULL, convert("foo (null)")); DoStrTest(convert("foo %hS"), NULL, convert("foo (null)")); DoWStrTest(convert("foo %lS"), NULL, convert("foo (null)")); DoWStrTest(convert("foo %wS"), NULL, convert("foo (null)")); DoStrTest(convert("foo %LS"), NULL, convert("foo (null)")); DoStrTest(convert("foo %I64S"), NULL, convert("foo (null)")); PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/pal/src/exception/signal.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*++ Module Name: exception/signal.cpp Abstract: Signal handler implementation (map signals to exceptions) --*/ #include "pal/dbgmsg.h" SET_DEFAULT_DEBUG_CHANNEL(EXCEPT); // some headers have code with asserts, so do this first #include "pal/corunix.hpp" #include "pal/handleapi.hpp" #include "pal/process.h" #include "pal/thread.hpp" #include "pal/threadinfo.hpp" #include "pal/threadsusp.hpp" #include "pal/seh.hpp" #include "pal/signal.hpp" #include "pal/palinternal.h" #include <clrconfignocache.h> #include <errno.h> #include <signal.h> #if !HAVE_MACH_EXCEPTIONS #include "pal/init.h" #include "pal/debug.h" #include "pal/virtual.h" #include "pal/utils.h" #include <string.h> #include <sys/ucontext.h> #include <sys/utsname.h> #include <unistd.h> #include <sys/mman.h> #endif // !HAVE_MACH_EXCEPTIONS #include "pal/context.h" #ifdef SIGRTMIN #define INJECT_ACTIVATION_SIGNAL SIGRTMIN #else #define INJECT_ACTIVATION_SIGNAL SIGUSR1 #endif #if !defined(INJECT_ACTIVATION_SIGNAL) && defined(FEATURE_HIJACK) #error FEATURE_HIJACK requires INJECT_ACTIVATION_SIGNAL to be defined #endif using namespace CorUnix; /* local type definitions *****************************************************/ typedef void (*SIGFUNC)(int, siginfo_t *, void *); /* internal function declarations *********************************************/ static void sigterm_handler(int code, siginfo_t *siginfo, void *context); #ifdef INJECT_ACTIVATION_SIGNAL static void inject_activation_handler(int code, siginfo_t *siginfo, void *context); #endif static void sigill_handler(int code, siginfo_t *siginfo, void *context); static void sigfpe_handler(int code, siginfo_t *siginfo, void *context); static void sigsegv_handler(int code, siginfo_t *siginfo, void *context); static void sigtrap_handler(int code, siginfo_t *siginfo, void *context); static void sigbus_handler(int code, siginfo_t *siginfo, void *context); static void sigint_handler(int code, siginfo_t *siginfo, void *context); static void sigquit_handler(int code, siginfo_t *siginfo, void *context); static void sigabrt_handler(int code, siginfo_t *siginfo, void *context); static bool common_signal_handler(int code, siginfo_t *siginfo, void *sigcontext, int numParams, ...); static void handle_signal(int signal_id, SIGFUNC sigfunc, struct sigaction *previousAction, int additionalFlags = 0, bool skipIgnored = false); static void restore_signal(int signal_id, struct sigaction *previousAction); static void restore_signal_and_resend(int code, struct sigaction* action); /* internal data declarations *********************************************/ bool g_registered_signal_handlers = false; #if !HAVE_MACH_EXCEPTIONS bool g_enable_alternate_stack_check = false; #endif // !HAVE_MACH_EXCEPTIONS static bool g_registered_sigterm_handler = false; static bool g_registered_activation_handler = false; struct sigaction g_previous_sigterm; #ifdef INJECT_ACTIVATION_SIGNAL struct sigaction g_previous_activation; #endif struct sigaction g_previous_sigill; struct sigaction g_previous_sigtrap; struct sigaction g_previous_sigfpe; struct sigaction g_previous_sigbus; struct sigaction g_previous_sigsegv; struct sigaction g_previous_sigint; struct sigaction g_previous_sigquit; struct sigaction g_previous_sigabrt; #if !HAVE_MACH_EXCEPTIONS // TOP of special stack for handling stack overflow volatile void* g_stackOverflowHandlerStack = NULL; // Flag that is or-ed with SIGSEGV to indicate that the SIGSEGV was a stack overflow const int StackOverflowFlag = 0x40000000; #endif // !HAVE_MACH_EXCEPTIONS /* public function definitions ************************************************/ /*++ Function : SEHInitializeSignals Set up signal handlers to catch signals and translate them to exceptions Parameters : None Return : TRUE in case of a success, FALSE otherwise --*/ BOOL SEHInitializeSignals(CorUnix::CPalThread *pthrCurrent, DWORD flags) { TRACE("Initializing signal handlers %04x\n", flags); #if !HAVE_MACH_EXCEPTIONS g_enable_alternate_stack_check = false; CLRConfigNoCache stackCheck = CLRConfigNoCache::Get("EnableAlternateStackCheck", /*noprefix*/ false, &getenv); if (stackCheck.IsSet()) { DWORD value; if (stackCheck.TryAsInteger(10, value)) g_enable_alternate_stack_check = (value != 0); } #endif if (flags & PAL_INITIALIZE_REGISTER_SIGNALS) { g_registered_signal_handlers = true; /* we call handle_signal for every possible signal, even if we don't provide a signal handler. handle_signal will set SA_RESTART flag for specified signal. Therefore, all signals will have SA_RESTART flag set, preventing slow Unix system calls from being interrupted. On systems without siginfo_t, SIGKILL and SIGSTOP can't be restarted, so we don't handle those signals. Both the Darwin and FreeBSD man pages say that SIGKILL and SIGSTOP can't be handled, but FreeBSD allows us to register a handler for them anyway. We don't do that. see sigaction man page for more details */ handle_signal(SIGILL, sigill_handler, &g_previous_sigill); handle_signal(SIGFPE, sigfpe_handler, &g_previous_sigfpe); handle_signal(SIGBUS, sigbus_handler, &g_previous_sigbus); handle_signal(SIGABRT, sigabrt_handler, &g_previous_sigabrt); // We don't setup a handler for SIGINT/SIGQUIT when those signals are ignored. // Otherwise our child processes would reset to the default on exec causing them // to terminate on these signals. handle_signal(SIGINT, sigint_handler, &g_previous_sigint, 0 /* additionalFlags */, true /* skipIgnored */); handle_signal(SIGQUIT, sigquit_handler, &g_previous_sigquit, 0 /* additionalFlags */, true /* skipIgnored */); #if HAVE_MACH_EXCEPTIONS handle_signal(SIGSEGV, sigsegv_handler, &g_previous_sigsegv); #else handle_signal(SIGTRAP, sigtrap_handler, &g_previous_sigtrap); // SIGSEGV handler runs on a separate stack so that we can handle stack overflow handle_signal(SIGSEGV, sigsegv_handler, &g_previous_sigsegv, SA_ONSTACK); if (!pthrCurrent->EnsureSignalAlternateStack()) { return FALSE; } // Allocate the minimal stack necessary for handling stack overflow int stackOverflowStackSize = ALIGN_UP(sizeof(SignalHandlerWorkerReturnPoint), 16) + 7 * 4096; // Align the size to virtual page size and add one virtual page as a stack guard stackOverflowStackSize = ALIGN_UP(stackOverflowStackSize, GetVirtualPageSize()) + GetVirtualPageSize(); int flags = MAP_ANONYMOUS | MAP_PRIVATE; #ifdef MAP_STACK flags |= MAP_STACK; #endif g_stackOverflowHandlerStack = mmap(NULL, stackOverflowStackSize, PROT_READ | PROT_WRITE, flags, -1, 0); if (g_stackOverflowHandlerStack == MAP_FAILED) { return FALSE; } // create a guard page for the alternate stack int st = mprotect((void*)g_stackOverflowHandlerStack, GetVirtualPageSize(), PROT_NONE); if (st != 0) { munmap((void*)g_stackOverflowHandlerStack, stackOverflowStackSize); return FALSE; } g_stackOverflowHandlerStack = (void*)((size_t)g_stackOverflowHandlerStack + stackOverflowStackSize); #endif // HAVE_MACH_EXCEPTIONS } /* The default action for SIGPIPE is process termination. Since SIGPIPE can be signaled when trying to write on a socket for which the connection has been dropped, we need to tell the system we want to ignore this signal. Instead of terminating the process, the system call which would had issued a SIGPIPE will, instead, report an error and set errno to EPIPE. */ signal(SIGPIPE, SIG_IGN); if (flags & PAL_INITIALIZE_REGISTER_SIGTERM_HANDLER) { g_registered_sigterm_handler = true; handle_signal(SIGTERM, sigterm_handler, &g_previous_sigterm); } #ifdef INJECT_ACTIVATION_SIGNAL if (flags & PAL_INITIALIZE_REGISTER_ACTIVATION_SIGNAL) { handle_signal(INJECT_ACTIVATION_SIGNAL, inject_activation_handler, &g_previous_activation); g_registered_activation_handler = true; } #endif return TRUE; } /*++ Function : SEHCleanupSignals Restore default signal handlers Parameters : None (no return value) note : reason for this function is that during PAL_Terminate, we reach a point where SEH isn't possible anymore (handle manager is off, etc). Past that point, we can't avoid crashing on a signal. --*/ void SEHCleanupSignals() { TRACE("Restoring default signal handlers\n"); if (g_registered_signal_handlers) { restore_signal(SIGILL, &g_previous_sigill); #if !HAVE_MACH_EXCEPTIONS restore_signal(SIGTRAP, &g_previous_sigtrap); #endif restore_signal(SIGFPE, &g_previous_sigfpe); restore_signal(SIGBUS, &g_previous_sigbus); restore_signal(SIGABRT, &g_previous_sigabrt); restore_signal(SIGSEGV, &g_previous_sigsegv); restore_signal(SIGINT, &g_previous_sigint); restore_signal(SIGQUIT, &g_previous_sigquit); } #ifdef INJECT_ACTIVATION_SIGNAL if (g_registered_activation_handler) { restore_signal(INJECT_ACTIVATION_SIGNAL, &g_previous_activation); } #endif if (g_registered_sigterm_handler) { restore_signal(SIGTERM, &g_previous_sigterm); } } /*++ Function : SEHCleanupAbort() Restore default SIGABORT signal handlers (no parameters, no return value) --*/ void SEHCleanupAbort() { if (g_registered_signal_handlers) { restore_signal(SIGABRT, &g_previous_sigabrt); } } /* internal function definitions **********************************************/ /*++ Function : IsRunningOnAlternateStack Detects if the current signal handlers is running on an alternate stack Parameters : The context of the signal Return : true if we are running on an alternate stack --*/ bool IsRunningOnAlternateStack(void *context) { #if HAVE_MACH_EXCEPTIONS return false; #else bool isRunningOnAlternateStack; if (g_enable_alternate_stack_check) { // Note: WSL doesn't return the alternate signal ranges in the uc_stack (the whole structure is zeroed no // matter whether the code is running on an alternate stack or not). So the check would always fail on WSL. stack_t *signalStack = &((native_context_t *)context)->uc_stack; // Check if the signalStack local variable address is within the alternate stack range. If it is not, // then either the alternate stack was not installed at all or the current method is not running on it. void* alternateStackEnd = (char *)signalStack->ss_sp + signalStack->ss_size; isRunningOnAlternateStack = ((signalStack->ss_flags & SS_DISABLE) == 0) && (signalStack->ss_sp <= &signalStack) && (&signalStack < alternateStackEnd); } else { // If alternate stack check is disabled, consider always that we are running on an alternate // signal handler stack. isRunningOnAlternateStack = true; } return isRunningOnAlternateStack; #endif // HAVE_MACH_EXCEPTIONS } static bool IsSaSigInfo(struct sigaction* action) { return (action->sa_flags & SA_SIGINFO) != 0; } static bool IsSigDfl(struct sigaction* action) { // macOS can return sigaction with SIG_DFL and SA_SIGINFO. // SA_SIGINFO means we should use sa_sigaction, but here we want to check sa_handler. // So we ignore SA_SIGINFO when sa_sigaction and sa_handler are at the same address. return (&action->sa_handler == (void*)&action->sa_sigaction || !IsSaSigInfo(action)) && action->sa_handler == SIG_DFL; } static bool IsSigIgn(struct sigaction* action) { return (&action->sa_handler == (void*)&action->sa_sigaction || !IsSaSigInfo(action)) && action->sa_handler == SIG_IGN; } /*++ Function : invoke_previous_action synchronously invokes the previous action or aborts when that is not possible Parameters : action : previous sigaction struct code : signal code siginfo : signal siginfo context : signal context signalRestarts: BOOL state : TRUE if the process will be signalled again (no return value) --*/ static void invoke_previous_action(struct sigaction* action, int code, siginfo_t *siginfo, void *context, bool signalRestarts = true) { _ASSERTE(action != NULL); if (IsSigIgn(action)) { if (signalRestarts) { // This signal mustn't be ignored because it will be restarted. PROCAbort(code); } return; } else if (IsSigDfl(action)) { if (signalRestarts) { // Restore the original and restart h/w exception. restore_signal(code, action); } else { // We can't invoke the original handler because returning from the // handler doesn't restart the exception. PROCAbort(code); } } else if (IsSaSigInfo(action)) { // Directly call the previous handler. _ASSERTE(action->sa_sigaction != NULL); action->sa_sigaction(code, siginfo, context); } else { // Directly call the previous handler. _ASSERTE(action->sa_handler != NULL); action->sa_handler(code); } PROCNotifyProcessShutdown(IsRunningOnAlternateStack(context)); PROCCreateCrashDumpIfEnabled(code); } /*++ Function : sigill_handler handle SIGILL signal (EXCEPTION_ILLEGAL_INSTRUCTION, others?) Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigill_handler(int code, siginfo_t *siginfo, void *context) { if (PALIsInitialized()) { if (common_signal_handler(code, siginfo, context, 0)) { return; } } invoke_previous_action(&g_previous_sigill, code, siginfo, context); } /*++ Function : sigfpe_handler handle SIGFPE signal (division by zero, floating point exception) Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigfpe_handler(int code, siginfo_t *siginfo, void *context) { if (PALIsInitialized()) { if (common_signal_handler(code, siginfo, context, 0)) { return; } } invoke_previous_action(&g_previous_sigfpe, code, siginfo, context); } #if !HAVE_MACH_EXCEPTIONS /*++ Function : signal_handler_worker Handles signal on the original stack where the signal occured. Invoked via setcontext. Parameters : POSIX signal handler parameter list ("man sigaction" for details) returnPoint - context to which the function returns if the common_signal_handler returns (no return value) --*/ extern "C" void signal_handler_worker(int code, siginfo_t *siginfo, void *context, SignalHandlerWorkerReturnPoint* returnPoint) { // TODO: First variable parameter says whether a read (0) or write (non-0) caused the // fault. We must disassemble the instruction at record.ExceptionAddress // to correctly fill in this value. // Unmask the activation signal now that we are running on the original stack of the thread sigset_t signal_set; sigemptyset(&signal_set); sigaddset(&signal_set, INJECT_ACTIVATION_SIGNAL); int sigmaskRet = pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL); if (sigmaskRet != 0) { ASSERT("pthread_sigmask failed; error number is %d\n", sigmaskRet); } returnPoint->returnFromHandler = common_signal_handler(code, siginfo, context, 2, (size_t)0, (size_t)siginfo->si_addr); // We are going to return to the alternate stack, so block the activation signal again sigmaskRet = pthread_sigmask(SIG_BLOCK, &signal_set, NULL); if (sigmaskRet != 0) { ASSERT("pthread_sigmask failed; error number is %d\n", sigmaskRet); } RtlRestoreContext(&returnPoint->context, NULL); } /*++ Function : SwitchStackAndExecuteHandler Switch to the stack specified by the sp argument Parameters : POSIX signal handler parameter list ("man sigaction" for details) sp - stack pointer of the stack to execute the handler on. If sp == 0, execute it on the original stack where the signal has occured. Return : The return value from the signal handler --*/ static bool SwitchStackAndExecuteHandler(int code, siginfo_t *siginfo, void *context, size_t sp) { // Establish a return point in case the common_signal_handler returns volatile bool contextInitialization = true; void *ptr = alloca(sizeof(SignalHandlerWorkerReturnPoint) + alignof(SignalHandlerWorkerReturnPoint) - 1); SignalHandlerWorkerReturnPoint *pReturnPoint = (SignalHandlerWorkerReturnPoint *)ALIGN_UP(ptr, alignof(SignalHandlerWorkerReturnPoint)); RtlCaptureContext(&pReturnPoint->context); // When the signal handler worker completes, it uses setcontext to return to this point if (contextInitialization) { contextInitialization = false; ExecuteHandlerOnCustomStack(code, siginfo, context, sp, pReturnPoint); _ASSERTE(FALSE); // The ExecuteHandlerOnCustomStack should never return } return pReturnPoint->returnFromHandler; } #endif // !HAVE_MACH_EXCEPTIONS /*++ Function : sigsegv_handler handle SIGSEGV signal (EXCEPTION_ACCESS_VIOLATION, others) Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigsegv_handler(int code, siginfo_t *siginfo, void *context) { #if !HAVE_MACH_EXCEPTIONS if (PALIsInitialized()) { // First check if we have a stack overflow size_t sp = (size_t)GetNativeContextSP((native_context_t *)context); size_t failureAddress = (size_t)siginfo->si_addr; // If the failure address is at most one page above or below the stack pointer, // we have a stack overflow. if ((failureAddress - (sp - GetVirtualPageSize())) < 2 * GetVirtualPageSize()) { if (GetCurrentPalThread()) { size_t handlerStackTop = __sync_val_compare_and_swap((size_t*)&g_stackOverflowHandlerStack, (size_t)g_stackOverflowHandlerStack, 0); if (handlerStackTop == 0) { // We have only one stack for handling stack overflow preallocated. We let only the first thread that hits stack overflow to // run the exception handling code on that stack (which ends up just dumping the stack trace and aborting the process). // Other threads are held spinning and sleeping here until the process exits. while (true) { sleep(1); } } if (SwitchStackAndExecuteHandler(code | StackOverflowFlag, siginfo, context, (size_t)handlerStackTop)) { PROCAbort(SIGSEGV); } } else { (void)!write(STDERR_FILENO, StackOverflowMessage, sizeof(StackOverflowMessage) - 1); PROCAbort(SIGSEGV); } } // Now that we know the SIGSEGV didn't happen due to a stack overflow, execute the common // hardware signal handler on the original stack. if (GetCurrentPalThread() && IsRunningOnAlternateStack(context)) { if (SwitchStackAndExecuteHandler(code, siginfo, context, 0 /* sp */)) // sp == 0 indicates execution on the original stack { return; } } else { // The code flow gets here when the signal handler is not running on an alternate stack or when it wasn't created // by coreclr. In both cases, we execute the common_signal_handler directly. // If thread isn't created by coreclr and has alternate signal stack GetCurrentPalThread() will return NULL too. // But since in this case we don't handle hardware exceptions (IsSafeToHandleHardwareException returns false) // we can call common_signal_handler on the alternate stack. if (common_signal_handler(code, siginfo, context, 2, (size_t)0, (size_t)siginfo->si_addr)) { return; } } } #endif // !HAVE_MACH_EXCEPTIONS invoke_previous_action(&g_previous_sigsegv, code, siginfo, context); } /*++ Function : sigtrap_handler handle SIGTRAP signal (EXCEPTION_SINGLE_STEP, EXCEPTION_BREAKPOINT) Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigtrap_handler(int code, siginfo_t *siginfo, void *context) { if (PALIsInitialized()) { if (common_signal_handler(code, siginfo, context, 0)) { return; } } // The signal doesn't restart, returning from a SIGTRAP handler continues execution past the trap. invoke_previous_action(&g_previous_sigtrap, code, siginfo, context, /* signalRestarts */ false); } /*++ Function : sigbus_handler handle SIGBUS signal (EXCEPTION_ACCESS_VIOLATION?) Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigbus_handler(int code, siginfo_t *siginfo, void *context) { if (PALIsInitialized()) { // TODO: First variable parameter says whether a read (0) or write (non-0) caused the // fault. We must disassemble the instruction at record.ExceptionAddress // to correctly fill in this value. if (common_signal_handler(code, siginfo, context, 2, (size_t)0, (size_t)siginfo->si_addr)) { return; } } invoke_previous_action(&g_previous_sigbus, code, siginfo, context); } /*++ Function : sigabrt_handler handle SIGABRT signal - abort() API Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigabrt_handler(int code, siginfo_t *siginfo, void *context) { invoke_previous_action(&g_previous_sigabrt, code, siginfo, context); } /*++ Function : sigint_handler handle SIGINT signal Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigint_handler(int code, siginfo_t *siginfo, void *context) { PROCNotifyProcessShutdown(); restore_signal_and_resend(code, &g_previous_sigint); } /*++ Function : sigquit_handler handle SIGQUIT signal Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigquit_handler(int code, siginfo_t *siginfo, void *context) { PROCNotifyProcessShutdown(); restore_signal_and_resend(code, &g_previous_sigquit); } /*++ Function : sigterm_handler handle SIGTERM signal Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigterm_handler(int code, siginfo_t *siginfo, void *context) { if (PALIsInitialized()) { // g_pSynchronizationManager shouldn't be null if PAL is initialized. _ASSERTE(g_pSynchronizationManager != nullptr); g_pSynchronizationManager->SendTerminationRequestToWorkerThread(); } else { restore_signal_and_resend(SIGTERM, &g_previous_sigterm); } } #ifdef INJECT_ACTIVATION_SIGNAL /*++ Function : inject_activation_handler Handle the INJECT_ACTIVATION_SIGNAL signal. This signal interrupts a running thread so it can call the activation function that was specified when sending the signal. Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void inject_activation_handler(int code, siginfo_t *siginfo, void *context) { // Only accept activations from the current process if (g_activationFunction != NULL && (siginfo->si_pid == getpid() #ifdef HOST_OSX // On OSX si_pid is sometimes 0. It was confirmed by Apple to be expected, as the si_pid is tracked at the process level. So when multiple // signals are in flight in the same process at the same time, it may be overwritten / zeroed. || siginfo->si_pid == 0 #endif )) { _ASSERTE(g_safeActivationCheckFunction != NULL); native_context_t *ucontext = (native_context_t *)context; CONTEXT winContext; CONTEXTFromNativeContext( ucontext, &winContext, CONTEXT_CONTROL | CONTEXT_INTEGER); if (g_safeActivationCheckFunction(CONTEXTGetPC(&winContext), /* checkingCurrentThread */ TRUE)) { int savedErrNo = errno; // Make sure that errno is not modified g_activationFunction(&winContext); errno = savedErrNo; // Activation function may have modified the context, so update it. CONTEXTToNativeContext(&winContext, ucontext); } } else { // Call the original handler when it is not ignored or default (terminate). if (g_previous_activation.sa_flags & SA_SIGINFO) { _ASSERTE(g_previous_activation.sa_sigaction != NULL); g_previous_activation.sa_sigaction(code, siginfo, context); } else { if (g_previous_activation.sa_handler != SIG_IGN && g_previous_activation.sa_handler != SIG_DFL) { _ASSERTE(g_previous_activation.sa_handler != NULL); g_previous_activation.sa_handler(code); } } } } #endif /*++ Function : InjectActivationInternal Interrupt the specified thread and have it call the activationFunction passed in Parameters : pThread - target PAL thread activationFunction - function to call (no return value) --*/ PAL_ERROR InjectActivationInternal(CorUnix::CPalThread* pThread) { #ifdef INJECT_ACTIVATION_SIGNAL int status = pthread_kill(pThread->GetPThreadSelf(), INJECT_ACTIVATION_SIGNAL); // We can get EAGAIN when printing stack overflow stack trace and when other threads hit // stack overflow too. Those are held in the sigsegv_handler with blocked signals until // the process exits. #ifdef __APPLE__ // On Apple, pthread_kill is not allowed to be sent to dispatch queue threads if (status == ENOTSUP) { return ERROR_NOT_SUPPORTED; } #endif if ((status != 0) && (status != EAGAIN)) { // Failure to send the signal is fatal. There are only two cases when sending // the signal can fail. First, if the signal ID is invalid and second, // if the thread doesn't exist anymore. PROCAbort(); } return NO_ERROR; #else return ERROR_CANCELLED; #endif } #if !HAVE_MACH_EXCEPTIONS /*++ Function : signal_ignore_handler Simple signal handler which does nothing Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void signal_ignore_handler(int code, siginfo_t *siginfo, void *context) { } #endif // !HAVE_MACH_EXCEPTIONS void PAL_IgnoreProfileSignal(int signalNum) { #if !HAVE_MACH_EXCEPTIONS // Add a signal handler which will ignore signals // This will allow signal to be used as a marker in perf recording. // This will be used as an aid to synchronize recorded profile with // test cases // // signal(signalNum, SGN_IGN) can not be used here. It will ignore // the signal in kernel space and therefore generate no recordable // event for profiling. Preventing it being used for profile // synchronization // // Since this is only used in rare circumstances no attempt to // restore the old handler will be made handle_signal(signalNum, signal_ignore_handler, 0); #endif } /*++ Function : common_signal_handler common code for all signal handlers Parameters : int code : signal received siginfo_t *siginfo : siginfo passed to the signal handler void *context : context structure passed to the signal handler int numParams : number of variable parameters of the exception ... : variable parameters of the exception (each of size_t type) Returns true if the execution should continue or false if the exception was unhandled Note: the "pointers" parameter should contain a valid exception record pointer, but the ContextRecord pointer will be overwritten. --*/ __attribute__((noinline)) static bool common_signal_handler(int code, siginfo_t *siginfo, void *sigcontext, int numParams, ...) { #if !HAVE_MACH_EXCEPTIONS sigset_t signal_set; CONTEXT signalContextRecord; CONTEXT* signalContextRecordPtr = &signalContextRecord; EXCEPTION_RECORD exceptionRecord; native_context_t *ucontext; ucontext = (native_context_t *)sigcontext; g_hardware_exception_context_locvar_offset = (int)((char*)&signalContextRecordPtr - (char*)__builtin_frame_address(0)); if (code == (SIGSEGV | StackOverflowFlag)) { exceptionRecord.ExceptionCode = EXCEPTION_STACK_OVERFLOW; code &= ~StackOverflowFlag; } else { exceptionRecord.ExceptionCode = CONTEXTGetExceptionCodeForSignal(siginfo, ucontext); } exceptionRecord.ExceptionFlags = EXCEPTION_IS_SIGNAL; exceptionRecord.ExceptionRecord = NULL; exceptionRecord.ExceptionAddress = GetNativeContextPC(ucontext); exceptionRecord.NumberParameters = numParams; va_list params; va_start(params, numParams); for (int i = 0; i < numParams; i++) { exceptionRecord.ExceptionInformation[i] = va_arg(params, size_t); } // Pre-populate context with data from current frame, because ucontext doesn't have some data (e.g. SS register) // which is required for restoring context RtlCaptureContext(&signalContextRecord); ULONG contextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_FLOATING_POINT; #if defined(HOST_AMD64) contextFlags |= CONTEXT_XSTATE; #endif // Fill context record with required information. from pal.h: // On non-Win32 platforms, the CONTEXT pointer in the // PEXCEPTION_POINTERS will contain at least the CONTEXT_CONTROL registers. CONTEXTFromNativeContext(ucontext, &signalContextRecord, contextFlags); /* Unmask signal so we can receive it again */ sigemptyset(&signal_set); sigaddset(&signal_set, code); int sigmaskRet = pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL); if (sigmaskRet != 0) { ASSERT("pthread_sigmask failed; error number is %d\n", sigmaskRet); } signalContextRecord.ContextFlags |= CONTEXT_EXCEPTION_ACTIVE; // The exception object takes ownership of the exceptionRecord and contextRecord PAL_SEHException exception(&exceptionRecord, &signalContextRecord, true); if (SEHProcessException(&exception)) { // Exception handling may have modified the context, so update it. CONTEXTToNativeContext(exception.ExceptionPointers.ContextRecord, ucontext); return true; } #endif // !HAVE_MACH_EXCEPTIONS return false; } /*++ Function : handle_signal register handler for specified signal Parameters : int signal_id : signal to handle SIGFUNC sigfunc : signal handler previousAction : previous sigaction struct (no return value) note : if sigfunc is NULL, the default signal handler is restored --*/ void handle_signal(int signal_id, SIGFUNC sigfunc, struct sigaction *previousAction, int additionalFlags, bool skipIgnored) { struct sigaction newAction; newAction.sa_flags = SA_RESTART | additionalFlags; newAction.sa_handler = NULL; newAction.sa_sigaction = sigfunc; newAction.sa_flags |= SA_SIGINFO; sigemptyset(&newAction.sa_mask); #ifdef INJECT_ACTIVATION_SIGNAL if ((additionalFlags & SA_ONSTACK) != 0) { // A handler that runs on a separate stack should not be interrupted by the activation signal // until it switches back to the regular stack, since that signal's handler would run on the // limited separate stack and likely run into a stack overflow. sigaddset(&newAction.sa_mask, INJECT_ACTIVATION_SIGNAL); } #endif if (skipIgnored) { if (-1 == sigaction(signal_id, NULL, previousAction)) { ASSERT("handle_signal: sigaction() call failed with error code %d (%s)\n", errno, strerror(errno)); } else if (previousAction->sa_handler == SIG_IGN) { return; } } if (-1 == sigaction(signal_id, &newAction, previousAction)) { ASSERT("handle_signal: sigaction() call failed with error code %d (%s)\n", errno, strerror(errno)); } } /*++ Function : restore_signal restore handler for specified signal Parameters : int signal_id : signal to handle previousAction : previous sigaction struct to restore (no return value) --*/ void restore_signal(int signal_id, struct sigaction *previousAction) { if (-1 == sigaction(signal_id, previousAction, NULL)) { ASSERT("restore_signal: sigaction() call failed with error code %d (%s)\n", errno, strerror(errno)); } } /*++ Function : restore_signal_and_resend restore handler for specified signal and signal the process Parameters : int signal_id : signal to handle previousAction : previous sigaction struct to restore (no return value) --*/ void restore_signal_and_resend(int signal_id, struct sigaction* previousAction) { restore_signal(signal_id, previousAction); kill(gPID, signal_id); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*++ Module Name: exception/signal.cpp Abstract: Signal handler implementation (map signals to exceptions) --*/ #include "pal/dbgmsg.h" SET_DEFAULT_DEBUG_CHANNEL(EXCEPT); // some headers have code with asserts, so do this first #include "pal/corunix.hpp" #include "pal/handleapi.hpp" #include "pal/process.h" #include "pal/thread.hpp" #include "pal/threadinfo.hpp" #include "pal/threadsusp.hpp" #include "pal/seh.hpp" #include "pal/signal.hpp" #include "pal/palinternal.h" #include <clrconfignocache.h> #include <errno.h> #include <signal.h> #if !HAVE_MACH_EXCEPTIONS #include "pal/init.h" #include "pal/debug.h" #include "pal/virtual.h" #include "pal/utils.h" #include <string.h> #include <sys/ucontext.h> #include <sys/utsname.h> #include <unistd.h> #include <sys/mman.h> #endif // !HAVE_MACH_EXCEPTIONS #include "pal/context.h" #ifdef SIGRTMIN #define INJECT_ACTIVATION_SIGNAL SIGRTMIN #else #define INJECT_ACTIVATION_SIGNAL SIGUSR1 #endif #if !defined(INJECT_ACTIVATION_SIGNAL) && defined(FEATURE_HIJACK) #error FEATURE_HIJACK requires INJECT_ACTIVATION_SIGNAL to be defined #endif using namespace CorUnix; /* local type definitions *****************************************************/ typedef void (*SIGFUNC)(int, siginfo_t *, void *); /* internal function declarations *********************************************/ static void sigterm_handler(int code, siginfo_t *siginfo, void *context); #ifdef INJECT_ACTIVATION_SIGNAL static void inject_activation_handler(int code, siginfo_t *siginfo, void *context); #endif static void sigill_handler(int code, siginfo_t *siginfo, void *context); static void sigfpe_handler(int code, siginfo_t *siginfo, void *context); static void sigsegv_handler(int code, siginfo_t *siginfo, void *context); static void sigtrap_handler(int code, siginfo_t *siginfo, void *context); static void sigbus_handler(int code, siginfo_t *siginfo, void *context); static void sigint_handler(int code, siginfo_t *siginfo, void *context); static void sigquit_handler(int code, siginfo_t *siginfo, void *context); static void sigabrt_handler(int code, siginfo_t *siginfo, void *context); static bool common_signal_handler(int code, siginfo_t *siginfo, void *sigcontext, int numParams, ...); static void handle_signal(int signal_id, SIGFUNC sigfunc, struct sigaction *previousAction, int additionalFlags = 0, bool skipIgnored = false); static void restore_signal(int signal_id, struct sigaction *previousAction); static void restore_signal_and_resend(int code, struct sigaction* action); /* internal data declarations *********************************************/ bool g_registered_signal_handlers = false; #if !HAVE_MACH_EXCEPTIONS bool g_enable_alternate_stack_check = false; #endif // !HAVE_MACH_EXCEPTIONS static bool g_registered_sigterm_handler = false; static bool g_registered_activation_handler = false; struct sigaction g_previous_sigterm; #ifdef INJECT_ACTIVATION_SIGNAL struct sigaction g_previous_activation; #endif struct sigaction g_previous_sigill; struct sigaction g_previous_sigtrap; struct sigaction g_previous_sigfpe; struct sigaction g_previous_sigbus; struct sigaction g_previous_sigsegv; struct sigaction g_previous_sigint; struct sigaction g_previous_sigquit; struct sigaction g_previous_sigabrt; #if !HAVE_MACH_EXCEPTIONS // TOP of special stack for handling stack overflow volatile void* g_stackOverflowHandlerStack = NULL; // Flag that is or-ed with SIGSEGV to indicate that the SIGSEGV was a stack overflow const int StackOverflowFlag = 0x40000000; #endif // !HAVE_MACH_EXCEPTIONS /* public function definitions ************************************************/ /*++ Function : SEHInitializeSignals Set up signal handlers to catch signals and translate them to exceptions Parameters : None Return : TRUE in case of a success, FALSE otherwise --*/ BOOL SEHInitializeSignals(CorUnix::CPalThread *pthrCurrent, DWORD flags) { TRACE("Initializing signal handlers %04x\n", flags); #if !HAVE_MACH_EXCEPTIONS g_enable_alternate_stack_check = false; CLRConfigNoCache stackCheck = CLRConfigNoCache::Get("EnableAlternateStackCheck", /*noprefix*/ false, &getenv); if (stackCheck.IsSet()) { DWORD value; if (stackCheck.TryAsInteger(10, value)) g_enable_alternate_stack_check = (value != 0); } #endif if (flags & PAL_INITIALIZE_REGISTER_SIGNALS) { g_registered_signal_handlers = true; /* we call handle_signal for every possible signal, even if we don't provide a signal handler. handle_signal will set SA_RESTART flag for specified signal. Therefore, all signals will have SA_RESTART flag set, preventing slow Unix system calls from being interrupted. On systems without siginfo_t, SIGKILL and SIGSTOP can't be restarted, so we don't handle those signals. Both the Darwin and FreeBSD man pages say that SIGKILL and SIGSTOP can't be handled, but FreeBSD allows us to register a handler for them anyway. We don't do that. see sigaction man page for more details */ handle_signal(SIGILL, sigill_handler, &g_previous_sigill); handle_signal(SIGFPE, sigfpe_handler, &g_previous_sigfpe); handle_signal(SIGBUS, sigbus_handler, &g_previous_sigbus); handle_signal(SIGABRT, sigabrt_handler, &g_previous_sigabrt); // We don't setup a handler for SIGINT/SIGQUIT when those signals are ignored. // Otherwise our child processes would reset to the default on exec causing them // to terminate on these signals. handle_signal(SIGINT, sigint_handler, &g_previous_sigint, 0 /* additionalFlags */, true /* skipIgnored */); handle_signal(SIGQUIT, sigquit_handler, &g_previous_sigquit, 0 /* additionalFlags */, true /* skipIgnored */); #if HAVE_MACH_EXCEPTIONS handle_signal(SIGSEGV, sigsegv_handler, &g_previous_sigsegv); #else handle_signal(SIGTRAP, sigtrap_handler, &g_previous_sigtrap); // SIGSEGV handler runs on a separate stack so that we can handle stack overflow handle_signal(SIGSEGV, sigsegv_handler, &g_previous_sigsegv, SA_ONSTACK); if (!pthrCurrent->EnsureSignalAlternateStack()) { return FALSE; } // Allocate the minimal stack necessary for handling stack overflow int stackOverflowStackSize = ALIGN_UP(sizeof(SignalHandlerWorkerReturnPoint), 16) + 7 * 4096; // Align the size to virtual page size and add one virtual page as a stack guard stackOverflowStackSize = ALIGN_UP(stackOverflowStackSize, GetVirtualPageSize()) + GetVirtualPageSize(); int flags = MAP_ANONYMOUS | MAP_PRIVATE; #ifdef MAP_STACK flags |= MAP_STACK; #endif g_stackOverflowHandlerStack = mmap(NULL, stackOverflowStackSize, PROT_READ | PROT_WRITE, flags, -1, 0); if (g_stackOverflowHandlerStack == MAP_FAILED) { return FALSE; } // create a guard page for the alternate stack int st = mprotect((void*)g_stackOverflowHandlerStack, GetVirtualPageSize(), PROT_NONE); if (st != 0) { munmap((void*)g_stackOverflowHandlerStack, stackOverflowStackSize); return FALSE; } g_stackOverflowHandlerStack = (void*)((size_t)g_stackOverflowHandlerStack + stackOverflowStackSize); #endif // HAVE_MACH_EXCEPTIONS } /* The default action for SIGPIPE is process termination. Since SIGPIPE can be signaled when trying to write on a socket for which the connection has been dropped, we need to tell the system we want to ignore this signal. Instead of terminating the process, the system call which would had issued a SIGPIPE will, instead, report an error and set errno to EPIPE. */ signal(SIGPIPE, SIG_IGN); if (flags & PAL_INITIALIZE_REGISTER_SIGTERM_HANDLER) { g_registered_sigterm_handler = true; handle_signal(SIGTERM, sigterm_handler, &g_previous_sigterm); } #ifdef INJECT_ACTIVATION_SIGNAL if (flags & PAL_INITIALIZE_REGISTER_ACTIVATION_SIGNAL) { handle_signal(INJECT_ACTIVATION_SIGNAL, inject_activation_handler, &g_previous_activation); g_registered_activation_handler = true; } #endif return TRUE; } /*++ Function : SEHCleanupSignals Restore default signal handlers Parameters : None (no return value) note : reason for this function is that during PAL_Terminate, we reach a point where SEH isn't possible anymore (handle manager is off, etc). Past that point, we can't avoid crashing on a signal. --*/ void SEHCleanupSignals() { TRACE("Restoring default signal handlers\n"); if (g_registered_signal_handlers) { restore_signal(SIGILL, &g_previous_sigill); #if !HAVE_MACH_EXCEPTIONS restore_signal(SIGTRAP, &g_previous_sigtrap); #endif restore_signal(SIGFPE, &g_previous_sigfpe); restore_signal(SIGBUS, &g_previous_sigbus); restore_signal(SIGABRT, &g_previous_sigabrt); restore_signal(SIGSEGV, &g_previous_sigsegv); restore_signal(SIGINT, &g_previous_sigint); restore_signal(SIGQUIT, &g_previous_sigquit); } #ifdef INJECT_ACTIVATION_SIGNAL if (g_registered_activation_handler) { restore_signal(INJECT_ACTIVATION_SIGNAL, &g_previous_activation); } #endif if (g_registered_sigterm_handler) { restore_signal(SIGTERM, &g_previous_sigterm); } } /*++ Function : SEHCleanupAbort() Restore default SIGABORT signal handlers (no parameters, no return value) --*/ void SEHCleanupAbort() { if (g_registered_signal_handlers) { restore_signal(SIGABRT, &g_previous_sigabrt); } } /* internal function definitions **********************************************/ /*++ Function : IsRunningOnAlternateStack Detects if the current signal handlers is running on an alternate stack Parameters : The context of the signal Return : true if we are running on an alternate stack --*/ bool IsRunningOnAlternateStack(void *context) { #if HAVE_MACH_EXCEPTIONS return false; #else bool isRunningOnAlternateStack; if (g_enable_alternate_stack_check) { // Note: WSL doesn't return the alternate signal ranges in the uc_stack (the whole structure is zeroed no // matter whether the code is running on an alternate stack or not). So the check would always fail on WSL. stack_t *signalStack = &((native_context_t *)context)->uc_stack; // Check if the signalStack local variable address is within the alternate stack range. If it is not, // then either the alternate stack was not installed at all or the current method is not running on it. void* alternateStackEnd = (char *)signalStack->ss_sp + signalStack->ss_size; isRunningOnAlternateStack = ((signalStack->ss_flags & SS_DISABLE) == 0) && (signalStack->ss_sp <= &signalStack) && (&signalStack < alternateStackEnd); } else { // If alternate stack check is disabled, consider always that we are running on an alternate // signal handler stack. isRunningOnAlternateStack = true; } return isRunningOnAlternateStack; #endif // HAVE_MACH_EXCEPTIONS } static bool IsSaSigInfo(struct sigaction* action) { return (action->sa_flags & SA_SIGINFO) != 0; } static bool IsSigDfl(struct sigaction* action) { // macOS can return sigaction with SIG_DFL and SA_SIGINFO. // SA_SIGINFO means we should use sa_sigaction, but here we want to check sa_handler. // So we ignore SA_SIGINFO when sa_sigaction and sa_handler are at the same address. return (&action->sa_handler == (void*)&action->sa_sigaction || !IsSaSigInfo(action)) && action->sa_handler == SIG_DFL; } static bool IsSigIgn(struct sigaction* action) { return (&action->sa_handler == (void*)&action->sa_sigaction || !IsSaSigInfo(action)) && action->sa_handler == SIG_IGN; } /*++ Function : invoke_previous_action synchronously invokes the previous action or aborts when that is not possible Parameters : action : previous sigaction struct code : signal code siginfo : signal siginfo context : signal context signalRestarts: BOOL state : TRUE if the process will be signalled again (no return value) --*/ static void invoke_previous_action(struct sigaction* action, int code, siginfo_t *siginfo, void *context, bool signalRestarts = true) { _ASSERTE(action != NULL); if (IsSigIgn(action)) { if (signalRestarts) { // This signal mustn't be ignored because it will be restarted. PROCAbort(code); } return; } else if (IsSigDfl(action)) { if (signalRestarts) { // Restore the original and restart h/w exception. restore_signal(code, action); } else { // We can't invoke the original handler because returning from the // handler doesn't restart the exception. PROCAbort(code); } } else if (IsSaSigInfo(action)) { // Directly call the previous handler. _ASSERTE(action->sa_sigaction != NULL); action->sa_sigaction(code, siginfo, context); } else { // Directly call the previous handler. _ASSERTE(action->sa_handler != NULL); action->sa_handler(code); } PROCNotifyProcessShutdown(IsRunningOnAlternateStack(context)); PROCCreateCrashDumpIfEnabled(code); } /*++ Function : sigill_handler handle SIGILL signal (EXCEPTION_ILLEGAL_INSTRUCTION, others?) Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigill_handler(int code, siginfo_t *siginfo, void *context) { if (PALIsInitialized()) { if (common_signal_handler(code, siginfo, context, 0)) { return; } } invoke_previous_action(&g_previous_sigill, code, siginfo, context); } /*++ Function : sigfpe_handler handle SIGFPE signal (division by zero, floating point exception) Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigfpe_handler(int code, siginfo_t *siginfo, void *context) { if (PALIsInitialized()) { if (common_signal_handler(code, siginfo, context, 0)) { return; } } invoke_previous_action(&g_previous_sigfpe, code, siginfo, context); } #if !HAVE_MACH_EXCEPTIONS /*++ Function : signal_handler_worker Handles signal on the original stack where the signal occured. Invoked via setcontext. Parameters : POSIX signal handler parameter list ("man sigaction" for details) returnPoint - context to which the function returns if the common_signal_handler returns (no return value) --*/ extern "C" void signal_handler_worker(int code, siginfo_t *siginfo, void *context, SignalHandlerWorkerReturnPoint* returnPoint) { // TODO: First variable parameter says whether a read (0) or write (non-0) caused the // fault. We must disassemble the instruction at record.ExceptionAddress // to correctly fill in this value. // Unmask the activation signal now that we are running on the original stack of the thread sigset_t signal_set; sigemptyset(&signal_set); sigaddset(&signal_set, INJECT_ACTIVATION_SIGNAL); int sigmaskRet = pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL); if (sigmaskRet != 0) { ASSERT("pthread_sigmask failed; error number is %d\n", sigmaskRet); } returnPoint->returnFromHandler = common_signal_handler(code, siginfo, context, 2, (size_t)0, (size_t)siginfo->si_addr); // We are going to return to the alternate stack, so block the activation signal again sigmaskRet = pthread_sigmask(SIG_BLOCK, &signal_set, NULL); if (sigmaskRet != 0) { ASSERT("pthread_sigmask failed; error number is %d\n", sigmaskRet); } RtlRestoreContext(&returnPoint->context, NULL); } /*++ Function : SwitchStackAndExecuteHandler Switch to the stack specified by the sp argument Parameters : POSIX signal handler parameter list ("man sigaction" for details) sp - stack pointer of the stack to execute the handler on. If sp == 0, execute it on the original stack where the signal has occured. Return : The return value from the signal handler --*/ static bool SwitchStackAndExecuteHandler(int code, siginfo_t *siginfo, void *context, size_t sp) { // Establish a return point in case the common_signal_handler returns volatile bool contextInitialization = true; void *ptr = alloca(sizeof(SignalHandlerWorkerReturnPoint) + alignof(SignalHandlerWorkerReturnPoint) - 1); SignalHandlerWorkerReturnPoint *pReturnPoint = (SignalHandlerWorkerReturnPoint *)ALIGN_UP(ptr, alignof(SignalHandlerWorkerReturnPoint)); RtlCaptureContext(&pReturnPoint->context); // When the signal handler worker completes, it uses setcontext to return to this point if (contextInitialization) { contextInitialization = false; ExecuteHandlerOnCustomStack(code, siginfo, context, sp, pReturnPoint); _ASSERTE(FALSE); // The ExecuteHandlerOnCustomStack should never return } return pReturnPoint->returnFromHandler; } #endif // !HAVE_MACH_EXCEPTIONS /*++ Function : sigsegv_handler handle SIGSEGV signal (EXCEPTION_ACCESS_VIOLATION, others) Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigsegv_handler(int code, siginfo_t *siginfo, void *context) { #if !HAVE_MACH_EXCEPTIONS if (PALIsInitialized()) { // First check if we have a stack overflow size_t sp = (size_t)GetNativeContextSP((native_context_t *)context); size_t failureAddress = (size_t)siginfo->si_addr; // If the failure address is at most one page above or below the stack pointer, // we have a stack overflow. if ((failureAddress - (sp - GetVirtualPageSize())) < 2 * GetVirtualPageSize()) { if (GetCurrentPalThread()) { size_t handlerStackTop = __sync_val_compare_and_swap((size_t*)&g_stackOverflowHandlerStack, (size_t)g_stackOverflowHandlerStack, 0); if (handlerStackTop == 0) { // We have only one stack for handling stack overflow preallocated. We let only the first thread that hits stack overflow to // run the exception handling code on that stack (which ends up just dumping the stack trace and aborting the process). // Other threads are held spinning and sleeping here until the process exits. while (true) { sleep(1); } } if (SwitchStackAndExecuteHandler(code | StackOverflowFlag, siginfo, context, (size_t)handlerStackTop)) { PROCAbort(SIGSEGV); } } else { (void)!write(STDERR_FILENO, StackOverflowMessage, sizeof(StackOverflowMessage) - 1); PROCAbort(SIGSEGV); } } // Now that we know the SIGSEGV didn't happen due to a stack overflow, execute the common // hardware signal handler on the original stack. if (GetCurrentPalThread() && IsRunningOnAlternateStack(context)) { if (SwitchStackAndExecuteHandler(code, siginfo, context, 0 /* sp */)) // sp == 0 indicates execution on the original stack { return; } } else { // The code flow gets here when the signal handler is not running on an alternate stack or when it wasn't created // by coreclr. In both cases, we execute the common_signal_handler directly. // If thread isn't created by coreclr and has alternate signal stack GetCurrentPalThread() will return NULL too. // But since in this case we don't handle hardware exceptions (IsSafeToHandleHardwareException returns false) // we can call common_signal_handler on the alternate stack. if (common_signal_handler(code, siginfo, context, 2, (size_t)0, (size_t)siginfo->si_addr)) { return; } } } #endif // !HAVE_MACH_EXCEPTIONS invoke_previous_action(&g_previous_sigsegv, code, siginfo, context); } /*++ Function : sigtrap_handler handle SIGTRAP signal (EXCEPTION_SINGLE_STEP, EXCEPTION_BREAKPOINT) Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigtrap_handler(int code, siginfo_t *siginfo, void *context) { if (PALIsInitialized()) { if (common_signal_handler(code, siginfo, context, 0)) { return; } } // The signal doesn't restart, returning from a SIGTRAP handler continues execution past the trap. invoke_previous_action(&g_previous_sigtrap, code, siginfo, context, /* signalRestarts */ false); } /*++ Function : sigbus_handler handle SIGBUS signal (EXCEPTION_ACCESS_VIOLATION?) Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigbus_handler(int code, siginfo_t *siginfo, void *context) { if (PALIsInitialized()) { // TODO: First variable parameter says whether a read (0) or write (non-0) caused the // fault. We must disassemble the instruction at record.ExceptionAddress // to correctly fill in this value. if (common_signal_handler(code, siginfo, context, 2, (size_t)0, (size_t)siginfo->si_addr)) { return; } } invoke_previous_action(&g_previous_sigbus, code, siginfo, context); } /*++ Function : sigabrt_handler handle SIGABRT signal - abort() API Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigabrt_handler(int code, siginfo_t *siginfo, void *context) { invoke_previous_action(&g_previous_sigabrt, code, siginfo, context); } /*++ Function : sigint_handler handle SIGINT signal Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigint_handler(int code, siginfo_t *siginfo, void *context) { PROCNotifyProcessShutdown(); restore_signal_and_resend(code, &g_previous_sigint); } /*++ Function : sigquit_handler handle SIGQUIT signal Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigquit_handler(int code, siginfo_t *siginfo, void *context) { PROCNotifyProcessShutdown(); restore_signal_and_resend(code, &g_previous_sigquit); } /*++ Function : sigterm_handler handle SIGTERM signal Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void sigterm_handler(int code, siginfo_t *siginfo, void *context) { if (PALIsInitialized()) { // g_pSynchronizationManager shouldn't be null if PAL is initialized. _ASSERTE(g_pSynchronizationManager != nullptr); g_pSynchronizationManager->SendTerminationRequestToWorkerThread(); } else { restore_signal_and_resend(SIGTERM, &g_previous_sigterm); } } #ifdef INJECT_ACTIVATION_SIGNAL /*++ Function : inject_activation_handler Handle the INJECT_ACTIVATION_SIGNAL signal. This signal interrupts a running thread so it can call the activation function that was specified when sending the signal. Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void inject_activation_handler(int code, siginfo_t *siginfo, void *context) { // Only accept activations from the current process if (g_activationFunction != NULL && (siginfo->si_pid == getpid() #ifdef HOST_OSX // On OSX si_pid is sometimes 0. It was confirmed by Apple to be expected, as the si_pid is tracked at the process level. So when multiple // signals are in flight in the same process at the same time, it may be overwritten / zeroed. || siginfo->si_pid == 0 #endif )) { _ASSERTE(g_safeActivationCheckFunction != NULL); native_context_t *ucontext = (native_context_t *)context; CONTEXT winContext; CONTEXTFromNativeContext( ucontext, &winContext, CONTEXT_CONTROL | CONTEXT_INTEGER); if (g_safeActivationCheckFunction(CONTEXTGetPC(&winContext), /* checkingCurrentThread */ TRUE)) { int savedErrNo = errno; // Make sure that errno is not modified g_activationFunction(&winContext); errno = savedErrNo; // Activation function may have modified the context, so update it. CONTEXTToNativeContext(&winContext, ucontext); } } else { // Call the original handler when it is not ignored or default (terminate). if (g_previous_activation.sa_flags & SA_SIGINFO) { _ASSERTE(g_previous_activation.sa_sigaction != NULL); g_previous_activation.sa_sigaction(code, siginfo, context); } else { if (g_previous_activation.sa_handler != SIG_IGN && g_previous_activation.sa_handler != SIG_DFL) { _ASSERTE(g_previous_activation.sa_handler != NULL); g_previous_activation.sa_handler(code); } } } } #endif /*++ Function : InjectActivationInternal Interrupt the specified thread and have it call the activationFunction passed in Parameters : pThread - target PAL thread activationFunction - function to call (no return value) --*/ PAL_ERROR InjectActivationInternal(CorUnix::CPalThread* pThread) { #ifdef INJECT_ACTIVATION_SIGNAL int status = pthread_kill(pThread->GetPThreadSelf(), INJECT_ACTIVATION_SIGNAL); // We can get EAGAIN when printing stack overflow stack trace and when other threads hit // stack overflow too. Those are held in the sigsegv_handler with blocked signals until // the process exits. #ifdef __APPLE__ // On Apple, pthread_kill is not allowed to be sent to dispatch queue threads if (status == ENOTSUP) { return ERROR_NOT_SUPPORTED; } #endif if ((status != 0) && (status != EAGAIN)) { // Failure to send the signal is fatal. There are only two cases when sending // the signal can fail. First, if the signal ID is invalid and second, // if the thread doesn't exist anymore. PROCAbort(); } return NO_ERROR; #else return ERROR_CANCELLED; #endif } #if !HAVE_MACH_EXCEPTIONS /*++ Function : signal_ignore_handler Simple signal handler which does nothing Parameters : POSIX signal handler parameter list ("man sigaction" for details) (no return value) --*/ static void signal_ignore_handler(int code, siginfo_t *siginfo, void *context) { } #endif // !HAVE_MACH_EXCEPTIONS void PAL_IgnoreProfileSignal(int signalNum) { #if !HAVE_MACH_EXCEPTIONS // Add a signal handler which will ignore signals // This will allow signal to be used as a marker in perf recording. // This will be used as an aid to synchronize recorded profile with // test cases // // signal(signalNum, SGN_IGN) can not be used here. It will ignore // the signal in kernel space and therefore generate no recordable // event for profiling. Preventing it being used for profile // synchronization // // Since this is only used in rare circumstances no attempt to // restore the old handler will be made handle_signal(signalNum, signal_ignore_handler, 0); #endif } /*++ Function : common_signal_handler common code for all signal handlers Parameters : int code : signal received siginfo_t *siginfo : siginfo passed to the signal handler void *context : context structure passed to the signal handler int numParams : number of variable parameters of the exception ... : variable parameters of the exception (each of size_t type) Returns true if the execution should continue or false if the exception was unhandled Note: the "pointers" parameter should contain a valid exception record pointer, but the ContextRecord pointer will be overwritten. --*/ __attribute__((noinline)) static bool common_signal_handler(int code, siginfo_t *siginfo, void *sigcontext, int numParams, ...) { #if !HAVE_MACH_EXCEPTIONS sigset_t signal_set; CONTEXT signalContextRecord; CONTEXT* signalContextRecordPtr = &signalContextRecord; EXCEPTION_RECORD exceptionRecord; native_context_t *ucontext; ucontext = (native_context_t *)sigcontext; g_hardware_exception_context_locvar_offset = (int)((char*)&signalContextRecordPtr - (char*)__builtin_frame_address(0)); if (code == (SIGSEGV | StackOverflowFlag)) { exceptionRecord.ExceptionCode = EXCEPTION_STACK_OVERFLOW; code &= ~StackOverflowFlag; } else { exceptionRecord.ExceptionCode = CONTEXTGetExceptionCodeForSignal(siginfo, ucontext); } exceptionRecord.ExceptionFlags = EXCEPTION_IS_SIGNAL; exceptionRecord.ExceptionRecord = NULL; exceptionRecord.ExceptionAddress = GetNativeContextPC(ucontext); exceptionRecord.NumberParameters = numParams; va_list params; va_start(params, numParams); for (int i = 0; i < numParams; i++) { exceptionRecord.ExceptionInformation[i] = va_arg(params, size_t); } // Pre-populate context with data from current frame, because ucontext doesn't have some data (e.g. SS register) // which is required for restoring context RtlCaptureContext(&signalContextRecord); ULONG contextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_FLOATING_POINT; #if defined(HOST_AMD64) contextFlags |= CONTEXT_XSTATE; #endif // Fill context record with required information. from pal.h: // On non-Win32 platforms, the CONTEXT pointer in the // PEXCEPTION_POINTERS will contain at least the CONTEXT_CONTROL registers. CONTEXTFromNativeContext(ucontext, &signalContextRecord, contextFlags); /* Unmask signal so we can receive it again */ sigemptyset(&signal_set); sigaddset(&signal_set, code); int sigmaskRet = pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL); if (sigmaskRet != 0) { ASSERT("pthread_sigmask failed; error number is %d\n", sigmaskRet); } signalContextRecord.ContextFlags |= CONTEXT_EXCEPTION_ACTIVE; // The exception object takes ownership of the exceptionRecord and contextRecord PAL_SEHException exception(&exceptionRecord, &signalContextRecord, true); if (SEHProcessException(&exception)) { // Exception handling may have modified the context, so update it. CONTEXTToNativeContext(exception.ExceptionPointers.ContextRecord, ucontext); return true; } #endif // !HAVE_MACH_EXCEPTIONS return false; } /*++ Function : handle_signal register handler for specified signal Parameters : int signal_id : signal to handle SIGFUNC sigfunc : signal handler previousAction : previous sigaction struct (no return value) note : if sigfunc is NULL, the default signal handler is restored --*/ void handle_signal(int signal_id, SIGFUNC sigfunc, struct sigaction *previousAction, int additionalFlags, bool skipIgnored) { struct sigaction newAction; newAction.sa_flags = SA_RESTART | additionalFlags; newAction.sa_handler = NULL; newAction.sa_sigaction = sigfunc; newAction.sa_flags |= SA_SIGINFO; sigemptyset(&newAction.sa_mask); #ifdef INJECT_ACTIVATION_SIGNAL if ((additionalFlags & SA_ONSTACK) != 0) { // A handler that runs on a separate stack should not be interrupted by the activation signal // until it switches back to the regular stack, since that signal's handler would run on the // limited separate stack and likely run into a stack overflow. sigaddset(&newAction.sa_mask, INJECT_ACTIVATION_SIGNAL); } #endif if (skipIgnored) { if (-1 == sigaction(signal_id, NULL, previousAction)) { ASSERT("handle_signal: sigaction() call failed with error code %d (%s)\n", errno, strerror(errno)); } else if (previousAction->sa_handler == SIG_IGN) { return; } } if (-1 == sigaction(signal_id, &newAction, previousAction)) { ASSERT("handle_signal: sigaction() call failed with error code %d (%s)\n", errno, strerror(errno)); } } /*++ Function : restore_signal restore handler for specified signal Parameters : int signal_id : signal to handle previousAction : previous sigaction struct to restore (no return value) --*/ void restore_signal(int signal_id, struct sigaction *previousAction) { if (-1 == sigaction(signal_id, previousAction, NULL)) { ASSERT("restore_signal: sigaction() call failed with error code %d (%s)\n", errno, strerror(errno)); } } /*++ Function : restore_signal_and_resend restore handler for specified signal and signal the process Parameters : int signal_id : signal to handle previousAction : previous sigaction struct to restore (no return value) --*/ void restore_signal_and_resend(int signal_id, struct sigaction* previousAction) { restore_signal(signal_id, previousAction); kill(gPID, signal_id); }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./docs/workflow/testing/coreclr/unix-test-instructions.md
Building and running tests on Linux, macOS, and FreeBSD ====================================================== CoreCLR tests ------------- ## Building Build CoreCLR on [Unix](../../building/coreclr/linux-instructions.md). ## Building the Tests Dotnet CLI is required to build the tests. This can be done on any platform then copied over if the architecture or OS does not support Dotnet. To build the tests on Unix: ```sh ./src/tests/build.sh ``` By default, the test build uses Release as the libraries configuration. To use a different configuration, set the `LibrariesConfiguration` property to the desired configuration. For example: ``` ./src/tests/build.sh /p:LibrariesConfiguration=Debug ``` Please note that this builds the Priority 0 tests. To build priority 1: ```sh ./src/tests/build.sh -priority1 ``` ## Generating Core_Root The `src/tests/build.sh` script generates the Core_Root folder, which contains the test host (`corerun`), libraries, and coreclr product binaries necessary to run a test. To generate Core_Root without building the tests: ``` ./src/tests/build.sh generatelayoutonly ``` The output will be at `<repo_root>/artifacts/tests/coreclr/<os>.<arch>.<configuration>/Tests/Core_Root`. ## Building Test Subsets The `src/tests/build.sh` script supports three options that let you limit the set of tests to build; when none of these is specified, the entire test tree (under `src/tests`) gets built but that can be lengthy (especially in `-priority1` mode) and unnecessary when working on a particular test. 1) `-test:<test-project>` - build a particular test project specified by its project file path, either absolute or relative to `src/tests`. The option can be specified multiple times on the command line to request building several individual projects; alternatively, a single occurrence of the option can represent several project paths separated by semicolons. **Example**: `src/tests/build.sh -test:JIT/Methodical/divrem/div/i4div_cs_do.csproj;JIT/Methodical/divrem/div/i8div_cs_do.csproj` 2) `-dir:<test-folder>` - build all test projects within a given directory path, either absolute or relative to `src/tests`. The option can be specified multiple times on the command line to request building projects in several folders; alternatively, a single occurrence of this option can represent several project folders separated by semicolons. **Example**: `src/tests/build.sh -dir:JIT/Methodical/Arrays/huge;JIT/Methodical/divrem/div` 3) `-tree:<root-folder>` - build all test projects within the subtree specified by its root path, either absolute or relative to `src/tests`. The option can be specified multiple times on the command line to request building projects in several subtrees; alternatively, a single instance of the option can represent several project subtree root folder paths separated by semicolons. **Example**: `src/tests/build.sh -tree:baseservices/exceptions;JIT/Methodical` **Please note** that priority filtering is orthogonal to specifying test subsets; even when you request building a particular test and the test is Pri1, you need to specify `-priority1` in the command line, otherwise the test build will get skipped. While somewhat unintuitive, 'fixing' this ad hoc would likely create more harm than good and we're hoping to ultimately get rid of the test priorities in the long term anyway. ## Building Individual Tests During development there are many instances where building an individual test is fast and necessary. All of the necessary tools to build are under `coreclr`. It is possible to use `~/runtime/dotnet.sh msbuild` as you would normally use MSBuild with a few caveats. **!! Note !! -- Passing /p:TargetOS=[OSX|Linux] is required.** ## Building an Individual Test ```sh ./dotnet.sh msbuild src/tests/path-to-proj-file /p:TargetOS=<TargetOS> /p:Configuration=<BuildType> ``` In addition to the test assembly, this will generate a `.sh` script next to the test assembly in the test's output folder. The test's output folder will be under `<repo_root>/artifacts/tests/coreclr/<os>.<arch>.<configuration>` at a subpath based on the test's location in source. ## Running Tests The following instructions assume that on the Unix machine: - The CoreCLR repo is cloned at `/mnt/coreclr` `src/tests/build.sh` will have set up the `Core_Root` directory correctly after the test build. ```sh ./src/tests/run.sh x64 checked ``` Please use the following command for help. ```sh ./src/tests/run.sh -h ``` ### Unsupported and temporarily disabled tests To support building all tests for all targets on single target, we use the conditional property ```xml <CLRTestTargetUnsupported Condition="...">true</CLRTestTargetUnsupported> ``` This property disables building of a test in a default build. It also disables running a test in the bash/batch wrapper scripts. It allows the test to be built on any target in CI when the `allTargets` option is passed to the `build.*` scripts. Tests which never should be built or run are marked ```xml <DisableProjectBuild>true</DisableProjectBuild> ``` This propoerty should not be conditioned on Target properties to allow all tests to be built for `allTargets`. ## Running Individual Tests After [building an individual test](#building-individual-tests), to run the test: 1) Set the `CORE_ROOT` environment variable to the [Core_Root folder](#generating-core_root). 2) Run the test using the `.sh` generated for the test. PAL tests --------- Build CoreCLR with PAL tests on the Unix machine: ```sh ./build.sh clr.paltests ``` Run tests: To run all tests including disabled tests ```sh ./src/coreclr/pal/tests/palsuite/runpaltests.sh $(pwd)/artifacts/bin/coreclr/$(uname).x64.Debug/paltests # on macOS, replace $(uname) with OSX ``` To only run enabled tests for the platform the tests were built for: ```sh artifacts/bin/coreclr/$(uname).x64.Debug/paltests/runpaltests.sh $(pwd)/artifacts/bin/coreclr/$(uname).x64.Debug/paltests # on macOS, replace $(uname) with OSX ``` Test results will go into: `/tmp/PalTestOutput/default/pal_tests.xml` To disable tests in the CI edit `src/coreclr/pal/tests/palsuite/issues.targets`
Building and running tests on Linux, macOS, and FreeBSD ====================================================== CoreCLR tests ------------- ## Building Build CoreCLR on [Unix](../../building/coreclr/linux-instructions.md). ## Building the Tests Dotnet CLI is required to build the tests. This can be done on any platform then copied over if the architecture or OS does not support Dotnet. To build the tests on Unix: ```sh ./src/tests/build.sh ``` By default, the test build uses Release as the libraries configuration. To use a different configuration, set the `LibrariesConfiguration` property to the desired configuration. For example: ``` ./src/tests/build.sh /p:LibrariesConfiguration=Debug ``` Please note that this builds the Priority 0 tests. To build priority 1: ```sh ./src/tests/build.sh -priority1 ``` ## Generating Core_Root The `src/tests/build.sh` script generates the Core_Root folder, which contains the test host (`corerun`), libraries, and coreclr product binaries necessary to run a test. To generate Core_Root without building the tests: ``` ./src/tests/build.sh generatelayoutonly ``` The output will be at `<repo_root>/artifacts/tests/coreclr/<os>.<arch>.<configuration>/Tests/Core_Root`. ## Building Test Subsets The `src/tests/build.sh` script supports three options that let you limit the set of tests to build; when none of these is specified, the entire test tree (under `src/tests`) gets built but that can be lengthy (especially in `-priority1` mode) and unnecessary when working on a particular test. 1) `-test:<test-project>` - build a particular test project specified by its project file path, either absolute or relative to `src/tests`. The option can be specified multiple times on the command line to request building several individual projects; alternatively, a single occurrence of the option can represent several project paths separated by semicolons. **Example**: `src/tests/build.sh -test:JIT/Methodical/divrem/div/i4div_cs_do.csproj;JIT/Methodical/divrem/div/i8div_cs_do.csproj` 2) `-dir:<test-folder>` - build all test projects within a given directory path, either absolute or relative to `src/tests`. The option can be specified multiple times on the command line to request building projects in several folders; alternatively, a single occurrence of this option can represent several project folders separated by semicolons. **Example**: `src/tests/build.sh -dir:JIT/Methodical/Arrays/huge;JIT/Methodical/divrem/div` 3) `-tree:<root-folder>` - build all test projects within the subtree specified by its root path, either absolute or relative to `src/tests`. The option can be specified multiple times on the command line to request building projects in several subtrees; alternatively, a single instance of the option can represent several project subtree root folder paths separated by semicolons. **Example**: `src/tests/build.sh -tree:baseservices/exceptions;JIT/Methodical` **Please note** that priority filtering is orthogonal to specifying test subsets; even when you request building a particular test and the test is Pri1, you need to specify `-priority1` in the command line, otherwise the test build will get skipped. While somewhat unintuitive, 'fixing' this ad hoc would likely create more harm than good and we're hoping to ultimately get rid of the test priorities in the long term anyway. ## Building Individual Tests During development there are many instances where building an individual test is fast and necessary. All of the necessary tools to build are under `coreclr`. It is possible to use `~/runtime/dotnet.sh msbuild` as you would normally use MSBuild with a few caveats. **!! Note !! -- Passing /p:TargetOS=[OSX|Linux] is required.** ## Building an Individual Test ```sh ./dotnet.sh msbuild src/tests/path-to-proj-file /p:TargetOS=<TargetOS> /p:Configuration=<BuildType> ``` In addition to the test assembly, this will generate a `.sh` script next to the test assembly in the test's output folder. The test's output folder will be under `<repo_root>/artifacts/tests/coreclr/<os>.<arch>.<configuration>` at a subpath based on the test's location in source. ## Running Tests The following instructions assume that on the Unix machine: - The CoreCLR repo is cloned at `/mnt/coreclr` `src/tests/build.sh` will have set up the `Core_Root` directory correctly after the test build. ```sh ./src/tests/run.sh x64 checked ``` Please use the following command for help. ```sh ./src/tests/run.sh -h ``` ### Unsupported and temporarily disabled tests To support building all tests for all targets on single target, we use the conditional property ```xml <CLRTestTargetUnsupported Condition="...">true</CLRTestTargetUnsupported> ``` This property disables building of a test in a default build. It also disables running a test in the bash/batch wrapper scripts. It allows the test to be built on any target in CI when the `allTargets` option is passed to the `build.*` scripts. Tests which never should be built or run are marked ```xml <DisableProjectBuild>true</DisableProjectBuild> ``` This propoerty should not be conditioned on Target properties to allow all tests to be built for `allTargets`. ## Running Individual Tests After [building an individual test](#building-individual-tests), to run the test: 1) Set the `CORE_ROOT` environment variable to the [Core_Root folder](#generating-core_root). 2) Run the test using the `.sh` generated for the test. PAL tests --------- Build CoreCLR with PAL tests on the Unix machine: ```sh ./build.sh clr.paltests ``` Run tests: To run all tests including disabled tests ```sh ./src/coreclr/pal/tests/palsuite/runpaltests.sh $(pwd)/artifacts/bin/coreclr/$(uname).x64.Debug/paltests # on macOS, replace $(uname) with OSX ``` To only run enabled tests for the platform the tests were built for: ```sh artifacts/bin/coreclr/$(uname).x64.Debug/paltests/runpaltests.sh $(pwd)/artifacts/bin/coreclr/$(uname).x64.Debug/paltests # on macOS, replace $(uname) with OSX ``` Test results will go into: `/tmp/PalTestOutput/default/pal_tests.xml` To disable tests in the CI edit `src/coreclr/pal/tests/palsuite/issues.targets`
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/xsltc/baseline/sft44.txt
Microsoft (R) XSLT Compiler version 2.0.61009 for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727 Copyright (C) Microsoft Corporation 2007. All rights reserved. error : Invalid setting 'script+document-'; must be dtd[+|-], document[+|-] or script[+|-].
Microsoft (R) XSLT Compiler version 2.0.61009 for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727 Copyright (C) Microsoft Corporation 2007. All rights reserved. error : Invalid setting 'script+document-'; must be dtd[+|-], document[+|-] or script[+|-].
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/jit64/mcc/interop/native_i3c.cpp
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <stdarg.h> #include "native.h" MCC_API VType3 sum(double count1, int count2, __int64 count3, float count4, short count5, double count6, ...) { int count = (int)count1 + (int)count2 + (int)count3 + (int)count4 + (int)count5 + (int)count6; VType3 res; va_list args; // zero out res res.reset(); // initialize variable arguments. va_start(args, count6); for (int i = 0; i < count; ++i) { VType3 val = va_arg(args, VType3); res.add(val); } // reset variable arguments. va_end(args); return res; }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <stdarg.h> #include "native.h" MCC_API VType3 sum(double count1, int count2, __int64 count3, float count4, short count5, double count6, ...) { int count = (int)count1 + (int)count2 + (int)count3 + (int)count4 + (int)count5 + (int)count6; VType3 res; va_list args; // zero out res res.reset(); // initialize variable arguments. va_start(args, count6); for (int i = 0; i < count; ++i) { VType3 val = va_arg(args, VType3); res.add(val); } // reset variable arguments. va_end(args); return res; }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/xsltc/baseline/cnt5.txt
<?xml version="1.0" encoding="utf-8"?>Hello, world!
<?xml version="1.0" encoding="utf-8"?>Hello, world!
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/pal/tests/palsuite/c_runtime/vfprintf/test14/test14.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================================ ** ** Source: test14.c ** ** Purpose: Test #14 for the vfprintf function. Tests the lowercase ** exponential notation double specifier (%e) ** ** **==========================================================================*/ #include <palsuite.h> #include "../vfprintf.h" PALTEST(c_runtime_vfprintf_test14_paltest_vfprintf_test14, "c_runtime/vfprintf/test14/paltest_vfprintf_test14") { double val = 256.0; double neg = -256.0; if (PAL_Initialize(argc, argv)) { return FAIL; } DoDoubleTest("foo %e", val, "foo 2.560000e+002", "foo 2.560000e+02"); DoDoubleTest("foo %le", val, "foo 2.560000e+002", "foo 2.560000e+02"); DoDoubleTest("foo %he", val, "foo 2.560000e+002", "foo 2.560000e+02"); DoDoubleTest("foo %Le", val, "foo 2.560000e+002", "foo 2.560000e+02"); DoDoubleTest("foo %I64e", val, "foo 2.560000e+002", "foo 2.560000e+02"); DoDoubleTest("foo %14e", val, "foo 2.560000e+002", "foo 2.560000e+02"); DoDoubleTest("foo %-14e", val, "foo 2.560000e+002 ", "foo 2.560000e+02 "); DoDoubleTest("foo %.1e", val, "foo 2.6e+002", "foo 2.6e+02"); DoDoubleTest("foo %.8e", val, "foo 2.56000000e+002", "foo 2.56000000e+02"); DoDoubleTest("foo %014e", val, "foo 02.560000e+002", "foo 002.560000e+02"); DoDoubleTest("foo %#e", val, "foo 2.560000e+002", "foo 2.560000e+02"); DoDoubleTest("foo %+e", val, "foo +2.560000e+002", "foo +2.560000e+02"); DoDoubleTest("foo % e", val, "foo 2.560000e+002", "foo 2.560000e+02"); DoDoubleTest("foo %+e", neg, "foo -2.560000e+002", "foo -2.560000e+02"); DoDoubleTest("foo % e", neg, "foo -2.560000e+002", "foo -2.560000e+02"); 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: test14.c ** ** Purpose: Test #14 for the vfprintf function. Tests the lowercase ** exponential notation double specifier (%e) ** ** **==========================================================================*/ #include <palsuite.h> #include "../vfprintf.h" PALTEST(c_runtime_vfprintf_test14_paltest_vfprintf_test14, "c_runtime/vfprintf/test14/paltest_vfprintf_test14") { double val = 256.0; double neg = -256.0; if (PAL_Initialize(argc, argv)) { return FAIL; } DoDoubleTest("foo %e", val, "foo 2.560000e+002", "foo 2.560000e+02"); DoDoubleTest("foo %le", val, "foo 2.560000e+002", "foo 2.560000e+02"); DoDoubleTest("foo %he", val, "foo 2.560000e+002", "foo 2.560000e+02"); DoDoubleTest("foo %Le", val, "foo 2.560000e+002", "foo 2.560000e+02"); DoDoubleTest("foo %I64e", val, "foo 2.560000e+002", "foo 2.560000e+02"); DoDoubleTest("foo %14e", val, "foo 2.560000e+002", "foo 2.560000e+02"); DoDoubleTest("foo %-14e", val, "foo 2.560000e+002 ", "foo 2.560000e+02 "); DoDoubleTest("foo %.1e", val, "foo 2.6e+002", "foo 2.6e+02"); DoDoubleTest("foo %.8e", val, "foo 2.56000000e+002", "foo 2.56000000e+02"); DoDoubleTest("foo %014e", val, "foo 02.560000e+002", "foo 002.560000e+02"); DoDoubleTest("foo %#e", val, "foo 2.560000e+002", "foo 2.560000e+02"); DoDoubleTest("foo %+e", val, "foo +2.560000e+002", "foo +2.560000e+02"); DoDoubleTest("foo % e", val, "foo 2.560000e+002", "foo 2.560000e+02"); DoDoubleTest("foo %+e", neg, "foo -2.560000e+002", "foo -2.560000e+02"); DoDoubleTest("foo % e", neg, "foo -2.560000e+002", "foo -2.560000e+02"); PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/pal/tests/palsuite/loader/LoadLibraryA/test5/loadlibrarya.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================= ** ** Source: loadlibrarya.c ** ** Purpose: Negative test the LoadLibraryA API. ** Call LoadLibraryA by passing a module name ** without extension but with a trailing dot. ** ** **============================================================*/ #include <palsuite.h> PALTEST(loader_LoadLibraryA_test5_paltest_loadlibrarya_test5, "loader/LoadLibraryA/test5/paltest_loadlibrarya_test5") { HMODULE ModuleHandle; char ModuleName[_MAX_FNAME]; int err; /* Initialize the PAL environment */ err = PAL_Initialize(argc, argv); if(0 != err) { return FAIL; } memset(ModuleName, 0, _MAX_FNAME); /*Module name without extension but with a trailing dot*/ #if WIN32 sprintf_s(ModuleName, ARRAY_SIZE(ModuleName), "%s", "rotor_pal."); #else /* Under FreeBSD */ sprintf_s(ModuleName, ARRAY_SIZE(ModuleName), "%s", "librotor_pal."); #endif /* load a module which does not have the file extension, * but has a trailing dot */ ModuleHandle = LoadLibraryA(ModuleName); if(NULL != ModuleHandle) { Trace("Failed to call LoadLibraryA API for a negative test " "call LoadLibraryA with module name which does not have " "extension except a trailing dot, a NULL module handle is" "expected, but no NULL module handle is returned, " "error code = %u\n", GetLastError()); /* decrement the reference count of the loaded dll */ err = FreeLibrary(ModuleHandle); if(0 == err) { Trace("\nFailed to call FreeLibrary API, " "error code = %u\n", GetLastError()); } Fail(""); } 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: loadlibrarya.c ** ** Purpose: Negative test the LoadLibraryA API. ** Call LoadLibraryA by passing a module name ** without extension but with a trailing dot. ** ** **============================================================*/ #include <palsuite.h> PALTEST(loader_LoadLibraryA_test5_paltest_loadlibrarya_test5, "loader/LoadLibraryA/test5/paltest_loadlibrarya_test5") { HMODULE ModuleHandle; char ModuleName[_MAX_FNAME]; int err; /* Initialize the PAL environment */ err = PAL_Initialize(argc, argv); if(0 != err) { return FAIL; } memset(ModuleName, 0, _MAX_FNAME); /*Module name without extension but with a trailing dot*/ #if WIN32 sprintf_s(ModuleName, ARRAY_SIZE(ModuleName), "%s", "rotor_pal."); #else /* Under FreeBSD */ sprintf_s(ModuleName, ARRAY_SIZE(ModuleName), "%s", "librotor_pal."); #endif /* load a module which does not have the file extension, * but has a trailing dot */ ModuleHandle = LoadLibraryA(ModuleName); if(NULL != ModuleHandle) { Trace("Failed to call LoadLibraryA API for a negative test " "call LoadLibraryA with module name which does not have " "extension except a trailing dot, a NULL module handle is" "expected, but no NULL module handle is returned, " "error code = %u\n", GetLastError()); /* decrement the reference count of the loaded dll */ err = FreeLibrary(ModuleHandle); if(0 == err) { Trace("\nFailed to call FreeLibrary API, " "error code = %u\n", GetLastError()); } Fail(""); } PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/jit64/hfa/main/testE/hfa_testE.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 HFATest { public class TestCase { #pragma warning disable 0414 const sbyte CONST_INT8 = (sbyte)77; const short CONST_INT16 = (short)77; const int CONST_INT32 = (int)77; const long CONST_INT64 = (long)77; const float CONST_FLOAT32 = (float)77.0; const double CONST_FLOAT64 = (double)77.0; #pragma warning restore 0414 static int Main() { HFA01 hfa01; HFA02 hfa02; HFA03 hfa03; HFA05 hfa05; HFA08 hfa08; HFA11 hfa11; HFA19 hfa19; TestMan.Init_HFA01(out hfa01); TestMan.Init_HFA02(out hfa02); TestMan.Init_HFA03(out hfa03); TestMan.Init_HFA05(out hfa05); TestMan.Init_HFA08(out hfa08); TestMan.Init_HFA11(out hfa11); TestMan.Init_HFA19(out hfa19); int nFailures = 0; nFailures += Common.CheckResult("Identity HFA 01", TestMan.Sum_HFA01(TestMan.Identity_HFA01(hfa01)), TestMan.EXPECTED_SUM_HFA01) ? 0 : 1; nFailures += Common.CheckResult("Identity HFA 02", TestMan.Sum_HFA02(TestMan.Identity_HFA02(hfa02)), TestMan.EXPECTED_SUM_HFA02) ? 0 : 1; nFailures += Common.CheckResult("Identity HFA 03", TestMan.Sum_HFA03(TestMan.Identity_HFA03(hfa03)), TestMan.EXPECTED_SUM_HFA03) ? 0 : 1; nFailures += Common.CheckResult("Identity HFA 05", TestMan.Sum_HFA05(TestMan.Identity_HFA05(hfa05)), TestMan.EXPECTED_SUM_HFA05) ? 0 : 1; nFailures += Common.CheckResult("Identity HFA 08", TestMan.Sum_HFA08(TestMan.Identity_HFA08(hfa08)), TestMan.EXPECTED_SUM_HFA08) ? 0 : 1; nFailures += Common.CheckResult("Identity HFA 11", TestMan.Sum_HFA11(TestMan.Identity_HFA11(hfa11)), TestMan.EXPECTED_SUM_HFA11) ? 0 : 1; nFailures += Common.CheckResult("Identity HFA 19", TestMan.Sum_HFA19(TestMan.Identity_HFA19(hfa19)), TestMan.EXPECTED_SUM_HFA19) ? 0 : 1; nFailures += Common.CheckResult("Get HFA 01", TestMan.Sum_HFA01(TestMan.Get_HFA01()), TestMan.EXPECTED_SUM_HFA01) ? 0 : 1; nFailures += Common.CheckResult("Get HFA 02", TestMan.Sum_HFA02(TestMan.Get_HFA02()), TestMan.EXPECTED_SUM_HFA02) ? 0 : 1; nFailures += Common.CheckResult("Get HFA 03", TestMan.Sum_HFA03(TestMan.Get_HFA03()), TestMan.EXPECTED_SUM_HFA03) ? 0 : 1; nFailures += Common.CheckResult("Get HFA 05", TestMan.Sum_HFA05(TestMan.Get_HFA05()), TestMan.EXPECTED_SUM_HFA05) ? 0 : 1; nFailures += Common.CheckResult("Get HFA 08", TestMan.Sum_HFA08(TestMan.Get_HFA08()), TestMan.EXPECTED_SUM_HFA08) ? 0 : 1; nFailures += Common.CheckResult("Get HFA 11", TestMan.Sum_HFA11(TestMan.Get_HFA11()), TestMan.EXPECTED_SUM_HFA11) ? 0 : 1; nFailures += Common.CheckResult("Get HFA 19", TestMan.Sum_HFA19(TestMan.Get_HFA19()), TestMan.EXPECTED_SUM_HFA19) ? 0 : 1; return nFailures == 0 ? Common.SUCC_RET_CODE : Common.FAIL_RET_CODE; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace HFATest { public class TestCase { #pragma warning disable 0414 const sbyte CONST_INT8 = (sbyte)77; const short CONST_INT16 = (short)77; const int CONST_INT32 = (int)77; const long CONST_INT64 = (long)77; const float CONST_FLOAT32 = (float)77.0; const double CONST_FLOAT64 = (double)77.0; #pragma warning restore 0414 static int Main() { HFA01 hfa01; HFA02 hfa02; HFA03 hfa03; HFA05 hfa05; HFA08 hfa08; HFA11 hfa11; HFA19 hfa19; TestMan.Init_HFA01(out hfa01); TestMan.Init_HFA02(out hfa02); TestMan.Init_HFA03(out hfa03); TestMan.Init_HFA05(out hfa05); TestMan.Init_HFA08(out hfa08); TestMan.Init_HFA11(out hfa11); TestMan.Init_HFA19(out hfa19); int nFailures = 0; nFailures += Common.CheckResult("Identity HFA 01", TestMan.Sum_HFA01(TestMan.Identity_HFA01(hfa01)), TestMan.EXPECTED_SUM_HFA01) ? 0 : 1; nFailures += Common.CheckResult("Identity HFA 02", TestMan.Sum_HFA02(TestMan.Identity_HFA02(hfa02)), TestMan.EXPECTED_SUM_HFA02) ? 0 : 1; nFailures += Common.CheckResult("Identity HFA 03", TestMan.Sum_HFA03(TestMan.Identity_HFA03(hfa03)), TestMan.EXPECTED_SUM_HFA03) ? 0 : 1; nFailures += Common.CheckResult("Identity HFA 05", TestMan.Sum_HFA05(TestMan.Identity_HFA05(hfa05)), TestMan.EXPECTED_SUM_HFA05) ? 0 : 1; nFailures += Common.CheckResult("Identity HFA 08", TestMan.Sum_HFA08(TestMan.Identity_HFA08(hfa08)), TestMan.EXPECTED_SUM_HFA08) ? 0 : 1; nFailures += Common.CheckResult("Identity HFA 11", TestMan.Sum_HFA11(TestMan.Identity_HFA11(hfa11)), TestMan.EXPECTED_SUM_HFA11) ? 0 : 1; nFailures += Common.CheckResult("Identity HFA 19", TestMan.Sum_HFA19(TestMan.Identity_HFA19(hfa19)), TestMan.EXPECTED_SUM_HFA19) ? 0 : 1; nFailures += Common.CheckResult("Get HFA 01", TestMan.Sum_HFA01(TestMan.Get_HFA01()), TestMan.EXPECTED_SUM_HFA01) ? 0 : 1; nFailures += Common.CheckResult("Get HFA 02", TestMan.Sum_HFA02(TestMan.Get_HFA02()), TestMan.EXPECTED_SUM_HFA02) ? 0 : 1; nFailures += Common.CheckResult("Get HFA 03", TestMan.Sum_HFA03(TestMan.Get_HFA03()), TestMan.EXPECTED_SUM_HFA03) ? 0 : 1; nFailures += Common.CheckResult("Get HFA 05", TestMan.Sum_HFA05(TestMan.Get_HFA05()), TestMan.EXPECTED_SUM_HFA05) ? 0 : 1; nFailures += Common.CheckResult("Get HFA 08", TestMan.Sum_HFA08(TestMan.Get_HFA08()), TestMan.EXPECTED_SUM_HFA08) ? 0 : 1; nFailures += Common.CheckResult("Get HFA 11", TestMan.Sum_HFA11(TestMan.Get_HFA11()), TestMan.EXPECTED_SUM_HFA11) ? 0 : 1; nFailures += Common.CheckResult("Get HFA 19", TestMan.Sum_HFA19(TestMan.Get_HFA19()), TestMan.EXPECTED_SUM_HFA19) ? 0 : 1; return nFailures == 0 ? Common.SUCC_RET_CODE : Common.FAIL_RET_CODE; } } }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/HardwareIntrinsics/General/Vector128/Floor.Single.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 FloorSingle() { var test = new VectorUnaryOpTest__FloorSingle(); // 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 VectorUnaryOpTest__FloorSingle { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__FloorSingle testClass) { var result = Vector128.Floor(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__FloorSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public VectorUnaryOpTest__FloorSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.Floor( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.Floor), new Type[] { typeof(Vector128<Single>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.Floor), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Single)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.Floor( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var result = Vector128.Floor(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__FloorSingle(); var result = Vector128.Floor(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.Floor(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.Floor(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != MathF.Floor(firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != MathF.Floor(firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.Floor)}<Single>(Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 FloorSingle() { var test = new VectorUnaryOpTest__FloorSingle(); // 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 VectorUnaryOpTest__FloorSingle { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__FloorSingle testClass) { var result = Vector128.Floor(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__FloorSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public VectorUnaryOpTest__FloorSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.Floor( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.Floor), new Type[] { typeof(Vector128<Single>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.Floor), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Single)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.Floor( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var result = Vector128.Floor(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__FloorSingle(); var result = Vector128.Floor(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.Floor(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.Floor(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != MathF.Floor(firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != MathF.Floor(firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.Floor)}<Single>(Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/nativeaot/Runtime/gcrhscan.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "common.h" #include "gcenv.h" #include "gcheaputilities.h" #include "objecthandle.h" #include "gcenv.ee.h" #include "PalRedhawkCommon.h" #include "gcrhinterface.h" #include "slist.h" #include "varint.h" #include "regdisplay.h" #include "StackFrameIterator.h" #include "thread.h" #include "shash.h" #include "RWLock.h" #include "RuntimeInstance.h" #include "threadstore.h" #include "threadstore.inl" #include "thread.inl" #ifndef DACCESS_COMPILE void GcEnumObjectsConservatively(PTR_PTR_Object ppLowerBound, PTR_PTR_Object ppUpperBound, EnumGcRefCallbackFunc * fnGcEnumRef, EnumGcRefScanContext * pSc); void EnumAllStaticGCRefs(EnumGcRefCallbackFunc * fn, EnumGcRefScanContext * sc) { GetRuntimeInstance()->EnumAllStaticGCRefs(reinterpret_cast<void*>(fn), sc); } /* * Scan all stack and statics roots */ void GCToEEInterface::GcScanRoots(EnumGcRefCallbackFunc * fn, int condemned, int max_gen, EnumGcRefScanContext * sc) { // STRESS_LOG1(LF_GCROOTS, LL_INFO10, "GCScan: Phase = %s\n", sc->promotion ? "promote" : "relocate"); FOREACH_THREAD(pThread) { // Skip "GC Special" threads which are really background workers that will never have any roots. if (pThread->IsGCSpecial()) continue; #if !defined (ISOLATED_HEAPS) // @TODO: it is very bizarre that this IsThreadUsingAllocationContextHeap takes a copy of the // allocation context instead of a reference or a pointer to it. This seems very wasteful given how // large the alloc_context is. if (!GCHeapUtilities::GetGCHeap()->IsThreadUsingAllocationContextHeap(pThread->GetAllocContext(), sc->thread_number)) { // STRESS_LOG2(LF_GC|LF_GCROOTS, LL_INFO100, "{ Scan of Thread %p (ID = %x) declined by this heap\n", // pThread, pThread->GetThreadId()); } else #endif { STRESS_LOG1(LF_GC|LF_GCROOTS, LL_INFO100, "{ Starting scan of Thread %p\n", pThread); sc->thread_under_crawl = pThread; #if defined(FEATURE_EVENT_TRACE) && !defined(DACCESS_COMPILE) sc->dwEtwRootKind = kEtwGCRootKindStack; #endif pThread->GcScanRoots(reinterpret_cast<void*>(fn), sc); #if defined(FEATURE_EVENT_TRACE) && !defined(DACCESS_COMPILE) sc->dwEtwRootKind = kEtwGCRootKindOther; #endif STRESS_LOG1(LF_GC|LF_GCROOTS, LL_INFO100, "Ending scan of Thread %p }\n", pThread); } } END_FOREACH_THREAD sc->thread_under_crawl = NULL; if ((!GCHeapUtilities::IsServerHeap() || sc->thread_number == 0) ||(condemned == max_gen && sc->promotion)) { #if defined(FEATURE_EVENT_TRACE) && !defined(DACCESS_COMPILE) sc->dwEtwRootKind = kEtwGCRootKindHandle; #endif EnumAllStaticGCRefs(fn, sc); } } void GCToEEInterface::GcEnumAllocContexts (enum_alloc_context_func* fn, void* param) { FOREACH_THREAD(thread) { (*fn) (thread->GetAllocContext(), param); } END_FOREACH_THREAD } #endif //!DACCESS_COMPILE void PromoteCarefully(PTR_PTR_Object obj, uint32_t flags, EnumGcRefCallbackFunc * fnGcEnumRef, EnumGcRefScanContext * pSc) { // // Sanity check that the flags contain only these three values // assert((flags & ~(GC_CALL_INTERIOR|GC_CALL_PINNED|GC_CALL_CHECK_APP_DOMAIN)) == 0); // // Sanity check that GC_CALL_INTERIOR FLAG is set // assert(flags & GC_CALL_INTERIOR); // If the object reference points into the stack, we // must not promote it, the GC cannot handle these. if (pSc->thread_under_crawl->IsWithinStackBounds(*obj)) return; fnGcEnumRef(obj, pSc, flags); } void GcEnumObject(PTR_PTR_Object ppObj, uint32_t flags, EnumGcRefCallbackFunc * fnGcEnumRef, EnumGcRefScanContext * pSc) { // // Sanity check that the flags contain only these three values // assert((flags & ~(GC_CALL_INTERIOR|GC_CALL_PINNED|GC_CALL_CHECK_APP_DOMAIN)) == 0); // for interior pointers, we optimize the case in which // it points into the current threads stack area // if (flags & GC_CALL_INTERIOR) PromoteCarefully (ppObj, flags, fnGcEnumRef, pSc); else fnGcEnumRef(ppObj, pSc, flags); } void GcBulkEnumObjects(PTR_PTR_Object pObjs, uint32_t cObjs, EnumGcRefCallbackFunc * fnGcEnumRef, EnumGcRefScanContext * pSc) { PTR_PTR_Object ppObj = pObjs; for (uint32_t i = 0; i < cObjs; i++) fnGcEnumRef(ppObj++, pSc, 0); } // Scan a contiguous range of memory and report everything that looks like it could be a GC reference as a // pinned interior reference. Pinned in case we are wrong (so the GC won't try to move the object and thus // corrupt the original memory value by relocating it). Interior since we (a) can't easily tell whether a // real reference is interior or not and interior is the more conservative choice that will work for both and // (b) because it might not be a real GC reference at all and in that case falsely listing the reference as // non-interior will cause the GC to make assumptions and crash quite quickly. void GcEnumObjectsConservatively(PTR_PTR_Object ppLowerBound, PTR_PTR_Object ppUpperBound, EnumGcRefCallbackFunc * fnGcEnumRef, EnumGcRefScanContext * pSc) { // Only report potential references in the promotion phase. Since we report everything as pinned there // should be no work to do in the relocation phase. if (pSc->promotion) { for (PTR_PTR_Object ppObj = ppLowerBound; ppObj < ppUpperBound; ppObj++) { // Only report values that lie in the GC heap range. This doesn't conclusively guarantee that the // value is a GC heap reference but it's a cheap check that weeds out a lot of spurious values. PTR_Object pObj = *ppObj; if (((PTR_UInt8)pObj >= g_lowest_address) && ((PTR_UInt8)pObj <= g_highest_address)) fnGcEnumRef(ppObj, pSc, GC_CALL_INTERIOR|GC_CALL_PINNED); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "common.h" #include "gcenv.h" #include "gcheaputilities.h" #include "objecthandle.h" #include "gcenv.ee.h" #include "PalRedhawkCommon.h" #include "gcrhinterface.h" #include "slist.h" #include "varint.h" #include "regdisplay.h" #include "StackFrameIterator.h" #include "thread.h" #include "shash.h" #include "RWLock.h" #include "RuntimeInstance.h" #include "threadstore.h" #include "threadstore.inl" #include "thread.inl" #ifndef DACCESS_COMPILE void GcEnumObjectsConservatively(PTR_PTR_Object ppLowerBound, PTR_PTR_Object ppUpperBound, EnumGcRefCallbackFunc * fnGcEnumRef, EnumGcRefScanContext * pSc); void EnumAllStaticGCRefs(EnumGcRefCallbackFunc * fn, EnumGcRefScanContext * sc) { GetRuntimeInstance()->EnumAllStaticGCRefs(reinterpret_cast<void*>(fn), sc); } /* * Scan all stack and statics roots */ void GCToEEInterface::GcScanRoots(EnumGcRefCallbackFunc * fn, int condemned, int max_gen, EnumGcRefScanContext * sc) { // STRESS_LOG1(LF_GCROOTS, LL_INFO10, "GCScan: Phase = %s\n", sc->promotion ? "promote" : "relocate"); FOREACH_THREAD(pThread) { // Skip "GC Special" threads which are really background workers that will never have any roots. if (pThread->IsGCSpecial()) continue; #if !defined (ISOLATED_HEAPS) // @TODO: it is very bizarre that this IsThreadUsingAllocationContextHeap takes a copy of the // allocation context instead of a reference or a pointer to it. This seems very wasteful given how // large the alloc_context is. if (!GCHeapUtilities::GetGCHeap()->IsThreadUsingAllocationContextHeap(pThread->GetAllocContext(), sc->thread_number)) { // STRESS_LOG2(LF_GC|LF_GCROOTS, LL_INFO100, "{ Scan of Thread %p (ID = %x) declined by this heap\n", // pThread, pThread->GetThreadId()); } else #endif { STRESS_LOG1(LF_GC|LF_GCROOTS, LL_INFO100, "{ Starting scan of Thread %p\n", pThread); sc->thread_under_crawl = pThread; #if defined(FEATURE_EVENT_TRACE) && !defined(DACCESS_COMPILE) sc->dwEtwRootKind = kEtwGCRootKindStack; #endif pThread->GcScanRoots(reinterpret_cast<void*>(fn), sc); #if defined(FEATURE_EVENT_TRACE) && !defined(DACCESS_COMPILE) sc->dwEtwRootKind = kEtwGCRootKindOther; #endif STRESS_LOG1(LF_GC|LF_GCROOTS, LL_INFO100, "Ending scan of Thread %p }\n", pThread); } } END_FOREACH_THREAD sc->thread_under_crawl = NULL; if ((!GCHeapUtilities::IsServerHeap() || sc->thread_number == 0) ||(condemned == max_gen && sc->promotion)) { #if defined(FEATURE_EVENT_TRACE) && !defined(DACCESS_COMPILE) sc->dwEtwRootKind = kEtwGCRootKindHandle; #endif EnumAllStaticGCRefs(fn, sc); } } void GCToEEInterface::GcEnumAllocContexts (enum_alloc_context_func* fn, void* param) { FOREACH_THREAD(thread) { (*fn) (thread->GetAllocContext(), param); } END_FOREACH_THREAD } #endif //!DACCESS_COMPILE void PromoteCarefully(PTR_PTR_Object obj, uint32_t flags, EnumGcRefCallbackFunc * fnGcEnumRef, EnumGcRefScanContext * pSc) { // // Sanity check that the flags contain only these three values // assert((flags & ~(GC_CALL_INTERIOR|GC_CALL_PINNED|GC_CALL_CHECK_APP_DOMAIN)) == 0); // // Sanity check that GC_CALL_INTERIOR FLAG is set // assert(flags & GC_CALL_INTERIOR); // If the object reference points into the stack, we // must not promote it, the GC cannot handle these. if (pSc->thread_under_crawl->IsWithinStackBounds(*obj)) return; fnGcEnumRef(obj, pSc, flags); } void GcEnumObject(PTR_PTR_Object ppObj, uint32_t flags, EnumGcRefCallbackFunc * fnGcEnumRef, EnumGcRefScanContext * pSc) { // // Sanity check that the flags contain only these three values // assert((flags & ~(GC_CALL_INTERIOR|GC_CALL_PINNED|GC_CALL_CHECK_APP_DOMAIN)) == 0); // for interior pointers, we optimize the case in which // it points into the current threads stack area // if (flags & GC_CALL_INTERIOR) PromoteCarefully (ppObj, flags, fnGcEnumRef, pSc); else fnGcEnumRef(ppObj, pSc, flags); } void GcBulkEnumObjects(PTR_PTR_Object pObjs, uint32_t cObjs, EnumGcRefCallbackFunc * fnGcEnumRef, EnumGcRefScanContext * pSc) { PTR_PTR_Object ppObj = pObjs; for (uint32_t i = 0; i < cObjs; i++) fnGcEnumRef(ppObj++, pSc, 0); } // Scan a contiguous range of memory and report everything that looks like it could be a GC reference as a // pinned interior reference. Pinned in case we are wrong (so the GC won't try to move the object and thus // corrupt the original memory value by relocating it). Interior since we (a) can't easily tell whether a // real reference is interior or not and interior is the more conservative choice that will work for both and // (b) because it might not be a real GC reference at all and in that case falsely listing the reference as // non-interior will cause the GC to make assumptions and crash quite quickly. void GcEnumObjectsConservatively(PTR_PTR_Object ppLowerBound, PTR_PTR_Object ppUpperBound, EnumGcRefCallbackFunc * fnGcEnumRef, EnumGcRefScanContext * pSc) { // Only report potential references in the promotion phase. Since we report everything as pinned there // should be no work to do in the relocation phase. if (pSc->promotion) { for (PTR_PTR_Object ppObj = ppLowerBound; ppObj < ppUpperBound; ppObj++) { // Only report values that lie in the GC heap range. This doesn't conclusively guarantee that the // value is a GC heap reference but it's a cheap check that weeds out a lot of spurious values. PTR_Object pObj = *ppObj; if (((PTR_UInt8)pObj >= g_lowest_address) && ((PTR_UInt8)pObj <= g_highest_address)) fnGcEnumRef(ppObj, pSc, GC_CALL_INTERIOR|GC_CALL_PINNED); } } }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Private.Xml/tests/XmlSchema/TestFiles/TestData/import_v1_a.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="ns-a" xmlns="ns-a" > <xsd:import schemaLocation="include_v1_b.xsd"/> <xsd:complexType name="ct-A"> <xsd:sequence minOccurs="1"> <xsd:element name="a1" type="xsd:int" /> <xsd:element name="a2" type="xsd:boolean" /> </xsd:sequence> </xsd:complexType> <xsd:element name="e1" type="ct-A" /> <xsd:element name="root"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:any namespace="##any" processContents="strict"/> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="ns-a" xmlns="ns-a" > <xsd:import schemaLocation="include_v1_b.xsd"/> <xsd:complexType name="ct-A"> <xsd:sequence minOccurs="1"> <xsd:element name="a1" type="xsd:int" /> <xsd:element name="a2" type="xsd:boolean" /> </xsd:sequence> </xsd:complexType> <xsd:element name="e1" type="ct-A" /> <xsd:element name="root"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:any namespace="##any" processContents="strict"/> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema>
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/vm/loaderallocator.inl
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef _LOADER_ALLOCATOR_I #define _LOADER_ALLOCATOR_I #include "assembly.hpp" #ifndef DACCESS_COMPILE inline LOADERALLOCATORREF LoaderAllocator::GetExposedObject() { LIMITED_METHOD_CONTRACT; OBJECTREF loaderAllocatorObject = (m_hLoaderAllocatorObjectHandle != NULL) ? ObjectFromHandle(m_hLoaderAllocatorObjectHandle) : NULL; return (LOADERALLOCATORREF)loaderAllocatorObject; } #endif inline void GlobalLoaderAllocator::Init(BaseDomain *pDomain) { LoaderAllocator::Init(pDomain, m_ExecutableHeapInstance); } inline BOOL LoaderAllocatorID::Equals(LoaderAllocatorID *pId) { LIMITED_METHOD_CONTRACT; if (GetType() != pId->GetType()) return false; return GetValue() == pId->GetValue(); } inline void LoaderAllocatorID::Init() { LIMITED_METHOD_CONTRACT; m_type = LAT_Assembly; }; inline void LoaderAllocatorID::AddDomainAssembly(DomainAssembly* pAssembly) { LIMITED_METHOD_CONTRACT; _ASSERTE(m_type == LAT_Assembly); // Link domain assembly together if (m_pDomainAssembly != NULL) { pAssembly->SetNextDomainAssemblyInSameALC(m_pDomainAssembly); } m_pDomainAssembly = pAssembly; } inline VOID* LoaderAllocatorID::GetValue() { LIMITED_METHOD_DAC_CONTRACT; return m_pValue; } inline COUNT_T LoaderAllocatorID::Hash() { LIMITED_METHOD_DAC_CONTRACT; return (COUNT_T)(SIZE_T)GetValue(); } inline LoaderAllocatorType LoaderAllocatorID::GetType() { LIMITED_METHOD_DAC_CONTRACT; return m_type; } inline DomainAssemblyIterator LoaderAllocatorID::GetDomainAssemblyIterator() { LIMITED_METHOD_DAC_CONTRACT; _ASSERTE(m_type == LAT_Assembly); return DomainAssemblyIterator(m_pDomainAssembly); } inline LoaderAllocatorID* AssemblyLoaderAllocator::Id() { LIMITED_METHOD_DAC_CONTRACT; return &m_Id; } inline LoaderAllocatorID* GlobalLoaderAllocator::Id() { LIMITED_METHOD_DAC_CONTRACT; return &m_Id; } /* static */ FORCEINLINE BOOL LoaderAllocator::GetHandleValueFast(LOADERHANDLE handle, OBJECTREF *pValue) { LIMITED_METHOD_CONTRACT; // If the slot value does have the low bit set, then it is a simple pointer to the value // Otherwise, we will need a more complicated operation to get the value. if ((((UINT_PTR)handle) & 1) != 0) { *pValue = *((OBJECTREF *)(((UINT_PTR)handle) - 1)); return TRUE; } else { return FALSE; } } FORCEINLINE BOOL LoaderAllocator::GetHandleValueFastPhase2(LOADERHANDLE handle, OBJECTREF *pValue) { SUPPORTS_DAC; STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_MODE_COOPERATIVE; STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; if (handle == 0) return FALSE; /* This is lockless access to the handle table, be careful */ OBJECTREF loaderAllocatorAsObjectRef = ObjectFromHandle(m_hLoaderAllocatorObjectHandle); // If the managed loader allocator has been collected, then the handles associated with it are dead as well. if (loaderAllocatorAsObjectRef == NULL) return FALSE; LOADERALLOCATORREF loaderAllocator = dac_cast<LOADERALLOCATORREF>(loaderAllocatorAsObjectRef); PTRARRAYREF handleTable = loaderAllocator->GetHandleTable(); UINT_PTR index = (((UINT_PTR)handle) >> 1) - 1; *pValue = handleTable->GetAt(index); return TRUE; } FORCEINLINE OBJECTREF LoaderAllocator::GetHandleValueFastCannotFailType2(LOADERHANDLE handle) { SUPPORTS_DAC; STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_MODE_COOPERATIVE; STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; /* This is lockless access to the handle table, be careful */ OBJECTREF loaderAllocatorAsObjectRef = ObjectFromHandle(m_hLoaderAllocatorObjectHandle); LOADERALLOCATORREF loaderAllocator = dac_cast<LOADERALLOCATORREF>(loaderAllocatorAsObjectRef); PTRARRAYREF handleTable = loaderAllocator->GetHandleTable(); UINT_PTR index = (((UINT_PTR)handle) >> 1) - 1; return handleTable->GetAt(index); } inline bool SegmentedHandleIndexStack::Push(DWORD value) { LIMITED_METHOD_CONTRACT; if (m_TOSIndex == Segment::Size) { Segment* segment; if (m_freeSegment == NULL) { segment = new (nothrow) Segment(); if (segment == NULL) { return false; } } else { segment = m_freeSegment; m_freeSegment = NULL; } segment->m_prev = m_TOSSegment; m_TOSSegment = segment; m_TOSIndex = 0; } m_TOSSegment->m_data[m_TOSIndex++] = value; return true; } inline DWORD SegmentedHandleIndexStack::Pop() { LIMITED_METHOD_CONTRACT; _ASSERTE(!IsEmpty()); if (m_TOSIndex == 0) { Segment* prevSegment = m_TOSSegment->m_prev; _ASSERTE(prevSegment != NULL); delete m_freeSegment; m_freeSegment = m_TOSSegment; m_TOSSegment = prevSegment; m_TOSIndex = Segment::Size; } return m_TOSSegment->m_data[--m_TOSIndex]; } inline bool SegmentedHandleIndexStack::IsEmpty() { LIMITED_METHOD_CONTRACT; return (m_TOSSegment == NULL) || ((m_TOSIndex == 0) && (m_TOSSegment->m_prev == NULL)); } #endif // _LOADER_ALLOCATOR_I
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef _LOADER_ALLOCATOR_I #define _LOADER_ALLOCATOR_I #include "assembly.hpp" #ifndef DACCESS_COMPILE inline LOADERALLOCATORREF LoaderAllocator::GetExposedObject() { LIMITED_METHOD_CONTRACT; OBJECTREF loaderAllocatorObject = (m_hLoaderAllocatorObjectHandle != NULL) ? ObjectFromHandle(m_hLoaderAllocatorObjectHandle) : NULL; return (LOADERALLOCATORREF)loaderAllocatorObject; } #endif inline void GlobalLoaderAllocator::Init(BaseDomain *pDomain) { LoaderAllocator::Init(pDomain, m_ExecutableHeapInstance); } inline BOOL LoaderAllocatorID::Equals(LoaderAllocatorID *pId) { LIMITED_METHOD_CONTRACT; if (GetType() != pId->GetType()) return false; return GetValue() == pId->GetValue(); } inline void LoaderAllocatorID::Init() { LIMITED_METHOD_CONTRACT; m_type = LAT_Assembly; }; inline void LoaderAllocatorID::AddDomainAssembly(DomainAssembly* pAssembly) { LIMITED_METHOD_CONTRACT; _ASSERTE(m_type == LAT_Assembly); // Link domain assembly together if (m_pDomainAssembly != NULL) { pAssembly->SetNextDomainAssemblyInSameALC(m_pDomainAssembly); } m_pDomainAssembly = pAssembly; } inline VOID* LoaderAllocatorID::GetValue() { LIMITED_METHOD_DAC_CONTRACT; return m_pValue; } inline COUNT_T LoaderAllocatorID::Hash() { LIMITED_METHOD_DAC_CONTRACT; return (COUNT_T)(SIZE_T)GetValue(); } inline LoaderAllocatorType LoaderAllocatorID::GetType() { LIMITED_METHOD_DAC_CONTRACT; return m_type; } inline DomainAssemblyIterator LoaderAllocatorID::GetDomainAssemblyIterator() { LIMITED_METHOD_DAC_CONTRACT; _ASSERTE(m_type == LAT_Assembly); return DomainAssemblyIterator(m_pDomainAssembly); } inline LoaderAllocatorID* AssemblyLoaderAllocator::Id() { LIMITED_METHOD_DAC_CONTRACT; return &m_Id; } inline LoaderAllocatorID* GlobalLoaderAllocator::Id() { LIMITED_METHOD_DAC_CONTRACT; return &m_Id; } /* static */ FORCEINLINE BOOL LoaderAllocator::GetHandleValueFast(LOADERHANDLE handle, OBJECTREF *pValue) { LIMITED_METHOD_CONTRACT; // If the slot value does have the low bit set, then it is a simple pointer to the value // Otherwise, we will need a more complicated operation to get the value. if ((((UINT_PTR)handle) & 1) != 0) { *pValue = *((OBJECTREF *)(((UINT_PTR)handle) - 1)); return TRUE; } else { return FALSE; } } FORCEINLINE BOOL LoaderAllocator::GetHandleValueFastPhase2(LOADERHANDLE handle, OBJECTREF *pValue) { SUPPORTS_DAC; STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_MODE_COOPERATIVE; STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; if (handle == 0) return FALSE; /* This is lockless access to the handle table, be careful */ OBJECTREF loaderAllocatorAsObjectRef = ObjectFromHandle(m_hLoaderAllocatorObjectHandle); // If the managed loader allocator has been collected, then the handles associated with it are dead as well. if (loaderAllocatorAsObjectRef == NULL) return FALSE; LOADERALLOCATORREF loaderAllocator = dac_cast<LOADERALLOCATORREF>(loaderAllocatorAsObjectRef); PTRARRAYREF handleTable = loaderAllocator->GetHandleTable(); UINT_PTR index = (((UINT_PTR)handle) >> 1) - 1; *pValue = handleTable->GetAt(index); return TRUE; } FORCEINLINE OBJECTREF LoaderAllocator::GetHandleValueFastCannotFailType2(LOADERHANDLE handle) { SUPPORTS_DAC; STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_MODE_COOPERATIVE; STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; /* This is lockless access to the handle table, be careful */ OBJECTREF loaderAllocatorAsObjectRef = ObjectFromHandle(m_hLoaderAllocatorObjectHandle); LOADERALLOCATORREF loaderAllocator = dac_cast<LOADERALLOCATORREF>(loaderAllocatorAsObjectRef); PTRARRAYREF handleTable = loaderAllocator->GetHandleTable(); UINT_PTR index = (((UINT_PTR)handle) >> 1) - 1; return handleTable->GetAt(index); } inline bool SegmentedHandleIndexStack::Push(DWORD value) { LIMITED_METHOD_CONTRACT; if (m_TOSIndex == Segment::Size) { Segment* segment; if (m_freeSegment == NULL) { segment = new (nothrow) Segment(); if (segment == NULL) { return false; } } else { segment = m_freeSegment; m_freeSegment = NULL; } segment->m_prev = m_TOSSegment; m_TOSSegment = segment; m_TOSIndex = 0; } m_TOSSegment->m_data[m_TOSIndex++] = value; return true; } inline DWORD SegmentedHandleIndexStack::Pop() { LIMITED_METHOD_CONTRACT; _ASSERTE(!IsEmpty()); if (m_TOSIndex == 0) { Segment* prevSegment = m_TOSSegment->m_prev; _ASSERTE(prevSegment != NULL); delete m_freeSegment; m_freeSegment = m_TOSSegment; m_TOSSegment = prevSegment; m_TOSIndex = Segment::Size; } return m_TOSSegment->m_data[--m_TOSIndex]; } inline bool SegmentedHandleIndexStack::IsEmpty() { LIMITED_METHOD_CONTRACT; return (m_TOSSegment == NULL) || ((m_TOSIndex == 0) && (m_TOSSegment->m_prev == NULL)); } #endif // _LOADER_ALLOCATOR_I
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/Common/tests/TestUtilities/System/RetryHelper.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.Threading; using System.Threading.Tasks; namespace System { public static partial class RetryHelper { private static readonly Func<int, int> s_defaultBackoffFunc = i => Math.Min(i * 100, 60_000); private static readonly Predicate<Exception> s_defaultRetryWhenFunc = _ => true; /// <summary>Executes the <paramref name="test"/> action up to a maximum of <paramref name="maxAttempts"/> times.</summary> /// <param name="maxAttempts">The maximum number of times to invoke <paramref name="test"/>.</param> /// <param name="test">The test to invoke.</param> /// <param name="backoffFunc">After a failure, invoked to determine how many milliseconds to wait before the next attempt. It's passed the number of iterations attempted.</param> /// <param name="retryWhen">Invoked to select the exceptions to retry on. If not set, any exception will trigger a retry.</param> public static void Execute(Action test, int maxAttempts = 5, Func<int, int> backoffFunc = null, Predicate<Exception> retryWhen = null) { // Validate arguments if (maxAttempts < 1) { throw new ArgumentOutOfRangeException(nameof(maxAttempts)); } if (test == null) { throw new ArgumentNullException(nameof(test)); } retryWhen ??= s_defaultRetryWhenFunc; // Execute the test until it either passes or we run it maxAttempts times var exceptions = new List<Exception>(); for (int i = 1; i <= maxAttempts; i++) { try { test(); return; } catch (Exception e) when (retryWhen(e)) { exceptions.Add(e); if (i == maxAttempts) { throw new AggregateException(exceptions); } } Thread.Sleep((backoffFunc ?? s_defaultBackoffFunc)(i)); } } /// <summary>Executes the <paramref name="test"/> action up to a maximum of <paramref name="maxAttempts"/> times.</summary> /// <param name="maxAttempts">The maximum number of times to invoke <paramref name="test"/>.</param> /// <param name="test">The test to invoke.</param> /// <param name="backoffFunc">After a failure, invoked to determine how many milliseconds to wait before the next attempt. It's passed the number of iterations attempted.</param> /// <param name="retryWhen">Invoked to select the exceptions to retry on. If not set, any exception will trigger a retry.</param> public static async Task ExecuteAsync(Func<Task> test, int maxAttempts = 5, Func<int, int> backoffFunc = null, Predicate<Exception> retryWhen = null) { // Validate arguments if (maxAttempts < 1) { throw new ArgumentOutOfRangeException(nameof(maxAttempts)); } if (test == null) { throw new ArgumentNullException(nameof(test)); } retryWhen ??= s_defaultRetryWhenFunc; // Execute the test until it either passes or we run it maxAttempts times var exceptions = new List<Exception>(); for (int i = 1; i <= maxAttempts; i++) { try { await test().ConfigureAwait(false); return; } catch (Exception e) when (retryWhen(e)) { exceptions.Add(e); if (i == maxAttempts) { throw new AggregateException(exceptions); } } await Task.Delay((backoffFunc ?? s_defaultBackoffFunc)(i)).ConfigureAwait(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.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace System { public static partial class RetryHelper { private static readonly Func<int, int> s_defaultBackoffFunc = i => Math.Min(i * 100, 60_000); private static readonly Predicate<Exception> s_defaultRetryWhenFunc = _ => true; /// <summary>Executes the <paramref name="test"/> action up to a maximum of <paramref name="maxAttempts"/> times.</summary> /// <param name="maxAttempts">The maximum number of times to invoke <paramref name="test"/>.</param> /// <param name="test">The test to invoke.</param> /// <param name="backoffFunc">After a failure, invoked to determine how many milliseconds to wait before the next attempt. It's passed the number of iterations attempted.</param> /// <param name="retryWhen">Invoked to select the exceptions to retry on. If not set, any exception will trigger a retry.</param> public static void Execute(Action test, int maxAttempts = 5, Func<int, int> backoffFunc = null, Predicate<Exception> retryWhen = null) { // Validate arguments if (maxAttempts < 1) { throw new ArgumentOutOfRangeException(nameof(maxAttempts)); } if (test == null) { throw new ArgumentNullException(nameof(test)); } retryWhen ??= s_defaultRetryWhenFunc; // Execute the test until it either passes or we run it maxAttempts times var exceptions = new List<Exception>(); for (int i = 1; i <= maxAttempts; i++) { try { test(); return; } catch (Exception e) when (retryWhen(e)) { exceptions.Add(e); if (i == maxAttempts) { throw new AggregateException(exceptions); } } Thread.Sleep((backoffFunc ?? s_defaultBackoffFunc)(i)); } } /// <summary>Executes the <paramref name="test"/> action up to a maximum of <paramref name="maxAttempts"/> times.</summary> /// <param name="maxAttempts">The maximum number of times to invoke <paramref name="test"/>.</param> /// <param name="test">The test to invoke.</param> /// <param name="backoffFunc">After a failure, invoked to determine how many milliseconds to wait before the next attempt. It's passed the number of iterations attempted.</param> /// <param name="retryWhen">Invoked to select the exceptions to retry on. If not set, any exception will trigger a retry.</param> public static async Task ExecuteAsync(Func<Task> test, int maxAttempts = 5, Func<int, int> backoffFunc = null, Predicate<Exception> retryWhen = null) { // Validate arguments if (maxAttempts < 1) { throw new ArgumentOutOfRangeException(nameof(maxAttempts)); } if (test == null) { throw new ArgumentNullException(nameof(test)); } retryWhen ??= s_defaultRetryWhenFunc; // Execute the test until it either passes or we run it maxAttempts times var exceptions = new List<Exception>(); for (int i = 1; i <= maxAttempts; i++) { try { await test().ConfigureAwait(false); return; } catch (Exception e) when (retryWhen(e)) { exceptions.Add(e); if (i == maxAttempts) { throw new AggregateException(exceptions); } } await Task.Delay((backoffFunc ?? s_defaultBackoffFunc)(i)).ConfigureAwait(false); } } } }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.ComponentModel.TypeConverter/tests/TrimmingTests/TypeConverterTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.ComponentModel; using System.Globalization; /// <summary> /// Tests that the relevant constructors of intrinsic TypeConverter types are preserved when needed in a trimmed application. /// </summary> class Program { static int Main(string[] args) { if (!RunTest(targetType: typeof(bool), expectedConverterType: typeof(BooleanConverter))) { return -1; } if (!RunTest(targetType: typeof(byte), expectedConverterType: typeof(ByteConverter))) { return -1; } if (!RunTest(targetType: typeof(sbyte), expectedConverterType: typeof(SByteConverter))) { return -1; } if (!RunTest(targetType: typeof(char), expectedConverterType: typeof(CharConverter))) { return -1; } if (!RunTest(targetType: typeof(double), expectedConverterType: typeof(DoubleConverter))) { return -1; } if (!RunTest(targetType: typeof(string), expectedConverterType: typeof(StringConverter))) { return -1; } if (!RunTest(targetType: typeof(short), expectedConverterType: typeof(Int16Converter))) { return -1; } if (!RunTest(targetType: typeof(int), expectedConverterType: typeof(Int32Converter))) { return -1; } if (!RunTest(targetType: typeof(long), expectedConverterType: typeof(Int64Converter))) { return -1; } if (!RunTest(targetType: typeof(float), expectedConverterType: typeof(SingleConverter))) { return -1; } if (!RunTest(targetType: typeof(ushort), expectedConverterType: typeof(UInt16Converter))) { return -1; } if (!RunTest(targetType: typeof(uint), expectedConverterType: typeof(UInt32Converter))) { return -1; } if (!RunTest(targetType: typeof(ulong), expectedConverterType: typeof(UInt64Converter))) { return -1; } if (!RunTest(targetType: typeof(object), expectedConverterType: typeof(TypeConverter))) { return -1; } if (!RunTest(targetType: typeof(DateTime), expectedConverterType: typeof(DateTimeConverter))) { return -1; } if (!RunTest(targetType: typeof(DateTimeOffset), expectedConverterType: typeof(DateTimeOffsetConverter))) { return -1; } if (!RunTest(targetType: typeof(decimal), expectedConverterType: typeof(DecimalConverter))) { return -1; } if (!RunTest(targetType: typeof(TimeSpan), expectedConverterType: typeof(TimeSpanConverter))) { return -1; } if (!RunTest(targetType: typeof(Guid), expectedConverterType: typeof(GuidConverter))) { return -1; } if (!RunTest(targetType: typeof(Array), expectedConverterType: typeof(ArrayConverter))) { return -1; } if (!RunTest(targetType: typeof(ICollection), expectedConverterType: typeof(CollectionConverter))) { return -1; } if (!RunTest(targetType: typeof(Enum), expectedConverterType: typeof(EnumConverter))) { return -1; } if (!RunTest(targetType: typeof(DayOfWeek), expectedConverterType: typeof(EnumConverter))) { return -1; } if (!RunTest(targetType: typeof(SomeValueType?), expectedConverterType: typeof(NullableConverter))) { return -1; } if (!RunTest(targetType: typeof(ClassWithNoConverter), expectedConverterType: typeof(TypeConverter))) { return -1; } if (!RunTest(targetType: typeof(Uri), expectedConverterType: typeof(UriTypeConverter))) { return -1; } if (!RunTest(targetType: typeof(CultureInfo), expectedConverterType: typeof(CultureInfoConverter))) { return -1; } if (!RunTest(targetType: typeof(Version), expectedConverterType: typeof(VersionConverter))) { return -1; } if (!RunTest(targetType: typeof(IFooComponent), expectedConverterType: typeof(ReferenceConverter))) { return -1; } return 100; } private static bool RunTest(Type targetType, Type expectedConverterType) { TypeConverter retrievedConverter = TypeDescriptor.GetConverter(targetType); return retrievedConverter.GetType() == expectedConverterType && retrievedConverter.CanConvertTo(typeof(string)); } private struct SomeValueType { } // TypeDescriptor should default to the TypeConverter in this case. private class ClassWithNoConverter { } private interface IFooComponent { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.ComponentModel; using System.Globalization; /// <summary> /// Tests that the relevant constructors of intrinsic TypeConverter types are preserved when needed in a trimmed application. /// </summary> class Program { static int Main(string[] args) { if (!RunTest(targetType: typeof(bool), expectedConverterType: typeof(BooleanConverter))) { return -1; } if (!RunTest(targetType: typeof(byte), expectedConverterType: typeof(ByteConverter))) { return -1; } if (!RunTest(targetType: typeof(sbyte), expectedConverterType: typeof(SByteConverter))) { return -1; } if (!RunTest(targetType: typeof(char), expectedConverterType: typeof(CharConverter))) { return -1; } if (!RunTest(targetType: typeof(double), expectedConverterType: typeof(DoubleConverter))) { return -1; } if (!RunTest(targetType: typeof(string), expectedConverterType: typeof(StringConverter))) { return -1; } if (!RunTest(targetType: typeof(short), expectedConverterType: typeof(Int16Converter))) { return -1; } if (!RunTest(targetType: typeof(int), expectedConverterType: typeof(Int32Converter))) { return -1; } if (!RunTest(targetType: typeof(long), expectedConverterType: typeof(Int64Converter))) { return -1; } if (!RunTest(targetType: typeof(float), expectedConverterType: typeof(SingleConverter))) { return -1; } if (!RunTest(targetType: typeof(ushort), expectedConverterType: typeof(UInt16Converter))) { return -1; } if (!RunTest(targetType: typeof(uint), expectedConverterType: typeof(UInt32Converter))) { return -1; } if (!RunTest(targetType: typeof(ulong), expectedConverterType: typeof(UInt64Converter))) { return -1; } if (!RunTest(targetType: typeof(object), expectedConverterType: typeof(TypeConverter))) { return -1; } if (!RunTest(targetType: typeof(DateTime), expectedConverterType: typeof(DateTimeConverter))) { return -1; } if (!RunTest(targetType: typeof(DateTimeOffset), expectedConverterType: typeof(DateTimeOffsetConverter))) { return -1; } if (!RunTest(targetType: typeof(decimal), expectedConverterType: typeof(DecimalConverter))) { return -1; } if (!RunTest(targetType: typeof(TimeSpan), expectedConverterType: typeof(TimeSpanConverter))) { return -1; } if (!RunTest(targetType: typeof(Guid), expectedConverterType: typeof(GuidConverter))) { return -1; } if (!RunTest(targetType: typeof(Array), expectedConverterType: typeof(ArrayConverter))) { return -1; } if (!RunTest(targetType: typeof(ICollection), expectedConverterType: typeof(CollectionConverter))) { return -1; } if (!RunTest(targetType: typeof(Enum), expectedConverterType: typeof(EnumConverter))) { return -1; } if (!RunTest(targetType: typeof(DayOfWeek), expectedConverterType: typeof(EnumConverter))) { return -1; } if (!RunTest(targetType: typeof(SomeValueType?), expectedConverterType: typeof(NullableConverter))) { return -1; } if (!RunTest(targetType: typeof(ClassWithNoConverter), expectedConverterType: typeof(TypeConverter))) { return -1; } if (!RunTest(targetType: typeof(Uri), expectedConverterType: typeof(UriTypeConverter))) { return -1; } if (!RunTest(targetType: typeof(CultureInfo), expectedConverterType: typeof(CultureInfoConverter))) { return -1; } if (!RunTest(targetType: typeof(Version), expectedConverterType: typeof(VersionConverter))) { return -1; } if (!RunTest(targetType: typeof(IFooComponent), expectedConverterType: typeof(ReferenceConverter))) { return -1; } return 100; } private static bool RunTest(Type targetType, Type expectedConverterType) { TypeConverter retrievedConverter = TypeDescriptor.GetConverter(targetType); return retrievedConverter.GetType() == expectedConverterType && retrievedConverter.CanConvertTo(typeof(string)); } private struct SomeValueType { } // TypeDescriptor should default to the TypeConverter in this case. private class ClassWithNoConverter { } private interface IFooComponent { } }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/pal/tests/palsuite/miscellaneous/IsBadWritePtr/test1/test.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================ ** ** Source: test.c ** ** Purpose: IsBadWritePtr() function ** ** **=========================================================*/ #include <palsuite.h> #define MEMORY_AMOUNT 16 PALTEST(miscellaneous_IsBadWritePtr_test1_paltest_isbadwriteptr_test1, "miscellaneous/IsBadWritePtr/test1/paltest_isbadwriteptr_test1") { void * TestingPointer = NULL; BOOL ResultValue = 0; /* * Initialize the PAL and return FAILURE if this fails */ if(0 != (PAL_Initialize(argc, argv))) { return FAIL; } TestingPointer = malloc(MEMORY_AMOUNT); if ( TestingPointer == NULL ) { Fail("ERROR: Failed to allocate memory for TestingPointer pointer. " "Can't properly exec test case without this.\n"); } /* This should be writeable, return 0 */ ResultValue = IsBadWritePtr(TestingPointer,MEMORY_AMOUNT); if(ResultValue != 0) { free(TestingPointer); Fail("ERROR: Returned %d when 0 should have been returned, checking " "to see if writable memory is unwriteable.\n",ResultValue); } free(TestingPointer); /* This should be !writeable, return nonezero */ TestingPointer = (void*)0x08; /* non writeable address */ ResultValue = IsBadWritePtr(TestingPointer,sizeof(int)); if(ResultValue == 0) { Fail("ERROR: Returned %d when nonezero should have been returned, " "checking to see if unwriteable memory is writeable.\n", ResultValue); } /* This should be !writeable, return Nonezero */ ResultValue = IsBadWritePtr(NULL,MEMORY_AMOUNT); if(ResultValue == 0) { Fail("ERROR: Returned %d when nonezero should have been " "returned,checking " "to see if a NULL pointer is writeable.\n", ResultValue); } 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: test.c ** ** Purpose: IsBadWritePtr() function ** ** **=========================================================*/ #include <palsuite.h> #define MEMORY_AMOUNT 16 PALTEST(miscellaneous_IsBadWritePtr_test1_paltest_isbadwriteptr_test1, "miscellaneous/IsBadWritePtr/test1/paltest_isbadwriteptr_test1") { void * TestingPointer = NULL; BOOL ResultValue = 0; /* * Initialize the PAL and return FAILURE if this fails */ if(0 != (PAL_Initialize(argc, argv))) { return FAIL; } TestingPointer = malloc(MEMORY_AMOUNT); if ( TestingPointer == NULL ) { Fail("ERROR: Failed to allocate memory for TestingPointer pointer. " "Can't properly exec test case without this.\n"); } /* This should be writeable, return 0 */ ResultValue = IsBadWritePtr(TestingPointer,MEMORY_AMOUNT); if(ResultValue != 0) { free(TestingPointer); Fail("ERROR: Returned %d when 0 should have been returned, checking " "to see if writable memory is unwriteable.\n",ResultValue); } free(TestingPointer); /* This should be !writeable, return nonezero */ TestingPointer = (void*)0x08; /* non writeable address */ ResultValue = IsBadWritePtr(TestingPointer,sizeof(int)); if(ResultValue == 0) { Fail("ERROR: Returned %d when nonezero should have been returned, " "checking to see if unwriteable memory is writeable.\n", ResultValue); } /* This should be !writeable, return Nonezero */ ResultValue = IsBadWritePtr(NULL,MEMORY_AMOUNT); if(ResultValue == 0) { Fail("ERROR: Returned %d when nonezero should have been " "returned,checking " "to see if a NULL pointer is writeable.\n", ResultValue); } PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Speech/src/Internal/SrgsCompiler/AppDomainGrammarProxy.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #region Using directives using System.Globalization; using System.Reflection; using System.Speech.Recognition.SrgsGrammar; using System.Text; #endregion #pragma warning disable 56500 // Remove all the catch all statements warnings used by the interop layer namespace System.Speech.Internal.SrgsCompiler { internal class AppDomainGrammarProxy : MarshalByRefObject { internal SrgsRule[] OnInit(string method, object[] parameters, string onInitParameters, out Exception exceptionThrown) { exceptionThrown = null; try { // If the onInitParameters are provided as a string, get the values as an array of value. if (!string.IsNullOrEmpty(onInitParameters)) { parameters = MatchInitParameters(method, onInitParameters, _rule, _rule); } // Find the constructor to call - there could be several Type[] types = new Type[parameters != null ? parameters.Length : 0]; if (parameters != null) { for (int i = 0; i < parameters.Length; i++) { types[i] = parameters[i].GetType(); } } MethodInfo onInit = _grammarType.GetMethod(method, types); // If somehow we failed to find a constructor, let the system handle it if (onInit == null) { throw new InvalidOperationException(SR.Get(SRID.ArgumentMismatch)); } SrgsRule[] extraRules = null; if (onInit != null) { extraRules = (SrgsRule[])onInit.Invoke(_grammar, parameters); } return extraRules; } catch (Exception e) { exceptionThrown = e; return null; } } internal object OnRecognition(string method, object[] parameters, out Exception exceptionThrown) { exceptionThrown = null; try { MethodInfo onRecognition = _grammarType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); // Execute the parse routine return onRecognition.Invoke(_grammar, parameters); } catch (Exception e) { exceptionThrown = e; } return null; } internal object OnParse(string rule, string method, object[] parameters, out Exception exceptionThrown) { exceptionThrown = null; try { MethodInfo onParse; System.Speech.Recognition.Grammar grammar; GetRuleInstance(rule, method, out onParse, out grammar); // Execute the parse routine return onParse.Invoke(grammar, parameters); } catch (Exception e) { exceptionThrown = e; return null; } } internal void OnError(string rule, string method, object[] parameters, out Exception exceptionThrown) { exceptionThrown = null; try { MethodInfo onError; System.Speech.Recognition.Grammar grammar; GetRuleInstance(rule, method, out onError, out grammar); // Execute the parse routine onError.Invoke(grammar, parameters); } catch (Exception e) { exceptionThrown = e; } } internal void Init(string rule, byte[] il, byte[] pdb) { _assembly = Assembly.Load(il, pdb); // Get the grammar class carrying the .NET Semantics code _grammarType = GetTypeForRule(_assembly, rule); // Something is Wrong if the grammar class cannot be found if (_grammarType == null) { throw new FormatException(SR.Get(SRID.RecognizerRuleNotFoundStream, rule)); } _rule = rule; try { _grammar = (System.Speech.Recognition.Grammar)_assembly.CreateInstance(_grammarType.FullName); } catch (MissingMemberException) { throw new ArgumentException(SR.Get(SRID.RuleScriptInvalidParameters, _grammarType.FullName, rule), nameof(rule)); } } private void GetRuleInstance(string rule, string method, out MethodInfo onParse, out System.Speech.Recognition.Grammar grammar) { Type ruleClass = rule == _rule ? _grammarType : GetTypeForRule(_assembly, rule); if (ruleClass == null || !ruleClass.IsSubclassOf(typeof(System.Speech.Recognition.Grammar))) { throw new FormatException(SR.Get(SRID.RecognizerInvalidBinaryGrammar)); } try { grammar = ruleClass == _grammarType ? _grammar : (System.Speech.Recognition.Grammar)_assembly.CreateInstance(ruleClass.FullName); } catch (MissingMemberException) { throw new ArgumentException(SR.Get(SRID.RuleScriptInvalidParameters, ruleClass.FullName, rule), nameof(rule)); } onParse = grammar.MethodInfo(method); } private static Type GetTypeForRule(Assembly assembly, string rule) { Type[] types = assembly.GetTypes(); for (int iType = 0; iType < types.Length; iType++) { Type type = types[iType]; if (type.Name == rule && type.IsPublic && type.IsSubclassOf(typeof(System.Speech.Recognition.Grammar))) { return type; } } return null; } /// <summary> /// Construct a list of parameters from a sapi:params string. /// </summary> private object[] MatchInitParameters(string method, string onInitParameters, string grammar, string rule) { MethodInfo[] mis = _grammarType.GetMethods(); NameValuePair[] pairs = ParseInitParams(onInitParameters); object[] values = new object[pairs.Length]; bool foundConstructor = false; for (int iCtor = 0; iCtor < mis.Length && !foundConstructor; iCtor++) { if (mis[iCtor].Name != method) { continue; } ParameterInfo[] paramInfo = mis[iCtor].GetParameters(); // Check if enough parameters are provided. if (paramInfo.Length > pairs.Length) { continue; } foundConstructor = true; for (int i = 0; i < pairs.Length && foundConstructor; i++) { NameValuePair pair = pairs[i]; // anonymous if (pair._name == null) { values[i] = pair._value; } else { bool foundParameter = false; for (int j = 0; j < paramInfo.Length; j++) { if (paramInfo[j].Name == pair._name) { values[j] = ParseValue(paramInfo[j].ParameterType, pair._value); foundParameter = true; break; } } if (!foundParameter) { foundConstructor = false; } } } } if (!foundConstructor) { throw new FormatException(SR.Get(SRID.CantFindAConstructor, grammar, rule, FormatConstructorParameters(mis, method))); } return values; } /// <summary> /// Parse the value for a type from a string to a strong type. /// If the type does not support the Parse method then the operation fails. /// </summary> private static object ParseValue(Type type, string value) { if (type == typeof(string)) { return value; } return type.InvokeMember("Parse", BindingFlags.InvokeMethod, null, null, new object[] { value }, CultureInfo.InvariantCulture); } /// <summary> /// Returns the list of the possible parameter names and type for a grammar /// </summary> private static string FormatConstructorParameters(MethodInfo[] cis, string method) { StringBuilder sb = new(); for (int iCtor = 0; iCtor < cis.Length; iCtor++) { if (cis[iCtor].Name == method) { sb.Append(sb.Length > 0 ? " or sapi:parms=\"" : "sapi:parms=\""); ParameterInfo[] pis = cis[iCtor].GetParameters(); for (int i = 0; i < pis.Length; i++) { if (i > 0) { sb.Append(';'); } ParameterInfo pi = pis[i]; sb.Append(pi.Name); sb.Append(':'); sb.Append(pi.ParameterType.Name); } sb.Append('"'); } } return sb.ToString(); } /// <summary> /// Split the init parameter strings into an array of name/values /// The format must be "name:value". If the ':' then parameter is anonymous. /// </summary> private static NameValuePair[] ParseInitParams(string initParameters) { string[] parameters = initParameters.Split(new char[] { ';' }, StringSplitOptions.None); NameValuePair[] pairs = new NameValuePair[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { string parameter = parameters[i]; int posColon = parameter.IndexOf(':'); if (posColon >= 0) { pairs[i]._name = parameter.Substring(0, posColon); pairs[i]._value = parameter.Substring(posColon + 1); } else { pairs[i]._value = parameter; } } return pairs; } #pragma warning disable 56524 // Arclist does not hold on any resources private System.Speech.Recognition.Grammar _grammar; #pragma warning restore 56524 // Arclist does not hold on any resources private Assembly _assembly; private string _rule; private Type _grammarType; private struct NameValuePair { internal string _name; internal string _value; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #region Using directives using System.Globalization; using System.Reflection; using System.Speech.Recognition.SrgsGrammar; using System.Text; #endregion #pragma warning disable 56500 // Remove all the catch all statements warnings used by the interop layer namespace System.Speech.Internal.SrgsCompiler { internal class AppDomainGrammarProxy : MarshalByRefObject { internal SrgsRule[] OnInit(string method, object[] parameters, string onInitParameters, out Exception exceptionThrown) { exceptionThrown = null; try { // If the onInitParameters are provided as a string, get the values as an array of value. if (!string.IsNullOrEmpty(onInitParameters)) { parameters = MatchInitParameters(method, onInitParameters, _rule, _rule); } // Find the constructor to call - there could be several Type[] types = new Type[parameters != null ? parameters.Length : 0]; if (parameters != null) { for (int i = 0; i < parameters.Length; i++) { types[i] = parameters[i].GetType(); } } MethodInfo onInit = _grammarType.GetMethod(method, types); // If somehow we failed to find a constructor, let the system handle it if (onInit == null) { throw new InvalidOperationException(SR.Get(SRID.ArgumentMismatch)); } SrgsRule[] extraRules = null; if (onInit != null) { extraRules = (SrgsRule[])onInit.Invoke(_grammar, parameters); } return extraRules; } catch (Exception e) { exceptionThrown = e; return null; } } internal object OnRecognition(string method, object[] parameters, out Exception exceptionThrown) { exceptionThrown = null; try { MethodInfo onRecognition = _grammarType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); // Execute the parse routine return onRecognition.Invoke(_grammar, parameters); } catch (Exception e) { exceptionThrown = e; } return null; } internal object OnParse(string rule, string method, object[] parameters, out Exception exceptionThrown) { exceptionThrown = null; try { MethodInfo onParse; System.Speech.Recognition.Grammar grammar; GetRuleInstance(rule, method, out onParse, out grammar); // Execute the parse routine return onParse.Invoke(grammar, parameters); } catch (Exception e) { exceptionThrown = e; return null; } } internal void OnError(string rule, string method, object[] parameters, out Exception exceptionThrown) { exceptionThrown = null; try { MethodInfo onError; System.Speech.Recognition.Grammar grammar; GetRuleInstance(rule, method, out onError, out grammar); // Execute the parse routine onError.Invoke(grammar, parameters); } catch (Exception e) { exceptionThrown = e; } } internal void Init(string rule, byte[] il, byte[] pdb) { _assembly = Assembly.Load(il, pdb); // Get the grammar class carrying the .NET Semantics code _grammarType = GetTypeForRule(_assembly, rule); // Something is Wrong if the grammar class cannot be found if (_grammarType == null) { throw new FormatException(SR.Get(SRID.RecognizerRuleNotFoundStream, rule)); } _rule = rule; try { _grammar = (System.Speech.Recognition.Grammar)_assembly.CreateInstance(_grammarType.FullName); } catch (MissingMemberException) { throw new ArgumentException(SR.Get(SRID.RuleScriptInvalidParameters, _grammarType.FullName, rule), nameof(rule)); } } private void GetRuleInstance(string rule, string method, out MethodInfo onParse, out System.Speech.Recognition.Grammar grammar) { Type ruleClass = rule == _rule ? _grammarType : GetTypeForRule(_assembly, rule); if (ruleClass == null || !ruleClass.IsSubclassOf(typeof(System.Speech.Recognition.Grammar))) { throw new FormatException(SR.Get(SRID.RecognizerInvalidBinaryGrammar)); } try { grammar = ruleClass == _grammarType ? _grammar : (System.Speech.Recognition.Grammar)_assembly.CreateInstance(ruleClass.FullName); } catch (MissingMemberException) { throw new ArgumentException(SR.Get(SRID.RuleScriptInvalidParameters, ruleClass.FullName, rule), nameof(rule)); } onParse = grammar.MethodInfo(method); } private static Type GetTypeForRule(Assembly assembly, string rule) { Type[] types = assembly.GetTypes(); for (int iType = 0; iType < types.Length; iType++) { Type type = types[iType]; if (type.Name == rule && type.IsPublic && type.IsSubclassOf(typeof(System.Speech.Recognition.Grammar))) { return type; } } return null; } /// <summary> /// Construct a list of parameters from a sapi:params string. /// </summary> private object[] MatchInitParameters(string method, string onInitParameters, string grammar, string rule) { MethodInfo[] mis = _grammarType.GetMethods(); NameValuePair[] pairs = ParseInitParams(onInitParameters); object[] values = new object[pairs.Length]; bool foundConstructor = false; for (int iCtor = 0; iCtor < mis.Length && !foundConstructor; iCtor++) { if (mis[iCtor].Name != method) { continue; } ParameterInfo[] paramInfo = mis[iCtor].GetParameters(); // Check if enough parameters are provided. if (paramInfo.Length > pairs.Length) { continue; } foundConstructor = true; for (int i = 0; i < pairs.Length && foundConstructor; i++) { NameValuePair pair = pairs[i]; // anonymous if (pair._name == null) { values[i] = pair._value; } else { bool foundParameter = false; for (int j = 0; j < paramInfo.Length; j++) { if (paramInfo[j].Name == pair._name) { values[j] = ParseValue(paramInfo[j].ParameterType, pair._value); foundParameter = true; break; } } if (!foundParameter) { foundConstructor = false; } } } } if (!foundConstructor) { throw new FormatException(SR.Get(SRID.CantFindAConstructor, grammar, rule, FormatConstructorParameters(mis, method))); } return values; } /// <summary> /// Parse the value for a type from a string to a strong type. /// If the type does not support the Parse method then the operation fails. /// </summary> private static object ParseValue(Type type, string value) { if (type == typeof(string)) { return value; } return type.InvokeMember("Parse", BindingFlags.InvokeMethod, null, null, new object[] { value }, CultureInfo.InvariantCulture); } /// <summary> /// Returns the list of the possible parameter names and type for a grammar /// </summary> private static string FormatConstructorParameters(MethodInfo[] cis, string method) { StringBuilder sb = new(); for (int iCtor = 0; iCtor < cis.Length; iCtor++) { if (cis[iCtor].Name == method) { sb.Append(sb.Length > 0 ? " or sapi:parms=\"" : "sapi:parms=\""); ParameterInfo[] pis = cis[iCtor].GetParameters(); for (int i = 0; i < pis.Length; i++) { if (i > 0) { sb.Append(';'); } ParameterInfo pi = pis[i]; sb.Append(pi.Name); sb.Append(':'); sb.Append(pi.ParameterType.Name); } sb.Append('"'); } } return sb.ToString(); } /// <summary> /// Split the init parameter strings into an array of name/values /// The format must be "name:value". If the ':' then parameter is anonymous. /// </summary> private static NameValuePair[] ParseInitParams(string initParameters) { string[] parameters = initParameters.Split(new char[] { ';' }, StringSplitOptions.None); NameValuePair[] pairs = new NameValuePair[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { string parameter = parameters[i]; int posColon = parameter.IndexOf(':'); if (posColon >= 0) { pairs[i]._name = parameter.Substring(0, posColon); pairs[i]._value = parameter.Substring(posColon + 1); } else { pairs[i]._value = parameter; } } return pairs; } #pragma warning disable 56524 // Arclist does not hold on any resources private System.Speech.Recognition.Grammar _grammar; #pragma warning restore 56524 // Arclist does not hold on any resources private Assembly _assembly; private string _rule; private Type _grammarType; private struct NameValuePair { internal string _name; internal string _value; } } }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/IPartImportsSatisfiedNotification.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.Composition { public interface IPartImportsSatisfiedNotification { void OnImportsSatisfied(); } }
// 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.Composition { public interface IPartImportsSatisfiedNotification { void OnImportsSatisfied(); } }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewArrayExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Runtime.CompilerServices; namespace System.Linq.Expressions { /// <summary> /// Represents creating a new array and possibly initializing the elements of the new array. /// </summary> [DebuggerTypeProxy(typeof(NewArrayExpressionProxy))] public class NewArrayExpression : Expression { internal NewArrayExpression(Type type, ReadOnlyCollection<Expression> expressions) { Expressions = expressions; Type = type; } internal static NewArrayExpression Make(ExpressionType nodeType, Type type, ReadOnlyCollection<Expression> expressions) { Debug.Assert(type.IsArray); if (nodeType == ExpressionType.NewArrayInit) { return new NewArrayInitExpression(type, expressions); } else { return new NewArrayBoundsExpression(type, expressions); } } /// <summary> /// Gets the static type of the expression that this <see cref="Expression"/> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="System.Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get; } /// <summary> /// Gets the bounds of the array if the value of the <see cref="ExpressionType"/> property is NewArrayBounds, or the values to initialize the elements of the new array if the value of the <see cref="Expression.NodeType"/> property is NewArrayInit. /// </summary> public ReadOnlyCollection<Expression> Expressions { get; } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitNewArray(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="expressions">The <see cref="Expressions"/> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public NewArrayExpression Update(IEnumerable<Expression> expressions) { // Explicit null check here as otherwise wrong parameter name will be used. ContractUtils.RequiresNotNull(expressions, nameof(expressions)); if (ExpressionUtils.SameElements(ref expressions!, Expressions)) { return this; } return NodeType == ExpressionType.NewArrayInit ? NewArrayInit(Type.GetElementType()!, expressions) : NewArrayBounds(Type.GetElementType()!, expressions); } } internal sealed class NewArrayInitExpression : NewArrayExpression { internal NewArrayInitExpression(Type type, ReadOnlyCollection<Expression> expressions) : base(type, expressions) { } /// <summary> /// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType => ExpressionType.NewArrayInit; } internal sealed class NewArrayBoundsExpression : NewArrayExpression { internal NewArrayBoundsExpression(Type type, ReadOnlyCollection<Expression> expressions) : base(type, expressions) { } /// <summary> /// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType => ExpressionType.NewArrayBounds; } public partial class Expression { #region NewArrayInit /// <summary> /// Creates a <see cref="NewArrayExpression"/> of the specified type from the provided initializers. /// </summary> /// <param name="type">A Type that represents the element type of the array.</param> /// <param name="initializers">The expressions used to create the array elements.</param> /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayInit"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns> public static NewArrayExpression NewArrayInit(Type type, params Expression[] initializers) { return NewArrayInit(type, (IEnumerable<Expression>)initializers); } /// <summary> /// Creates a <see cref="NewArrayExpression"/> of the specified type from the provided initializers. /// </summary> /// <param name="type">A Type that represents the element type of the array.</param> /// <param name="initializers">The expressions used to create the array elements.</param> /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayInit"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns> public static NewArrayExpression NewArrayInit(Type type, IEnumerable<Expression> initializers) { ContractUtils.RequiresNotNull(type, nameof(type)); ContractUtils.RequiresNotNull(initializers, nameof(initializers)); if (type == typeof(void)) { throw Error.ArgumentCannotBeOfTypeVoid(nameof(type)); } TypeUtils.ValidateType(type, nameof(type)); ReadOnlyCollection<Expression> initializerList = initializers.ToReadOnly(); Expression[]? newList = null; for (int i = 0, n = initializerList.Count; i < n; i++) { Expression expr = initializerList[i]; ExpressionUtils.RequiresCanRead(expr, nameof(initializers), i); if (!TypeUtils.AreReferenceAssignable(type, expr.Type)) { if (!TryQuote(type, ref expr)) { throw Error.ExpressionTypeCannotInitializeArrayType(expr.Type, type); } if (newList == null) { newList = new Expression[initializerList.Count]; for (int j = 0; j < i; j++) { newList[j] = initializerList[j]; } } } if (newList != null) { newList[i] = expr; } } if (newList != null) { initializerList = new TrueReadOnlyCollection<Expression>(newList); } return NewArrayExpression.Make(ExpressionType.NewArrayInit, type.MakeArrayType(), initializerList); } #endregion #region NewArrayBounds /// <summary> /// Creates a <see cref="NewArrayExpression"/> that represents creating an array that has a specified rank. /// </summary> /// <param name="type">A <see cref="System.Type"/> that represents the element type of the array.</param> /// <param name="bounds">An array that contains Expression objects to use to populate the <see cref="NewArrayExpression.Expressions"/> collection.</param> /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayBounds"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns> public static NewArrayExpression NewArrayBounds(Type type, params Expression[] bounds) { return NewArrayBounds(type, (IEnumerable<Expression>)bounds); } /// <summary> /// Creates a <see cref="NewArrayExpression"/> that represents creating an array that has a specified rank. /// </summary> /// <param name="type">A <see cref="System.Type"/> that represents the element type of the array.</param> /// <param name="bounds">An <see cref="IEnumerable{T}"/> that contains <see cref="Expression"/> objects to use to populate the <see cref="NewArrayExpression.Expressions"/> collection.</param> /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayBounds"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns> public static NewArrayExpression NewArrayBounds(Type type, IEnumerable<Expression> bounds) { ContractUtils.RequiresNotNull(type, nameof(type)); ContractUtils.RequiresNotNull(bounds, nameof(bounds)); if (type == typeof(void)) { throw Error.ArgumentCannotBeOfTypeVoid(nameof(type)); } TypeUtils.ValidateType(type, nameof(type)); ReadOnlyCollection<Expression> boundsList = bounds.ToReadOnly(); int dimensions = boundsList.Count; if (dimensions <= 0) throw Error.BoundsCannotBeLessThanOne(nameof(bounds)); for (int i = 0; i < dimensions; i++) { Expression expr = boundsList[i]; ExpressionUtils.RequiresCanRead(expr, nameof(bounds), i); if (!expr.Type.IsInteger()) { throw Error.ArgumentMustBeInteger(nameof(bounds), i); } } Type arrayType; if (dimensions == 1) { //To get a vector, need call Type.MakeArrayType(). //Type.MakeArrayType(1) gives a non-vector array, which will cause type check error. arrayType = type.MakeArrayType(); } else { arrayType = type.MakeArrayType(dimensions); } return NewArrayExpression.Make(ExpressionType.NewArrayBounds, arrayType, boundsList); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Runtime.CompilerServices; namespace System.Linq.Expressions { /// <summary> /// Represents creating a new array and possibly initializing the elements of the new array. /// </summary> [DebuggerTypeProxy(typeof(NewArrayExpressionProxy))] public class NewArrayExpression : Expression { internal NewArrayExpression(Type type, ReadOnlyCollection<Expression> expressions) { Expressions = expressions; Type = type; } internal static NewArrayExpression Make(ExpressionType nodeType, Type type, ReadOnlyCollection<Expression> expressions) { Debug.Assert(type.IsArray); if (nodeType == ExpressionType.NewArrayInit) { return new NewArrayInitExpression(type, expressions); } else { return new NewArrayBoundsExpression(type, expressions); } } /// <summary> /// Gets the static type of the expression that this <see cref="Expression"/> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="System.Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get; } /// <summary> /// Gets the bounds of the array if the value of the <see cref="ExpressionType"/> property is NewArrayBounds, or the values to initialize the elements of the new array if the value of the <see cref="Expression.NodeType"/> property is NewArrayInit. /// </summary> public ReadOnlyCollection<Expression> Expressions { get; } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitNewArray(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="expressions">The <see cref="Expressions"/> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public NewArrayExpression Update(IEnumerable<Expression> expressions) { // Explicit null check here as otherwise wrong parameter name will be used. ContractUtils.RequiresNotNull(expressions, nameof(expressions)); if (ExpressionUtils.SameElements(ref expressions!, Expressions)) { return this; } return NodeType == ExpressionType.NewArrayInit ? NewArrayInit(Type.GetElementType()!, expressions) : NewArrayBounds(Type.GetElementType()!, expressions); } } internal sealed class NewArrayInitExpression : NewArrayExpression { internal NewArrayInitExpression(Type type, ReadOnlyCollection<Expression> expressions) : base(type, expressions) { } /// <summary> /// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType => ExpressionType.NewArrayInit; } internal sealed class NewArrayBoundsExpression : NewArrayExpression { internal NewArrayBoundsExpression(Type type, ReadOnlyCollection<Expression> expressions) : base(type, expressions) { } /// <summary> /// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType => ExpressionType.NewArrayBounds; } public partial class Expression { #region NewArrayInit /// <summary> /// Creates a <see cref="NewArrayExpression"/> of the specified type from the provided initializers. /// </summary> /// <param name="type">A Type that represents the element type of the array.</param> /// <param name="initializers">The expressions used to create the array elements.</param> /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayInit"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns> public static NewArrayExpression NewArrayInit(Type type, params Expression[] initializers) { return NewArrayInit(type, (IEnumerable<Expression>)initializers); } /// <summary> /// Creates a <see cref="NewArrayExpression"/> of the specified type from the provided initializers. /// </summary> /// <param name="type">A Type that represents the element type of the array.</param> /// <param name="initializers">The expressions used to create the array elements.</param> /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayInit"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns> public static NewArrayExpression NewArrayInit(Type type, IEnumerable<Expression> initializers) { ContractUtils.RequiresNotNull(type, nameof(type)); ContractUtils.RequiresNotNull(initializers, nameof(initializers)); if (type == typeof(void)) { throw Error.ArgumentCannotBeOfTypeVoid(nameof(type)); } TypeUtils.ValidateType(type, nameof(type)); ReadOnlyCollection<Expression> initializerList = initializers.ToReadOnly(); Expression[]? newList = null; for (int i = 0, n = initializerList.Count; i < n; i++) { Expression expr = initializerList[i]; ExpressionUtils.RequiresCanRead(expr, nameof(initializers), i); if (!TypeUtils.AreReferenceAssignable(type, expr.Type)) { if (!TryQuote(type, ref expr)) { throw Error.ExpressionTypeCannotInitializeArrayType(expr.Type, type); } if (newList == null) { newList = new Expression[initializerList.Count]; for (int j = 0; j < i; j++) { newList[j] = initializerList[j]; } } } if (newList != null) { newList[i] = expr; } } if (newList != null) { initializerList = new TrueReadOnlyCollection<Expression>(newList); } return NewArrayExpression.Make(ExpressionType.NewArrayInit, type.MakeArrayType(), initializerList); } #endregion #region NewArrayBounds /// <summary> /// Creates a <see cref="NewArrayExpression"/> that represents creating an array that has a specified rank. /// </summary> /// <param name="type">A <see cref="System.Type"/> that represents the element type of the array.</param> /// <param name="bounds">An array that contains Expression objects to use to populate the <see cref="NewArrayExpression.Expressions"/> collection.</param> /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayBounds"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns> public static NewArrayExpression NewArrayBounds(Type type, params Expression[] bounds) { return NewArrayBounds(type, (IEnumerable<Expression>)bounds); } /// <summary> /// Creates a <see cref="NewArrayExpression"/> that represents creating an array that has a specified rank. /// </summary> /// <param name="type">A <see cref="System.Type"/> that represents the element type of the array.</param> /// <param name="bounds">An <see cref="IEnumerable{T}"/> that contains <see cref="Expression"/> objects to use to populate the <see cref="NewArrayExpression.Expressions"/> collection.</param> /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayBounds"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns> public static NewArrayExpression NewArrayBounds(Type type, IEnumerable<Expression> bounds) { ContractUtils.RequiresNotNull(type, nameof(type)); ContractUtils.RequiresNotNull(bounds, nameof(bounds)); if (type == typeof(void)) { throw Error.ArgumentCannotBeOfTypeVoid(nameof(type)); } TypeUtils.ValidateType(type, nameof(type)); ReadOnlyCollection<Expression> boundsList = bounds.ToReadOnly(); int dimensions = boundsList.Count; if (dimensions <= 0) throw Error.BoundsCannotBeLessThanOne(nameof(bounds)); for (int i = 0; i < dimensions; i++) { Expression expr = boundsList[i]; ExpressionUtils.RequiresCanRead(expr, nameof(bounds), i); if (!expr.Type.IsInteger()) { throw Error.ArgumentMustBeInteger(nameof(bounds), i); } } Type arrayType; if (dimensions == 1) { //To get a vector, need call Type.MakeArrayType(). //Type.MakeArrayType(1) gives a non-vector array, which will cause type check error. arrayType = type.MakeArrayType(); } else { arrayType = type.MakeArrayType(dimensions); } return NewArrayExpression.Make(ExpressionType.NewArrayBounds, arrayType, boundsList); } #endregion } }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/HardwareIntrinsics/X86/Avx2_Vector128/Blend.UInt32.85.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 BlendUInt3285() { var test = new ImmBinaryOpTest__BlendUInt3285(); 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(); // 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(); // 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(); } 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 ImmBinaryOpTest__BlendUInt3285 { private struct TestStruct { public Vector128<UInt32> _fld1; public Vector128<UInt32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__BlendUInt3285 testClass) { var result = Avx2.Blend(_fld1, _fld2, 85); 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<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private Vector128<UInt32> _fld1; private Vector128<UInt32> _fld2; private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable; static ImmBinaryOpTest__BlendUInt3285() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public ImmBinaryOpTest__BlendUInt3285() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Blend( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr), 85 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Blend( Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)), 85 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Blend( Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)), 85 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr), (byte)85 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)), (byte)85 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)), (byte)85 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Blend( _clsVar1, _clsVar2, 85 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr); var result = Avx2.Blend(left, right, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.Blend(left, right, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.Blend(left, right, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__BlendUInt3285(); var result = Avx2.Blend(test._fld1, test._fld2, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Blend(_fld1, _fld2, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Blend(test._fld1, test._fld2, 85); 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 RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt32> left, Vector128<UInt32> right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (((85 & (1 << 0)) == 0) ? left[0] : right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (((85 & (1 << i)) == 0) ? left[i] : right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Blend)}<UInt32>(Vector128<UInt32>.85, Vector128<UInt32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void BlendUInt3285() { var test = new ImmBinaryOpTest__BlendUInt3285(); 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(); // 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(); // 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(); } 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 ImmBinaryOpTest__BlendUInt3285 { private struct TestStruct { public Vector128<UInt32> _fld1; public Vector128<UInt32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__BlendUInt3285 testClass) { var result = Avx2.Blend(_fld1, _fld2, 85); 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<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private Vector128<UInt32> _fld1; private Vector128<UInt32> _fld2; private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable; static ImmBinaryOpTest__BlendUInt3285() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public ImmBinaryOpTest__BlendUInt3285() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Blend( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr), 85 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Blend( Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)), 85 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Blend( Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)), 85 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr), (byte)85 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)), (byte)85 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)), (byte)85 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Blend( _clsVar1, _clsVar2, 85 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr); var result = Avx2.Blend(left, right, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.Blend(left, right, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.Blend(left, right, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__BlendUInt3285(); var result = Avx2.Blend(test._fld1, test._fld2, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Blend(_fld1, _fld2, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Blend(test._fld1, test._fld2, 85); 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 RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt32> left, Vector128<UInt32> right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (((85 & (1 << 0)) == 0) ? left[0] : right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (((85 & (1 << i)) == 0) ? left[i] : right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Blend)}<UInt32>(Vector128<UInt32>.85, Vector128<UInt32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/vm/clrvarargs.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //////////////////////////////////////////////////////////////////////////////// // This module contains the implementation of the native methods for the // varargs class(es).. // //////////////////////////////////////////////////////////////////////////////// #ifndef _CLRVARARGS_H_ #define _CLRVARARGS_H_ struct VARARGS { VASigCookie *ArgCookie; SigPointer SigPtr; BYTE *ArgPtr; int RemainingArgs; static DWORD CalcVaListSize(VARARGS *data); static void MarshalToManagedVaList(va_list va, VARARGS *dataout); static void MarshalToUnmanagedVaList(va_list va, DWORD cbVaListSize, const VARARGS *data); }; #endif // _CLRVARARGS_H_
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //////////////////////////////////////////////////////////////////////////////// // This module contains the implementation of the native methods for the // varargs class(es).. // //////////////////////////////////////////////////////////////////////////////// #ifndef _CLRVARARGS_H_ #define _CLRVARARGS_H_ struct VARARGS { VASigCookie *ArgCookie; SigPointer SigPtr; BYTE *ArgPtr; int RemainingArgs; static DWORD CalcVaListSize(VARARGS *data); static void MarshalToManagedVaList(va_list va, VARARGS *dataout); static void MarshalToUnmanagedVaList(va_list va, DWORD cbVaListSize, const VARARGS *data); }; #endif // _CLRVARARGS_H_
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Drawing.Common/src/Resources/System/Drawing/ShieldIcon.ico
 00h ( 00 h^"00%' nMh^(0`wwxxxxw8xxw狋쌌x{xw~~gw||xgn{{xg{hlglx|lv{?vvv{{~v|{{|vv|f{;phfllfl{?l|vvv{{ffswWyYQ37782&"#chxxyy9"2zzzwwy62b67ww9##8xys&677{zwwwyyYz:zzwx97ssxwxwx77:zyx8z7pxw{xxx7xxxxxwxxxw7wxwzzxxwxxwxx{wxwx?w?????( @wxx~苋w|w狋l{|xv|vv{pNvv{lfl{v|g{xwwuuq372b6wxw9#"sgxyr2:{xyy*wzx3w7xxxwxzwxpx{:xxwxvxx8wxwp???( wwphp~Flfpv7?p#copc?px8op/pycwx?(0` |}h~]V ZV ]acf#j)p.m3u7z9zD}F',2!+$9 Z*E4I>S8Wd n>b/uKYT\EY[hlaweckmqz|hxsyGdSgGjQlWqKqWtclamfwu{bvr}jtflhrtąHƊUʓZ̙dӞeĚtԣmժv| .2+ 176%D6#EDyyOAUFm[Ejrrq{ ($+(4 *-4;H9DU_YaafnqqtFNJUR^We_pemhvw{~;3\gD]iuhvuAEGRvfjxƛ{ˡ\wKBRymu}x'7=lWKUfsK\gwȧݶdz㼌˶չŗǛˤͥӫڵڷѩ̻ԻÖ=+A@οʟAͿJAͽJIHFAIHFEDCIIFDDCBxIFDDCB<wEEDCB <?ECB <EC <EC  ;GC   (E  (C (yֺC 'C 'z> ֺ> vWVUQQPPPPPPLLR "{|ˬmqheecbbaaaaadK%6:*ֺmkjh_c]]\[[[[aK/9-Ylkjjh_]]\\[[[aK/9-Yljpjpo`]\\[[[aK%168ֻYmkjpqpph_]\[[aO%199:::7msjqqqqpoh_][aO!01499665uskkrrrqqpohf_S!004446/&$lsttrqqponX.0!!!033341/##$uuْؓtrrq|||||42/$#$ۓ}7&&&۔Ɗ}7&&&Ɗ}7&&)TƉ}75))ձƊ}5,ֺƊ,ֲƊ}~񺩺ִƊ,~}Z،~,ָ?????( @V/oY6t Im KsU}gDwrNxV Z\^abe"f!l*l0q1s5u8y9{;|D~C '+$8,B4J2N9UMYXfBdTfHlUmWxfvx~gw_€FƇNƊPČ[ȏZǑ]ɒ[ϝeЛcդnϥzѦuҬ}حz*i)t !)&0 '19:DU]WadiITR]Wdajftw{i $GKXyjxd{WCzxŚ|ˢp̲}yikvz -/0<~MZXELS\ia{jbqA_kq|߷ӳϷӲ⺊ÕǜͣƣѩĽײ޺ëʴìŭ˸ژf~yq𭛚:6}}z:653.wwwtg853/vvvvr73.vwvvwsڔ3-vw}x|e1 [npv{۔ݛ Wlnp0 Vklmuݝ Vijlpّ, UiikoQ<RRST^b͖cNG@DCBBBB%+”ݲcNHGE?>>>B'YڒcNHHK@?>BB!'+Zے﮶JMMMLGE>B!$'+++ݒONOOMMHGF; !&&('%#*݇cPhhhOOMM](((((((%"*އhhdaZY)#*އȥaa`Y##ݒﴳԼʩ`YY)ݒ˩aaYڔԼ˥\㒇`嘓㱷Z‡???( \bgfg!lU.E8NKPLZAfOg_a}2>26GYev<wϚyϛp%1:Ѫ% !!1>>9%!9:>>%&,>0>7 $>0>,&!:0>!&>0:)&<0:)!< :$ : :!:. >! :.- >!&4>>./ >>9$* *> >1! )%5>>:&%* &4?(0` %   "###!  JJK"󏏐eefN#S7776 ˶fz|M__`J! °uڶĚ;iKAhhiQ!  rǜ•潎ǴpuuAWWXF  xǚ໊߶|jmmtM++,4 ltݶٯ|תu֤n؝d_a`_gR(;r޹٭xզoџgΙa͓ZϋNTUTST^B& FFGħծ{ԧpџf͗]ɑVNjPņI}>MONMLNZ3" ͷѦsҡj͘_ʑWƋNąHC|=u2zKMMKJKNX;HHI>IǛhϛeʑWƋOÅHB|<x9u4n(tNONMNNNVWf&  h͘bȋRąIB|=x9v4s1p.i"pIMQRRTVYeI vˬ͘dƊQD}>x9u5q1o-m*k'el=CJPV[adksE''(0  ő^ŊS~Cy;u6s1p.m)k(i%g#ai-6>GR^ipv~l!ĚtȍX~Cv9r3o/n+l)i%g"f"c_~g(2;HZkzR3333  ȏ]Gt8p2m-k*i&h$e!dc`\we%/>Pg}~dʢƇSu<o2l-i)g%f"dba_]Yrc$2F^y\))*-Ƌ\zDo4j-h(g&e"c b`_][V nb ';SqmmoS !չdžUr:j/g)f%e"ca_]][YS j` 0Jhg{z{o{Hk4f,d'c%c!a`_][YVPg}_ (A`v##$)~~ϻi{Jf(d"dddccb`][ X Qi[ "9X}MMN<:~m[UFOAH:A3=-8(5%4"3!213#EV [ _bf n/uD[tŲ̂ԴؾѸssuW qxZe7F/&  +||"!+-8<GNZamuÒȝѩmq ptagW`9F,"   .#'/$8/D>SPddtwĔțͥsy pqnq]dW`U`>J,    /&+2';2G@UQectsĕřtz qqnq]cU_T_T`ER(4     0$+1#9+B5MBYQg`uoyu{!vvrt`dW`UaSbTbNY:E$+  3",4!:(A0J9TD_Qj]tg|oq~s}lt!vwdh[bWdWfUeTcR_KT8@$+ 7,!6%?)E.K6T>]HeQnZu`wcvcrdncj"{|gj^f^j`o`r^oXhUbR\JS>F-4D%8&B+J0Q7W=_EgLmSrYuZsZnXgVb[b"nphnkuo}qoj{brZiVbR^MXFNEjKbDb?b>b@fDkIpNsRtSrRlOeL[IUSZξ"|y{wnfw_p[kXe\jigecbab_[zWqRiM^KWV^ο"}slf{jv͗w˛wʞyʟyʠyʟxȞvřsmhbw\mYg^i"xyب֫խԬӫѨ}̣yǜtngau[kYf^g!߸ݹ۶رԭΦ|Ȟvohbt]k^hai yyݺٴԮΦ}Ǟuokhwdpclfl ܺشҬˤ|ěxqdtjv 򟟟ܹٶӯΧȠ|au "m֟޷ٳձҫ˦ȡjuﭭR!iؚԪϧͥʣ}i}NEʓ˞ǝȟrppp&M髫ŖŚl~uuv/q{~}ulya Viii+ߡ&&& 葑˄@????( @  [[\Mhhh^^^\\]aaabbbw()))-HHHY  )))1εױj]]^j ''(*ĮԷ㺊pg}QQQb&&'̷׷ݷ٭yڥoĽdd`+++Pƭӭ{եoϜc˒YˉLRQQSs!!!7``aQΦuПh˓YƋN‚Ez9MLKNMyyz" 888.ͦ{˒ZʼnMB{;u4n*}MNOPT[WXXxӵȑ[ƒF|=v6r0n+h!uDMSZ_gi# '''!ŌW~Du6q0m*j&g#bd.=Jap|{onooopҭGs6m-k)h$e c^X,<Zu$$%4 8882ŊZq6k-g&e"b`]YL )Jm``atnno`ձ{Fj.g'e"b_][UG<aRRR `o8d'c"ba_\XRE.S !% aabhtNzmIxdAv_<uZ8sW5rU2oW-m(u &Bo̶DDE; jija}ck8F,  Hm#%37FUco{ĕͣddekgff~ciS];G$   Kp&.)>:OVin~ÓƛllmdcdchU_S`BO'2  Ou#0"9/H>WUlg{w|qqqccchkXaUdSbLY7? ' U|/#=*E6SC`To_wgxhtnnn`_`orajdqev_pWePZ@I/4+l0J2S8ZAeJmTsWqUhR_zlll^^^|~t{y~zm~brYhS_X]zY|W}XZY{VrOdKXw}kjk___xnrzϟ{ͣ{ͣzˡwƛqi_sYh}mlmbabܲٴװѩ|ɟsj_q\hoooaaa޼ڶѪ~ȟskmzpppjijnֲܹͦ}Úommnuhgh'mllaþװѫʣ|||qqqufffD222YYY\ˠě㋋4344 ~~X}ưzz{444777'bbcV !i򄄄555*  8896222S000V666K??(  @2zhhj,xxz{hhjlU<llnTyyzlU}<hhj}}ba}f1<lU}g!\1%<lU}gb\1:<lU}\\\11<GYev.E.E.ELZKPGYev2>.E.E.EOgKPGYev26.E8NAfSuKPGYGYpp8NwϚw˟KPKP||~GYpwϚKPhhjssu쳳GYGYKPKPhhjRhhj1xhhj@튊󪪫
 00h ( 00 h^"00%' nMh^(0`wwxxxxw8xxw狋쌌x{xw~~gw||xgn{{xg{hlglx|lv{?vvv{{~v|{{|vv|f{;phfllfl{?l|vvv{{ffswWyYQ37782&"#chxxyy9"2zzzwwy62b67ww9##8xys&677{zwwwyyYz:zzwx97ssxwxwx77:zyx8z7pxw{xxx7xxxxxwxxxw7wxwzzxxwxxwxx{wxwx?w?????( @wxx~苋w|w狋l{|xv|vv{pNvv{lfl{v|g{xwwuuq372b6wxw9#"sgxyr2:{xyy*wzx3w7xxxwxzwxpx{:xxwxvxx8wxwp???( wwphp~Flfpv7?p#copc?px8op/pycwx?(0` |}h~]V ZV ]acf#j)p.m3u7z9zD}F',2!+$9 Z*E4I>S8Wd n>b/uKYT\EY[hlaweckmqz|hxsyGdSgGjQlWqKqWtclamfwu{bvr}jtflhrtąHƊUʓZ̙dӞeĚtԣmժv| .2+ 176%D6#EDyyOAUFm[Ejrrq{ ($+(4 *-4;H9DU_YaafnqqtFNJUR^We_pemhvw{~;3\gD]iuhvuAEGRvfjxƛ{ˡ\wKBRymu}x'7=lWKUfsK\gwȧݶdz㼌˶չŗǛˤͥӫڵڷѩ̻ԻÖ=+A@οʟAͿJAͽJIHFAIHFEDCIIFDDCBxIFDDCB<wEEDCB <?ECB <EC <EC  ;GC   (E  (C (yֺC 'C 'z> ֺ> vWVUQQPPPPPPLLR "{|ˬmqheecbbaaaaadK%6:*ֺmkjh_c]]\[[[[aK/9-Ylkjjh_]]\\[[[aK/9-Yljpjpo`]\\[[[aK%168ֻYmkjpqpph_]\[[aO%199:::7msjqqqqpoh_][aO!01499665uskkrrrqqpohf_S!004446/&$lsttrqqponX.0!!!033341/##$uuْؓtrrq|||||42/$#$ۓ}7&&&۔Ɗ}7&&&Ɗ}7&&)TƉ}75))ձƊ}5,ֺƊ,ֲƊ}~񺩺ִƊ,~}Z،~,ָ?????( @V/oY6t Im KsU}gDwrNxV Z\^abe"f!l*l0q1s5u8y9{;|D~C '+$8,B4J2N9UMYXfBdTfHlUmWxfvx~gw_€FƇNƊPČ[ȏZǑ]ɒ[ϝeЛcդnϥzѦuҬ}حz*i)t !)&0 '19:DU]WadiITR]Wdajftw{i $GKXyjxd{WCzxŚ|ˢp̲}yikvz -/0<~MZXELS\ia{jbqA_kq|߷ӳϷӲ⺊ÕǜͣƣѩĽײ޺ëʴìŭ˸ژf~yq𭛚:6}}z:653.wwwtg853/vvvvr73.vwvvwsڔ3-vw}x|e1 [npv{۔ݛ Wlnp0 Vklmuݝ Vijlpّ, UiikoQ<RRST^b͖cNG@DCBBBB%+”ݲcNHGE?>>>B'YڒcNHHK@?>BB!'+Zے﮶JMMMLGE>B!$'+++ݒONOOMMHGF; !&&('%#*݇cPhhhOOMM](((((((%"*އhhdaZY)#*އȥaa`Y##ݒﴳԼʩ`YY)ݒ˩aaYڔԼ˥\㒇`嘓㱷Z‡???( \bgfg!lU.E8NKPLZAfOg_a}2>26GYev<wϚyϛp%1:Ѫ% !!1>>9%!9:>>%&,>0>7 $>0>,&!:0>!&>0:)&<0:)!< :$ : :!:. >! :.- >!&4>>./ >>9$* *> >1! )%5>>:&%* &4?(0` %   "###!  JJK"󏏐eefN#S7776 ˶fz|M__`J! °uڶĚ;iKAhhiQ!  rǜ•潎ǴpuuAWWXF  xǚ໊߶|jmmtM++,4 ltݶٯ|תu֤n؝d_a`_gR(;r޹٭xզoџgΙa͓ZϋNTUTST^B& FFGħծ{ԧpџf͗]ɑVNjPņI}>MONMLNZ3" ͷѦsҡj͘_ʑWƋNąHC|=u2zKMMKJKNX;HHI>IǛhϛeʑWƋOÅHB|<x9u4n(tNONMNNNVWf&  h͘bȋRąIB|=x9v4s1p.i"pIMQRRTVYeI vˬ͘dƊQD}>x9u5q1o-m*k'el=CJPV[adksE''(0  ő^ŊS~Cy;u6s1p.m)k(i%g#ai-6>GR^ipv~l!ĚtȍX~Cv9r3o/n+l)i%g"f"c_~g(2;HZkzR3333  ȏ]Gt8p2m-k*i&h$e!dc`\we%/>Pg}~dʢƇSu<o2l-i)g%f"dba_]Yrc$2F^y\))*-Ƌ\zDo4j-h(g&e"c b`_][V nb ';SqmmoS !չdžUr:j/g)f%e"ca_]][YS j` 0Jhg{z{o{Hk4f,d'c%c!a`_][YVPg}_ (A`v##$)~~ϻi{Jf(d"dddccb`][ X Qi[ "9X}MMN<:~m[UFOAH:A3=-8(5%4"3!213#EV [ _bf n/uD[tŲ̂ԴؾѸssuW qxZe7F/&  +||"!+-8<GNZamuÒȝѩmq ptagW`9F,"   .#'/$8/D>SPddtwĔțͥsy pqnq]dW`U`>J,    /&+2';2G@UQectsĕřtz qqnq]cU_T_T`ER(4     0$+1#9+B5MBYQg`uoyu{!vvrt`dW`UaSbTbNY:E$+  3",4!:(A0J9TD_Qj]tg|oq~s}lt!vwdh[bWdWfUeTcR_KT8@$+ 7,!6%?)E.K6T>]HeQnZu`wcvcrdncj"{|gj^f^j`o`r^oXhUbR\JS>F-4D%8&B+J0Q7W=_EgLmSrYuZsZnXgVb[b"nphnkuo}qoj{brZiVbR^MXFNEjKbDb?b>b@fDkIpNsRtSrRlOeL[IUSZξ"|y{wnfw_p[kXe\jigecbab_[zWqRiM^KWV^ο"}slf{jv͗w˛wʞyʟyʠyʟxȞvřsmhbw\mYg^i"xyب֫խԬӫѨ}̣yǜtngau[kYf^g!߸ݹ۶رԭΦ|Ȟvohbt]k^hai yyݺٴԮΦ}Ǟuokhwdpclfl ܺشҬˤ|ěxqdtjv 򟟟ܹٶӯΧȠ|au "m֟޷ٳձҫ˦ȡjuﭭR!iؚԪϧͥʣ}i}NEʓ˞ǝȟrppp&M髫ŖŚl~uuv/q{~}ulya Viii+ߡ&&& 葑˄@????( @  [[\Mhhh^^^\\]aaabbbw()))-HHHY  )))1εױj]]^j ''(*ĮԷ㺊pg}QQQb&&'̷׷ݷ٭yڥoĽdd`+++Pƭӭ{եoϜc˒YˉLRQQSs!!!7``aQΦuПh˓YƋN‚Ez9MLKNMyyz" 888.ͦ{˒ZʼnMB{;u4n*}MNOPT[WXXxӵȑ[ƒF|=v6r0n+h!uDMSZ_gi# '''!ŌW~Du6q0m*j&g#bd.=Jap|{onooopҭGs6m-k)h$e c^X,<Zu$$%4 8882ŊZq6k-g&e"b`]YL )Jm``atnno`ձ{Fj.g'e"b_][UG<aRRR `o8d'c"ba_\XRE.S !% aabhtNzmIxdAv_<uZ8sW5rU2oW-m(u &Bo̶DDE; jija}ck8F,  Hm#%37FUco{ĕͣddekgff~ciS];G$   Kp&.)>:OVin~ÓƛllmdcdchU_S`BO'2  Ou#0"9/H>WUlg{w|qqqccchkXaUdSbLY7? ' U|/#=*E6SC`To_wgxhtnnn`_`orajdqev_pWePZ@I/4+l0J2S8ZAeJmTsWqUhR_zlll^^^|~t{y~zm~brYhS_X]zY|W}XZY{VrOdKXw}kjk___xnrzϟ{ͣ{ͣzˡwƛqi_sYh}mlmbabܲٴװѩ|ɟsj_q\hoooaaa޼ڶѪ~ȟskmzpppjijnֲܹͦ}Úommnuhgh'mllaþװѫʣ|||qqqufffD222YYY\ˠě㋋4344 ~~X}ưzz{444777'bbcV !i򄄄555*  8896222S000V666K??(  @2zhhj,xxz{hhjlU<llnTyyzlU}<hhj}}ba}f1<lU}g!\1%<lU}gb\1:<lU}\\\11<GYev.E.E.ELZKPGYev2>.E.E.EOgKPGYev26.E8NAfSuKPGYGYpp8NwϚw˟KPKP||~GYpwϚKPhhjssu쳳GYGYKPKPhhjRhhj1xhhj@튊󪪫
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObjectSequence.netfx.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.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Diagnostics.Metrics { internal interface IObjectSequence { object? this[int i] { get; set; } } internal partial struct ObjectSequence1 : IEquatable<ObjectSequence1>, IObjectSequence { public object? this[int i] { get { if (i == 0) { return Value1; } throw new IndexOutOfRangeException(); } set { if (i == 0) { Value1 = value; } else { throw new IndexOutOfRangeException(); } } } } internal partial struct ObjectSequence2 : IEquatable<ObjectSequence2>, IObjectSequence { public object? this[int i] { get { if (i == 0) { return Value1; } else if (i == 1) { return Value2; } throw new IndexOutOfRangeException(); } set { if (i == 0) { Value1 = value; } else if (i == 1) { Value2 = value; } else { throw new IndexOutOfRangeException(); } } } // this isn't exactly identical to the netcore algorithm, but good enough public override int GetHashCode() => (Value1?.GetHashCode() ?? 0) ^ (Value2?.GetHashCode() ?? 0 << 3); } internal partial struct ObjectSequence3 : IEquatable<ObjectSequence3>, IObjectSequence { public object? this[int i] { get { if (i == 0) { return Value1; } else if (i == 1) { return Value2; } else if (i == 2) { return Value3; } throw new IndexOutOfRangeException(); } set { if (i == 0) { Value1 = value; } else if (i == 1) { Value2 = value; } else if (i == 2) { Value3 = value; } else { throw new IndexOutOfRangeException(); } } } // this isn't exactly identical to the netcore algorithm, but good enough public override int GetHashCode() => (Value1?.GetHashCode() ?? 0) ^ (Value2?.GetHashCode() ?? 0 << 3) ^ (Value3?.GetHashCode() ?? 0 << 6); } internal partial struct ObjectSequenceMany : IEquatable<ObjectSequenceMany>, IObjectSequence { public object? this[int i] { get { return _values[i]; } set { _values[i] = value; } } public override int GetHashCode() { int hash = 0; for (int i = 0; i < _values.Length; i++) { // this isn't exactly identical to the netcore algorithm, but good enough hash <<= 3; object? value = _values[i]; if (value != null) { hash ^= value.GetHashCode(); } } return hash; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Diagnostics.Metrics { internal interface IObjectSequence { object? this[int i] { get; set; } } internal partial struct ObjectSequence1 : IEquatable<ObjectSequence1>, IObjectSequence { public object? this[int i] { get { if (i == 0) { return Value1; } throw new IndexOutOfRangeException(); } set { if (i == 0) { Value1 = value; } else { throw new IndexOutOfRangeException(); } } } } internal partial struct ObjectSequence2 : IEquatable<ObjectSequence2>, IObjectSequence { public object? this[int i] { get { if (i == 0) { return Value1; } else if (i == 1) { return Value2; } throw new IndexOutOfRangeException(); } set { if (i == 0) { Value1 = value; } else if (i == 1) { Value2 = value; } else { throw new IndexOutOfRangeException(); } } } // this isn't exactly identical to the netcore algorithm, but good enough public override int GetHashCode() => (Value1?.GetHashCode() ?? 0) ^ (Value2?.GetHashCode() ?? 0 << 3); } internal partial struct ObjectSequence3 : IEquatable<ObjectSequence3>, IObjectSequence { public object? this[int i] { get { if (i == 0) { return Value1; } else if (i == 1) { return Value2; } else if (i == 2) { return Value3; } throw new IndexOutOfRangeException(); } set { if (i == 0) { Value1 = value; } else if (i == 1) { Value2 = value; } else if (i == 2) { Value3 = value; } else { throw new IndexOutOfRangeException(); } } } // this isn't exactly identical to the netcore algorithm, but good enough public override int GetHashCode() => (Value1?.GetHashCode() ?? 0) ^ (Value2?.GetHashCode() ?? 0 << 3) ^ (Value3?.GetHashCode() ?? 0 << 6); } internal partial struct ObjectSequenceMany : IEquatable<ObjectSequenceMany>, IObjectSequence { public object? this[int i] { get { return _values[i]; } set { _values[i] = value; } } public override int GetHashCode() { int hash = 0; for (int i = 0; i < _values.Length; i++) { // this isn't exactly identical to the netcore algorithm, but good enough hash <<= 3; object? value = _values[i]; if (value != null) { hash ^= value.GetHashCode(); } } return hash; } } }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/HardwareIntrinsics/X86/Fma_Vector256/MultiplySubtract.Double.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MultiplySubtractDouble() { var test = new SimpleTernaryOpTest__MultiplySubtractDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplySubtractDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] inArray3, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Double> _fld1; public Vector256<Double> _fld2; public Vector256<Double> _fld3; 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] = 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>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplySubtractDouble testClass) { var result = Fma.MultiplySubtract(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplySubtractDouble testClass) { fixed (Vector256<Double>* pFld1 = &_fld1) fixed (Vector256<Double>* pFld2 = &_fld2) fixed (Vector256<Double>* pFld3 = &_fld3) { var result = Fma.MultiplySubtract( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)), Avx.LoadVector256((Double*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, 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 Op3ElementCount = 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 Double[] _data3 = new Double[Op3ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private static Vector256<Double> _clsVar3; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private Vector256<Double> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplySubtractDouble() { 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] = 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>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); } public SimpleTernaryOpTest__MultiplySubtractDouble() { 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] = 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 < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[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] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, _data3, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Fma.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Fma.MultiplySubtract( Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Fma.MultiplySubtract( Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Fma.MultiplySubtract( Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Fma.MultiplySubtract( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Double>* pClsVar1 = &_clsVar1) fixed (Vector256<Double>* pClsVar2 = &_clsVar2) fixed (Vector256<Double>* pClsVar3 = &_clsVar3) { var result = Fma.MultiplySubtract( Avx.LoadVector256((Double*)(pClsVar1)), Avx.LoadVector256((Double*)(pClsVar2)), Avx.LoadVector256((Double*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray3Ptr); var result = Fma.MultiplySubtract(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)); var op3 = Avx.LoadVector256((Double*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplySubtract(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)); var op3 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplySubtract(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplySubtractDouble(); var result = Fma.MultiplySubtract(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplySubtractDouble(); fixed (Vector256<Double>* pFld1 = &test._fld1) fixed (Vector256<Double>* pFld2 = &test._fld2) fixed (Vector256<Double>* pFld3 = &test._fld3) { var result = Fma.MultiplySubtract( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)), Avx.LoadVector256((Double*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Fma.MultiplySubtract(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Double>* pFld1 = &_fld1) fixed (Vector256<Double>* pFld2 = &_fld2) fixed (Vector256<Double>* pFld3 = &_fld3) { var result = Fma.MultiplySubtract( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)), Avx.LoadVector256((Double*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Fma.MultiplySubtract(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Fma.MultiplySubtract( Avx.LoadVector256((Double*)(&test._fld1)), Avx.LoadVector256((Double*)(&test._fld2)), Avx.LoadVector256((Double*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Double> op1, Vector256<Double> op2, Vector256<Double> op3, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] inArray3 = new Double[Op3ElementCount]; 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.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] inArray3 = new Double[Op3ElementCount]; 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 inArray3[0]), ref Unsafe.AsRef<byte>(op3), (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, inArray3, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] secondOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(Math.Round((firstOp[0] * secondOp[0]) - thirdOp[0], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[0], 9))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(Math.Round((firstOp[i] * secondOp[i]) - thirdOp[i], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[i], 9))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtract)}<Double>(Vector256<Double>, Vector256<Double>, Vector256<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 MultiplySubtractDouble() { var test = new SimpleTernaryOpTest__MultiplySubtractDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplySubtractDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] inArray3, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Double> _fld1; public Vector256<Double> _fld2; public Vector256<Double> _fld3; 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] = 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>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplySubtractDouble testClass) { var result = Fma.MultiplySubtract(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplySubtractDouble testClass) { fixed (Vector256<Double>* pFld1 = &_fld1) fixed (Vector256<Double>* pFld2 = &_fld2) fixed (Vector256<Double>* pFld3 = &_fld3) { var result = Fma.MultiplySubtract( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)), Avx.LoadVector256((Double*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, 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 Op3ElementCount = 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 Double[] _data3 = new Double[Op3ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private static Vector256<Double> _clsVar3; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private Vector256<Double> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplySubtractDouble() { 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] = 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>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); } public SimpleTernaryOpTest__MultiplySubtractDouble() { 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] = 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 < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[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] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, _data3, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Fma.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Fma.MultiplySubtract( Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Fma.MultiplySubtract( Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Fma.MultiplySubtract( Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Fma.MultiplySubtract( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Double>* pClsVar1 = &_clsVar1) fixed (Vector256<Double>* pClsVar2 = &_clsVar2) fixed (Vector256<Double>* pClsVar3 = &_clsVar3) { var result = Fma.MultiplySubtract( Avx.LoadVector256((Double*)(pClsVar1)), Avx.LoadVector256((Double*)(pClsVar2)), Avx.LoadVector256((Double*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray3Ptr); var result = Fma.MultiplySubtract(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)); var op3 = Avx.LoadVector256((Double*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplySubtract(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)); var op3 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplySubtract(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplySubtractDouble(); var result = Fma.MultiplySubtract(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplySubtractDouble(); fixed (Vector256<Double>* pFld1 = &test._fld1) fixed (Vector256<Double>* pFld2 = &test._fld2) fixed (Vector256<Double>* pFld3 = &test._fld3) { var result = Fma.MultiplySubtract( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)), Avx.LoadVector256((Double*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Fma.MultiplySubtract(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Double>* pFld1 = &_fld1) fixed (Vector256<Double>* pFld2 = &_fld2) fixed (Vector256<Double>* pFld3 = &_fld3) { var result = Fma.MultiplySubtract( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)), Avx.LoadVector256((Double*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Fma.MultiplySubtract(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Fma.MultiplySubtract( Avx.LoadVector256((Double*)(&test._fld1)), Avx.LoadVector256((Double*)(&test._fld2)), Avx.LoadVector256((Double*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Double> op1, Vector256<Double> op2, Vector256<Double> op3, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] inArray3 = new Double[Op3ElementCount]; 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.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] inArray3 = new Double[Op3ElementCount]; 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 inArray3[0]), ref Unsafe.AsRef<byte>(op3), (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, inArray3, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] secondOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(Math.Round((firstOp[0] * secondOp[0]) - thirdOp[0], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[0], 9))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(Math.Round((firstOp[i] * secondOp[i]) - thirdOp[i], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[i], 9))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtract)}<Double>(Vector256<Double>, Vector256<Double>, Vector256<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/coreclr/tools/dotnet-pgo/dotnet-pgo.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AssemblyName>dotnet-pgo</AssemblyName> <OutputType>Exe</OutputType> <PlatformTarget>AnyCPU</PlatformTarget> <TargetFramework>$(NetCoreAppToolCurrent)</TargetFramework> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputPath>$(RuntimeBinDir)/dotnet-pgo</OutputPath> <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> <EnableDefaultEmbeddedResourceItems>false</EnableDefaultEmbeddedResourceItems> <RuntimeIdentifiers>linux-x64;linux-musl-x64;win-x64</RuntimeIdentifiers> <IsPackable>true</IsPackable> <PackAsTool>true</PackAsTool> <ToolCommandName>dotnet-pgo</ToolCommandName> <PackAsToolShimRuntimeIdentifiers>win-x64;win-x86;win-arm;osx-x64</PackAsToolShimRuntimeIdentifiers> <PackagedShimOutputRootDirectory>$(OutputPath)</PackagedShimOutputRootDirectory> <IsShipping>false</IsShipping> <!-- This tool is not yet ready to ship, but may do so in the future --> <Description>.NET Performance Guided Optimization Tool</Description> <PackageTags>Optimization</PackageTags> <PackageReleaseNotes>$(Description)</PackageReleaseNotes> <RootNamespace>Microsoft.Diagnostics.Tools.Pgo</RootNamespace> <RollForward>Major</RollForward> </PropertyGroup> <ItemGroup> <Compile Include="..\aot\ILCompiler.ReadyToRun\IBC\MIbcProfileParser.cs" Link="MIbcProfileParser.cs" /> <Compile Include="..\aot\ILCompiler.ReadyToRun\IBC\IBCProfileData.cs" Link="IBCProfileData.cs" /> <Compile Include="..\aot\ILCompiler.ReadyToRun\Compiler\ProfileData.cs" Link="ProfileData.cs" /> <Compile Include="..\Common\Pgo\TypeSystemEntityOrUnknown.cs" Link="TypeSystemEntityOrUnknown.cs" /> <Compile Include="..\Common\TypeSystem\IL\FlowGraph.cs" Link="SPGO\FlowGraph.cs" /> <Compile Include="..\Common\TypeSystem\IL\ILReader.cs" Link="ILReader.cs" /> <Compile Include="..\Common\TypeSystem\MetadataEmitter\TypeSystemMetadataEmitter.cs" Link="TypeSystemMetadataEmitter" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="..\Common\CommandLine\Resources\Strings.resx"> <GenerateSource>true</GenerateSource> <ClassName>Internal.CommandLine.Strings</ClassName> </EmbeddedResource> <Compile Include="..\Common\CommandLine\Argument.cs" Link="CommandLine\Argument.cs" /> <Compile Include="..\Common\CommandLine\Argument_1.cs" Link="CommandLine\Argument_1.cs" /> <Compile Include="..\Common\CommandLine\ArgumentCommand.cs" Link="CommandLine\ArgumentCommand.cs" /> <Compile Include="..\Common\CommandLine\ArgumentCommand_1.cs" Link="CommandLine\ArgumentCommand_1.cs" /> <Compile Include="..\Common\CommandLine\ArgumentLexer.cs" Link="CommandLine\ArgumentLexer.cs" /> <Compile Include="..\Common\CommandLine\ArgumentList_1.cs" Link="CommandLine\ArgumentList_1.cs" /> <Compile Include="..\Common\CommandLine\ArgumentParser.cs" Link="CommandLine\ArgumentParser.cs" /> <Compile Include="..\Common\CommandLine\ArgumentSyntax.cs" Link="CommandLine\ArgumentSyntax.cs" /> <Compile Include="..\Common\CommandLine\ArgumentSyntax_Definers.cs" Link="CommandLine\ArgumentSyntax_Definers.cs" /> <Compile Include="..\Common\CommandLine\ArgumentSyntaxException.cs" Link="CommandLine\ArgumentSyntaxException.cs" /> <Compile Include="..\Common\CommandLine\ArgumentToken.cs" Link="CommandLine\ArgumentToken.cs" /> <Compile Include="..\Common\CommandLine\CommandLineException.cs" Link="CommandLine\CommandLineException.cs" /> <Compile Include="..\Common\CommandLine\CommandLineHelpers.cs" Link="CommandLine\CommandLineHelpers.cs" /> <Compile Include="..\Common\CommandLine\Enumerable.cs" Link="CommandLine\Enumerable.cs" /> <Compile Include="..\Common\CommandLine\HelpTextGenerator.cs" Link="CommandLine\HelpTextGenerator.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="../aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj" /> <ProjectReference Include="../aot/ILCompiler.Reflection.ReadyToRun/ILCompiler.Reflection.ReadyToRun.csproj" /> <PackageReference Include="Microsoft.Diagnostics.Tracing.TraceEvent" Version="$(TraceEventVersion)" /> <PackageReference Include="System.Reflection.Metadata" Version="$(SystemReflectionMetadataVersion)" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AssemblyName>dotnet-pgo</AssemblyName> <OutputType>Exe</OutputType> <PlatformTarget>AnyCPU</PlatformTarget> <TargetFramework>$(NetCoreAppToolCurrent)</TargetFramework> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputPath>$(RuntimeBinDir)/dotnet-pgo</OutputPath> <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> <EnableDefaultEmbeddedResourceItems>false</EnableDefaultEmbeddedResourceItems> <RuntimeIdentifiers>linux-x64;linux-musl-x64;win-x64</RuntimeIdentifiers> <IsPackable>true</IsPackable> <PackAsTool>true</PackAsTool> <ToolCommandName>dotnet-pgo</ToolCommandName> <PackAsToolShimRuntimeIdentifiers>win-x64;win-x86;win-arm;osx-x64</PackAsToolShimRuntimeIdentifiers> <PackagedShimOutputRootDirectory>$(OutputPath)</PackagedShimOutputRootDirectory> <IsShipping>false</IsShipping> <!-- This tool is not yet ready to ship, but may do so in the future --> <Description>.NET Performance Guided Optimization Tool</Description> <PackageTags>Optimization</PackageTags> <PackageReleaseNotes>$(Description)</PackageReleaseNotes> <RootNamespace>Microsoft.Diagnostics.Tools.Pgo</RootNamespace> <RollForward>Major</RollForward> </PropertyGroup> <ItemGroup> <Compile Include="..\aot\ILCompiler.ReadyToRun\IBC\MIbcProfileParser.cs" Link="MIbcProfileParser.cs" /> <Compile Include="..\aot\ILCompiler.ReadyToRun\IBC\IBCProfileData.cs" Link="IBCProfileData.cs" /> <Compile Include="..\aot\ILCompiler.ReadyToRun\Compiler\ProfileData.cs" Link="ProfileData.cs" /> <Compile Include="..\Common\Pgo\TypeSystemEntityOrUnknown.cs" Link="TypeSystemEntityOrUnknown.cs" /> <Compile Include="..\Common\TypeSystem\IL\FlowGraph.cs" Link="SPGO\FlowGraph.cs" /> <Compile Include="..\Common\TypeSystem\IL\ILReader.cs" Link="ILReader.cs" /> <Compile Include="..\Common\TypeSystem\MetadataEmitter\TypeSystemMetadataEmitter.cs" Link="TypeSystemMetadataEmitter" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="..\Common\CommandLine\Resources\Strings.resx"> <GenerateSource>true</GenerateSource> <ClassName>Internal.CommandLine.Strings</ClassName> </EmbeddedResource> <Compile Include="..\Common\CommandLine\Argument.cs" Link="CommandLine\Argument.cs" /> <Compile Include="..\Common\CommandLine\Argument_1.cs" Link="CommandLine\Argument_1.cs" /> <Compile Include="..\Common\CommandLine\ArgumentCommand.cs" Link="CommandLine\ArgumentCommand.cs" /> <Compile Include="..\Common\CommandLine\ArgumentCommand_1.cs" Link="CommandLine\ArgumentCommand_1.cs" /> <Compile Include="..\Common\CommandLine\ArgumentLexer.cs" Link="CommandLine\ArgumentLexer.cs" /> <Compile Include="..\Common\CommandLine\ArgumentList_1.cs" Link="CommandLine\ArgumentList_1.cs" /> <Compile Include="..\Common\CommandLine\ArgumentParser.cs" Link="CommandLine\ArgumentParser.cs" /> <Compile Include="..\Common\CommandLine\ArgumentSyntax.cs" Link="CommandLine\ArgumentSyntax.cs" /> <Compile Include="..\Common\CommandLine\ArgumentSyntax_Definers.cs" Link="CommandLine\ArgumentSyntax_Definers.cs" /> <Compile Include="..\Common\CommandLine\ArgumentSyntaxException.cs" Link="CommandLine\ArgumentSyntaxException.cs" /> <Compile Include="..\Common\CommandLine\ArgumentToken.cs" Link="CommandLine\ArgumentToken.cs" /> <Compile Include="..\Common\CommandLine\CommandLineException.cs" Link="CommandLine\CommandLineException.cs" /> <Compile Include="..\Common\CommandLine\CommandLineHelpers.cs" Link="CommandLine\CommandLineHelpers.cs" /> <Compile Include="..\Common\CommandLine\Enumerable.cs" Link="CommandLine\Enumerable.cs" /> <Compile Include="..\Common\CommandLine\HelpTextGenerator.cs" Link="CommandLine\HelpTextGenerator.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="../aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj" /> <ProjectReference Include="../aot/ILCompiler.Reflection.ReadyToRun/ILCompiler.Reflection.ReadyToRun.csproj" /> <PackageReference Include="Microsoft.Diagnostics.Tracing.TraceEvent" Version="$(TraceEventVersion)" /> <PackageReference Include="System.Reflection.Metadata" Version="$(SystemReflectionMetadataVersion)" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Net.Http/src/System/Net/Http/ByteArrayContent.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.IO; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { public class ByteArrayContent : HttpContent { private readonly byte[] _content; private readonly int _offset; private readonly int _count; public ByteArrayContent(byte[] content!!) { _content = content; _count = content.Length; } public ByteArrayContent(byte[] content!!, int offset, int count) { if ((offset < 0) || (offset > content.Length)) { throw new ArgumentOutOfRangeException(nameof(offset)); } if ((count < 0) || (count > (content.Length - offset))) { throw new ArgumentOutOfRangeException(nameof(count)); } _content = content; _offset = offset; _count = count; } protected override void SerializeToStream(Stream stream, TransportContext? context, CancellationToken cancellationToken) => stream.Write(_content, _offset, _count); protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) => SerializeToStreamAsyncCore(stream, default); protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken cancellationToken) => // Only skip the original protected virtual SerializeToStreamAsync if this // isn't a derived type that may have overridden the behavior. GetType() == typeof(ByteArrayContent) ? SerializeToStreamAsyncCore(stream, cancellationToken) : base.SerializeToStreamAsync(stream, context, cancellationToken); private protected Task SerializeToStreamAsyncCore(Stream stream, CancellationToken cancellationToken) => stream.WriteAsync(_content, _offset, _count, cancellationToken); protected internal override bool TryComputeLength(out long length) { length = _count; return true; } protected override Stream CreateContentReadStream(CancellationToken cancellationToken) => CreateMemoryStreamForByteArray(); protected override Task<Stream> CreateContentReadStreamAsync() => Task.FromResult<Stream>(CreateMemoryStreamForByteArray()); internal override Stream? TryCreateContentReadStream() => GetType() == typeof(ByteArrayContent) ? CreateMemoryStreamForByteArray() : // type check ensures we use possible derived type's CreateContentReadStreamAsync override null; internal MemoryStream CreateMemoryStreamForByteArray() => new MemoryStream(_content, _offset, _count, writable: false); internal override bool AllowDuplex => 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.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { public class ByteArrayContent : HttpContent { private readonly byte[] _content; private readonly int _offset; private readonly int _count; public ByteArrayContent(byte[] content!!) { _content = content; _count = content.Length; } public ByteArrayContent(byte[] content!!, int offset, int count) { if ((offset < 0) || (offset > content.Length)) { throw new ArgumentOutOfRangeException(nameof(offset)); } if ((count < 0) || (count > (content.Length - offset))) { throw new ArgumentOutOfRangeException(nameof(count)); } _content = content; _offset = offset; _count = count; } protected override void SerializeToStream(Stream stream, TransportContext? context, CancellationToken cancellationToken) => stream.Write(_content, _offset, _count); protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) => SerializeToStreamAsyncCore(stream, default); protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken cancellationToken) => // Only skip the original protected virtual SerializeToStreamAsync if this // isn't a derived type that may have overridden the behavior. GetType() == typeof(ByteArrayContent) ? SerializeToStreamAsyncCore(stream, cancellationToken) : base.SerializeToStreamAsync(stream, context, cancellationToken); private protected Task SerializeToStreamAsyncCore(Stream stream, CancellationToken cancellationToken) => stream.WriteAsync(_content, _offset, _count, cancellationToken); protected internal override bool TryComputeLength(out long length) { length = _count; return true; } protected override Stream CreateContentReadStream(CancellationToken cancellationToken) => CreateMemoryStreamForByteArray(); protected override Task<Stream> CreateContentReadStreamAsync() => Task.FromResult<Stream>(CreateMemoryStreamForByteArray()); internal override Stream? TryCreateContentReadStream() => GetType() == typeof(ByteArrayContent) ? CreateMemoryStreamForByteArray() : // type check ensures we use possible derived type's CreateContentReadStreamAsync override null; internal MemoryStream CreateMemoryStreamForByteArray() => new MemoryStream(_content, _offset, _count, writable: false); internal override bool AllowDuplex => false; } }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Collections/ref/System.Collections.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <Compile Include="System.Collections.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\System.Runtime\ref\System.Runtime.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <Compile Include="System.Collections.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\System.Runtime\ref\System.Runtime.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./docs/design/coreclr/jit/removing-embedded-statements.md
## Removing Embedded Statements From the RyuJIT Backend IR Pat Gavlin ([*[email protected]*](mailto:[email protected])) July 2016 ### Abstract RyuJIT’s IR comes in two forms: that produced and manipulated in the front end and that expected and manipulated by the back end. The boundary between these two forms of IR is comprised of rationalization and lowering, both of which transform the front-end IR into back end IR. For the purposes of this paper, the relevant differences between the two IRs revolve around ordering constructs within basic blocks: top-level statements, trees, comma nodes, and embedded statements. The latter two constructs are used to represent arbitrary (often side-effecting) code that executes at a specific point in a tree but does not otherwise participate in the tree’s dataflow. Unfortunately, representational challenges with embedded statements make them difficult to understand and error-prone to manipulate. This paper proposes that we remove all statements--embedded and otherwise--from the backend IR by chaining the last linearly-threaded node within a statement to the first linearly-threaded node within its successor and vice versa as well as removing certain constraints on the shape of the nodes within a block. ### Review: IR ordering semantics As previously mentioned, RyuJIT uses two forms of IR: the front-end IR (referred to hereafter as HIR) and the back-end IR (referred to hereafter as LIR). Aside from using different representations for operations such as stores, HIR and LIR differ in their ordering constructs within basic blocks. Within a basic block, the HIR is ordered first by statements. Each statement consists of a single tree that performs the computation associated with that statement. The nodes of that tree are executed in the order produced by a left-to-right post-order visit of the tree’s nodes (with the exception of binary operator nodes that have the GTF\_REVERSE\_OPS flag set, which reverses the order of their operand trees). As such, the edges in a tree represent both ordering and edges in a dataflow graph where every definition has a single use, with some exceptions: - Edges to nodes that represent defs of storage locations (e.g. edges to nodes on the LHS of assignment operators) often represent neither ordering or a use-to-def relationship: the def of the location happens as part of the execution of its parent, and the edge does not represent a use of an SDSU temp. - Edges to unused values do not represent a use-to-def relationship: these edges exist only for ordering. The primary source of the latter are comma nodes, which are used in the HIR specifically to insert arbitrary code into a tree’s execution that does not otherwise participate in its SDSU dataflow. Similar to the HIR, the LIR is ordered first by statements. Each statement consists of a single tree and a linear threading of nodes that represent the SDSU dataflow and computation, respectively, that are associated with that statement. The linear threading of nodes must contain each node that is present in the tree, and all nodes that make up the tree must be present in the linear threading in the same order in which they would have been executed by the HIR ’s tree ordering. Additional nodes may be present in the linear threading in the form of embedded statements, which are sub-statements whose nodes form a contiguous subsequence of their containing statement’s execution order, but do not participate in the containing statement’s SDSU dataflow (i.e. the embedded statement’s nodes are not present in the containing statement’s tree). Embedded statements otherwise have the same ordering semantics as top-level statements, and are used for the same purpose as comma nodes in the HIR: they allow the compiler to insert arbitrary code into a statement’s execution that does not otherwise participate in its SDSU dataflow. As mentioned, both comma nodes and embedded statements are used for the same purpose in the HIR and LIR, respectively. Each construct represents a contiguous sequence of code that executes within the context of a tree but that does not participate in its SDSU dataflow. Of the two, however, embedded statements are generally more difficult to work with: since they are not present in their containing statement’s tree, the developer must take particular care when processing LIR in order to avoid omitting the nodes that comprise embedded statements from analyses such as those required for code motion (e.g. the analysis required to make addressing mode “contained”) and to avoid violating the tree order constraint placed upon the LIR ’s linear threading. The problems with manipulating embedded statements have two relatively clear solutions: either replace embedded statements with a construct that is represented in its parent statement’s tree, or remove the tree order constraint and move the LIR to a linear ordering that is constrained only by the requirements of dataflow and side-effect consistency. We believe that the latter is preferable to the former, as it is consistent with the overall direction that the LIR has taken thus far and reduces the number of concepts bound up in tree edges, which would thereafter represent only the SDSU dataflow for a node. This would clarify the meaning of the IR as well as the analysis required to perform the transformations required by the backend. ### Approach The approach that we propose is outlined below. #### 1. Add utilities for working with LIR. Efficiently working with the new IR shape will require the creation of utilities for manipulating, analyzing, validating, and displaying linearly-ordered LIR. Of these, validation and display of the LIR are particularly interesting. Validation is likely to check at least the following properties: 1. The linear threading is loop-free 2. All SDSU temps (i.e. temps represented by edges) are in fact singly-used 3. All defs of SDSU temps occur before the corresponding use 4. All SDSU defs that are used are present in the linear IR In the short term, we propose that the LIR be displayed using the linear dump that was recently added to the JIT. These dumps would be configured such that all of the information typically present in today’s tree-style dumps (e.g. node flags, value numbers, etc.) is also present in the linear dump. #### 2. Stop Generating embedded statements in the rationalizer. This can be approached in a few different ways: 1. Remove commas from the IR before rationalizing. There is already infrastructure in-flight in order to perform this transformation, so this is attractive from a dev-hours point of view. Unfortunately, this approach carries both throughput and a code quality risks due to the addition of another pass and the creation of additional local vars. 2. Change the rationalizer such that it simply does not produce embedded statements. This requires that the rationalizer is either able to operate on both HIR and LIR or simply linearize commas as it goes. 3. Remove embedded statements from the IR with a linearization pass between the rationalizer and lowering. We will move forward with option 2, as it is the most attractive from a throughput and code quality standpoint: it does not add additional passes (as does option 3), nor does it introduce additional local vars (as does option 1). #### 3. Refactor decomposition and lowering to work with linear LIR. The bulk of the work in this step involves moving these passes from statement- and tree-ordered walks to linear walks and refactoring any code that uses the parent stack to instead use a helper that can calculate the def-to-use edge for a node. It will also be necessary to replace embedded statement insertion with simple linear IR insertion, which is straightforward. ##### 3.i. Decomposition Transitioning decomposition should be rather simple. This pass walks the nodes of each statement in execution order, decomposing 64-bit operations into equivalent sequences of 32-bit operations as it goes. Critically, the rewrites performed by decomposition are universally expansions of a single operator into a contiguous sequence of operators whose results are combined to form the ultimate result. This sort of transformation is easily performed on linear IR by inserting the new nodes before the node being replaced. Furthermore, because nodes will appear in the linear walk in the same relative order that they appear in the execution-order tree walk, rewrites performed in linear order will occur in the same order in which they were originally performed. ##### 3.ii. Lowering The picture for lowering is much the same as the picture for decomposition. Like decomposition, all rewrites are performed in execution order, and most rewrites are simple expansions of a single node into multiple nodes. There is one notable exception, however: the lowering of add nodes for the x86 architecture examines the parent stack provided by tree walks in order to defer lowering until it may be possible to form an address mode. In this case, the use of the parent stack can be replaced with a helper that finds the node that uses the def produced by the add node. ##### 3.iii. General issues Both decomposition and lowering make use of a utility to fix up information present in the per-call-node side table that tracks extra information about the call’s arguments when necessary. This helper can be replaced by instead fixing up the side table entries when the call is visited by each pass. #### 4. Remove uses of statements and the tree-order invariant from LSRA. LSRA currently depends on the tree order invariant so that it can build a stack to track data associated with the defs consumed by an operator. Removing the tree order invariant requires that LSRA is able to accommodate situations where the contents of this stack as produced by a linear walk would no longer contain correct information due to the insertion of new nodes that produce values that are live across the operator and some subset of its operands. Analysis indicates that a simple map from defs to the necessary information should be sufficient. #### 5. Remove uses of statements from the rest of the backend. The rest of the backend--i.e. codegen--has no known dependencies on tree order, so there are no concerns with respect to the change in ordering semantics. However, statement nodes are used to derive IL offsets for debug information. There are a number of alternative methods of tracking IL offsets to consider: 1. Insert “IL offset” nodes into the linearly-ordered LIR. These nodes would then be noted by code generation and used to emit the necessary IP-mapping entries in the same way that statements are today. This has the disadvantage of requiring additional work when performing code motion on LIR if the IL offset for a particular node needs to be kept up-to-date. However, today’s backend does not perform this sort of code motion and even if it did, optimized debugging is not currently a scenario, so a loss of debugging fidelity may be acceptable. 2. Use a side table to map from each node to its IL offset. Although this increases the total working set of the backend, this has the advantage of making it easy to keep IL offsets correct in the face of code motion. 3. Add IL offset information directly to each node. This has the disadvantage of increasing the working set of the entire compiler. Unless we expect to require correct debug information in the face of code motion in the future, our recommendation is for the first option, which comes at a minimum size and implementation cost. #### 6. Remove contained nodes from the LIR’s execution order. Once statements are removed from the LIR, there is one major issue left to address: the presence of contained nodes in the LIR’s execution order. The execution of these nodes logically happens as part of the node in which they are contained, but these nodes remain physically present in the IR at their original locations. As a result, the backend must often take care to skip contained nodes when manipulating the LIR in ways that must take execution order into account. Instead of leaving such nodes in the LIR, these node should be removed from execution order and instead be represented as (probably unordered) trees referenced only by the containing node. ### Conclusion and Future Directions The changes suggested in this paper move RyuJIT’s LIR from a linear view of a tree-ordered nodes with certain nodes represented only in execution order to a linearly ordered sequence of nodes. Furthermore, with this change, tree edges in LIR would represent either uses of SDSU temps that have a place in execution order (where the edge points from the use of the temp to the def) or uses of unordered expression trees that execute as part of the parent node. This form should be easier to work with due to the removal of the tree order constraint and embedded statements and its similarity to other linear IR designs.
## Removing Embedded Statements From the RyuJIT Backend IR Pat Gavlin ([*[email protected]*](mailto:[email protected])) July 2016 ### Abstract RyuJIT’s IR comes in two forms: that produced and manipulated in the front end and that expected and manipulated by the back end. The boundary between these two forms of IR is comprised of rationalization and lowering, both of which transform the front-end IR into back end IR. For the purposes of this paper, the relevant differences between the two IRs revolve around ordering constructs within basic blocks: top-level statements, trees, comma nodes, and embedded statements. The latter two constructs are used to represent arbitrary (often side-effecting) code that executes at a specific point in a tree but does not otherwise participate in the tree’s dataflow. Unfortunately, representational challenges with embedded statements make them difficult to understand and error-prone to manipulate. This paper proposes that we remove all statements--embedded and otherwise--from the backend IR by chaining the last linearly-threaded node within a statement to the first linearly-threaded node within its successor and vice versa as well as removing certain constraints on the shape of the nodes within a block. ### Review: IR ordering semantics As previously mentioned, RyuJIT uses two forms of IR: the front-end IR (referred to hereafter as HIR) and the back-end IR (referred to hereafter as LIR). Aside from using different representations for operations such as stores, HIR and LIR differ in their ordering constructs within basic blocks. Within a basic block, the HIR is ordered first by statements. Each statement consists of a single tree that performs the computation associated with that statement. The nodes of that tree are executed in the order produced by a left-to-right post-order visit of the tree’s nodes (with the exception of binary operator nodes that have the GTF\_REVERSE\_OPS flag set, which reverses the order of their operand trees). As such, the edges in a tree represent both ordering and edges in a dataflow graph where every definition has a single use, with some exceptions: - Edges to nodes that represent defs of storage locations (e.g. edges to nodes on the LHS of assignment operators) often represent neither ordering or a use-to-def relationship: the def of the location happens as part of the execution of its parent, and the edge does not represent a use of an SDSU temp. - Edges to unused values do not represent a use-to-def relationship: these edges exist only for ordering. The primary source of the latter are comma nodes, which are used in the HIR specifically to insert arbitrary code into a tree’s execution that does not otherwise participate in its SDSU dataflow. Similar to the HIR, the LIR is ordered first by statements. Each statement consists of a single tree and a linear threading of nodes that represent the SDSU dataflow and computation, respectively, that are associated with that statement. The linear threading of nodes must contain each node that is present in the tree, and all nodes that make up the tree must be present in the linear threading in the same order in which they would have been executed by the HIR ’s tree ordering. Additional nodes may be present in the linear threading in the form of embedded statements, which are sub-statements whose nodes form a contiguous subsequence of their containing statement’s execution order, but do not participate in the containing statement’s SDSU dataflow (i.e. the embedded statement’s nodes are not present in the containing statement’s tree). Embedded statements otherwise have the same ordering semantics as top-level statements, and are used for the same purpose as comma nodes in the HIR: they allow the compiler to insert arbitrary code into a statement’s execution that does not otherwise participate in its SDSU dataflow. As mentioned, both comma nodes and embedded statements are used for the same purpose in the HIR and LIR, respectively. Each construct represents a contiguous sequence of code that executes within the context of a tree but that does not participate in its SDSU dataflow. Of the two, however, embedded statements are generally more difficult to work with: since they are not present in their containing statement’s tree, the developer must take particular care when processing LIR in order to avoid omitting the nodes that comprise embedded statements from analyses such as those required for code motion (e.g. the analysis required to make addressing mode “contained”) and to avoid violating the tree order constraint placed upon the LIR ’s linear threading. The problems with manipulating embedded statements have two relatively clear solutions: either replace embedded statements with a construct that is represented in its parent statement’s tree, or remove the tree order constraint and move the LIR to a linear ordering that is constrained only by the requirements of dataflow and side-effect consistency. We believe that the latter is preferable to the former, as it is consistent with the overall direction that the LIR has taken thus far and reduces the number of concepts bound up in tree edges, which would thereafter represent only the SDSU dataflow for a node. This would clarify the meaning of the IR as well as the analysis required to perform the transformations required by the backend. ### Approach The approach that we propose is outlined below. #### 1. Add utilities for working with LIR. Efficiently working with the new IR shape will require the creation of utilities for manipulating, analyzing, validating, and displaying linearly-ordered LIR. Of these, validation and display of the LIR are particularly interesting. Validation is likely to check at least the following properties: 1. The linear threading is loop-free 2. All SDSU temps (i.e. temps represented by edges) are in fact singly-used 3. All defs of SDSU temps occur before the corresponding use 4. All SDSU defs that are used are present in the linear IR In the short term, we propose that the LIR be displayed using the linear dump that was recently added to the JIT. These dumps would be configured such that all of the information typically present in today’s tree-style dumps (e.g. node flags, value numbers, etc.) is also present in the linear dump. #### 2. Stop Generating embedded statements in the rationalizer. This can be approached in a few different ways: 1. Remove commas from the IR before rationalizing. There is already infrastructure in-flight in order to perform this transformation, so this is attractive from a dev-hours point of view. Unfortunately, this approach carries both throughput and a code quality risks due to the addition of another pass and the creation of additional local vars. 2. Change the rationalizer such that it simply does not produce embedded statements. This requires that the rationalizer is either able to operate on both HIR and LIR or simply linearize commas as it goes. 3. Remove embedded statements from the IR with a linearization pass between the rationalizer and lowering. We will move forward with option 2, as it is the most attractive from a throughput and code quality standpoint: it does not add additional passes (as does option 3), nor does it introduce additional local vars (as does option 1). #### 3. Refactor decomposition and lowering to work with linear LIR. The bulk of the work in this step involves moving these passes from statement- and tree-ordered walks to linear walks and refactoring any code that uses the parent stack to instead use a helper that can calculate the def-to-use edge for a node. It will also be necessary to replace embedded statement insertion with simple linear IR insertion, which is straightforward. ##### 3.i. Decomposition Transitioning decomposition should be rather simple. This pass walks the nodes of each statement in execution order, decomposing 64-bit operations into equivalent sequences of 32-bit operations as it goes. Critically, the rewrites performed by decomposition are universally expansions of a single operator into a contiguous sequence of operators whose results are combined to form the ultimate result. This sort of transformation is easily performed on linear IR by inserting the new nodes before the node being replaced. Furthermore, because nodes will appear in the linear walk in the same relative order that they appear in the execution-order tree walk, rewrites performed in linear order will occur in the same order in which they were originally performed. ##### 3.ii. Lowering The picture for lowering is much the same as the picture for decomposition. Like decomposition, all rewrites are performed in execution order, and most rewrites are simple expansions of a single node into multiple nodes. There is one notable exception, however: the lowering of add nodes for the x86 architecture examines the parent stack provided by tree walks in order to defer lowering until it may be possible to form an address mode. In this case, the use of the parent stack can be replaced with a helper that finds the node that uses the def produced by the add node. ##### 3.iii. General issues Both decomposition and lowering make use of a utility to fix up information present in the per-call-node side table that tracks extra information about the call’s arguments when necessary. This helper can be replaced by instead fixing up the side table entries when the call is visited by each pass. #### 4. Remove uses of statements and the tree-order invariant from LSRA. LSRA currently depends on the tree order invariant so that it can build a stack to track data associated with the defs consumed by an operator. Removing the tree order invariant requires that LSRA is able to accommodate situations where the contents of this stack as produced by a linear walk would no longer contain correct information due to the insertion of new nodes that produce values that are live across the operator and some subset of its operands. Analysis indicates that a simple map from defs to the necessary information should be sufficient. #### 5. Remove uses of statements from the rest of the backend. The rest of the backend--i.e. codegen--has no known dependencies on tree order, so there are no concerns with respect to the change in ordering semantics. However, statement nodes are used to derive IL offsets for debug information. There are a number of alternative methods of tracking IL offsets to consider: 1. Insert “IL offset” nodes into the linearly-ordered LIR. These nodes would then be noted by code generation and used to emit the necessary IP-mapping entries in the same way that statements are today. This has the disadvantage of requiring additional work when performing code motion on LIR if the IL offset for a particular node needs to be kept up-to-date. However, today’s backend does not perform this sort of code motion and even if it did, optimized debugging is not currently a scenario, so a loss of debugging fidelity may be acceptable. 2. Use a side table to map from each node to its IL offset. Although this increases the total working set of the backend, this has the advantage of making it easy to keep IL offsets correct in the face of code motion. 3. Add IL offset information directly to each node. This has the disadvantage of increasing the working set of the entire compiler. Unless we expect to require correct debug information in the face of code motion in the future, our recommendation is for the first option, which comes at a minimum size and implementation cost. #### 6. Remove contained nodes from the LIR’s execution order. Once statements are removed from the LIR, there is one major issue left to address: the presence of contained nodes in the LIR’s execution order. The execution of these nodes logically happens as part of the node in which they are contained, but these nodes remain physically present in the IR at their original locations. As a result, the backend must often take care to skip contained nodes when manipulating the LIR in ways that must take execution order into account. Instead of leaving such nodes in the LIR, these node should be removed from execution order and instead be represented as (probably unordered) trees referenced only by the containing node. ### Conclusion and Future Directions The changes suggested in this paper move RyuJIT’s LIR from a linear view of a tree-ordered nodes with certain nodes represented only in execution order to a linearly ordered sequence of nodes. Furthermore, with this change, tree edges in LIR would represent either uses of SDSU temps that have a place in execution order (where the edge points from the use of the temp to the def) or uses of unordered expression trees that execute as part of the parent node. This form should be easier to work with due to the removal of the tree order constraint and embedded statements and its similarity to other linear IR designs.
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/HardwareIntrinsics/X86/Sse41_Overloaded/RoundToPositiveInfinityScalar.Single.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 RoundToPositiveInfinityScalarSingle() { var test = new SimpleUnaryOpTest__RoundToPositiveInfinityScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__RoundToPositiveInfinityScalarSingle { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__RoundToPositiveInfinityScalarSingle testClass) { var result = Sse41.RoundToPositiveInfinityScalar(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToPositiveInfinityScalarSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) { var result = Sse41.RoundToPositiveInfinityScalar( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__RoundToPositiveInfinityScalarSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleUnaryOpTest__RoundToPositiveInfinityScalarSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.RoundToPositiveInfinityScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.RoundToPositiveInfinityScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.RoundToPositiveInfinityScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToPositiveInfinityScalar), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToPositiveInfinityScalar), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToPositiveInfinityScalar), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.RoundToPositiveInfinityScalar( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) { var result = Sse41.RoundToPositiveInfinityScalar( Sse.LoadVector128((Single*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var result = Sse41.RoundToPositiveInfinityScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var result = Sse41.RoundToPositiveInfinityScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var result = Sse41.RoundToPositiveInfinityScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__RoundToPositiveInfinityScalarSingle(); var result = Sse41.RoundToPositiveInfinityScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__RoundToPositiveInfinityScalarSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) { var result = Sse41.RoundToPositiveInfinityScalar( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.RoundToPositiveInfinityScalar(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) { var result = Sse41.RoundToPositiveInfinityScalar( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.RoundToPositiveInfinityScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.RoundToPositiveInfinityScalar( Sse.LoadVector128((Single*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Ceiling(firstOp[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.RoundToPositiveInfinityScalar)}<Single>(Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 RoundToPositiveInfinityScalarSingle() { var test = new SimpleUnaryOpTest__RoundToPositiveInfinityScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__RoundToPositiveInfinityScalarSingle { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__RoundToPositiveInfinityScalarSingle testClass) { var result = Sse41.RoundToPositiveInfinityScalar(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToPositiveInfinityScalarSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) { var result = Sse41.RoundToPositiveInfinityScalar( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__RoundToPositiveInfinityScalarSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleUnaryOpTest__RoundToPositiveInfinityScalarSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.RoundToPositiveInfinityScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.RoundToPositiveInfinityScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.RoundToPositiveInfinityScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToPositiveInfinityScalar), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToPositiveInfinityScalar), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToPositiveInfinityScalar), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.RoundToPositiveInfinityScalar( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) { var result = Sse41.RoundToPositiveInfinityScalar( Sse.LoadVector128((Single*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var result = Sse41.RoundToPositiveInfinityScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var result = Sse41.RoundToPositiveInfinityScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var result = Sse41.RoundToPositiveInfinityScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__RoundToPositiveInfinityScalarSingle(); var result = Sse41.RoundToPositiveInfinityScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__RoundToPositiveInfinityScalarSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) { var result = Sse41.RoundToPositiveInfinityScalar( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.RoundToPositiveInfinityScalar(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) { var result = Sse41.RoundToPositiveInfinityScalar( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.RoundToPositiveInfinityScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.RoundToPositiveInfinityScalar( Sse.LoadVector128((Single*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Ceiling(firstOp[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.RoundToPositiveInfinityScalar)}<Single>(Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/BitwiseClear.Vector64.Single.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void BitwiseClear_Vector64_Single() { var test = new SimpleBinaryOpTest__BitwiseClear_Vector64_Single(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__BitwiseClear_Vector64_Single { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Single> _fld1; public Vector64<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__BitwiseClear_Vector64_Single testClass) { var result = AdvSimd.BitwiseClear(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__BitwiseClear_Vector64_Single testClass) { fixed (Vector64<Single>* pFld1 = &_fld1) fixed (Vector64<Single>* pFld2 = &_fld2) { var result = AdvSimd.BitwiseClear( AdvSimd.LoadVector64((Single*)(pFld1)), AdvSimd.LoadVector64((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector64<Single> _clsVar1; private static Vector64<Single> _clsVar2; private Vector64<Single> _fld1; private Vector64<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__BitwiseClear_Vector64_Single() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); } public SimpleBinaryOpTest__BitwiseClear_Vector64_Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.BitwiseClear( Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.BitwiseClear( AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.BitwiseClear), new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.BitwiseClear), new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.BitwiseClear( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Single>* pClsVar1 = &_clsVar1) fixed (Vector64<Single>* pClsVar2 = &_clsVar2) { var result = AdvSimd.BitwiseClear( AdvSimd.LoadVector64((Single*)(pClsVar1)), AdvSimd.LoadVector64((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr); var result = AdvSimd.BitwiseClear(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr)); var result = AdvSimd.BitwiseClear(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__BitwiseClear_Vector64_Single(); var result = AdvSimd.BitwiseClear(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__BitwiseClear_Vector64_Single(); fixed (Vector64<Single>* pFld1 = &test._fld1) fixed (Vector64<Single>* pFld2 = &test._fld2) { var result = AdvSimd.BitwiseClear( AdvSimd.LoadVector64((Single*)(pFld1)), AdvSimd.LoadVector64((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.BitwiseClear(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Single>* pFld1 = &_fld1) fixed (Vector64<Single>* pFld2 = &_fld2) { var result = AdvSimd.BitwiseClear( AdvSimd.LoadVector64((Single*)(pFld1)), AdvSimd.LoadVector64((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.BitwiseClear(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.BitwiseClear( AdvSimd.LoadVector64((Single*)(&test._fld1)), AdvSimd.LoadVector64((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Single> op1, Vector64<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(Helpers.BitwiseClear(left[i], right[i])) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.BitwiseClear)}<Single>(Vector64<Single>, Vector64<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void BitwiseClear_Vector64_Single() { var test = new SimpleBinaryOpTest__BitwiseClear_Vector64_Single(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__BitwiseClear_Vector64_Single { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Single> _fld1; public Vector64<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__BitwiseClear_Vector64_Single testClass) { var result = AdvSimd.BitwiseClear(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__BitwiseClear_Vector64_Single testClass) { fixed (Vector64<Single>* pFld1 = &_fld1) fixed (Vector64<Single>* pFld2 = &_fld2) { var result = AdvSimd.BitwiseClear( AdvSimd.LoadVector64((Single*)(pFld1)), AdvSimd.LoadVector64((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector64<Single> _clsVar1; private static Vector64<Single> _clsVar2; private Vector64<Single> _fld1; private Vector64<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__BitwiseClear_Vector64_Single() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); } public SimpleBinaryOpTest__BitwiseClear_Vector64_Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.BitwiseClear( Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.BitwiseClear( AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.BitwiseClear), new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.BitwiseClear), new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.BitwiseClear( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Single>* pClsVar1 = &_clsVar1) fixed (Vector64<Single>* pClsVar2 = &_clsVar2) { var result = AdvSimd.BitwiseClear( AdvSimd.LoadVector64((Single*)(pClsVar1)), AdvSimd.LoadVector64((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr); var result = AdvSimd.BitwiseClear(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr)); var result = AdvSimd.BitwiseClear(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__BitwiseClear_Vector64_Single(); var result = AdvSimd.BitwiseClear(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__BitwiseClear_Vector64_Single(); fixed (Vector64<Single>* pFld1 = &test._fld1) fixed (Vector64<Single>* pFld2 = &test._fld2) { var result = AdvSimd.BitwiseClear( AdvSimd.LoadVector64((Single*)(pFld1)), AdvSimd.LoadVector64((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.BitwiseClear(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Single>* pFld1 = &_fld1) fixed (Vector64<Single>* pFld2 = &_fld2) { var result = AdvSimd.BitwiseClear( AdvSimd.LoadVector64((Single*)(pFld1)), AdvSimd.LoadVector64((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.BitwiseClear(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.BitwiseClear( AdvSimd.LoadVector64((Single*)(&test._fld1)), AdvSimd.LoadVector64((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Single> op1, Vector64<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(Helpers.BitwiseClear(left[i], right[i])) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.BitwiseClear)}<Single>(Vector64<Single>, Vector64<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/jit64/gc/misc/simple1.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="simple1.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="simple1.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest563/Generated563.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="Generated563.il" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\TestFramework\TestFramework.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="Generated563.il" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\TestFramework\TestFramework.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/jit64/localloc/unwind/unwind01_dynamic.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>PdbOnly</DebugType> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> <DefineConstants>$(DefineConstants);LOCALLOC_DYNAMIC</DefineConstants> <NoWarn>$(NoWarn),8002</NoWarn> </PropertyGroup> <ItemGroup> <Compile Include="unwind01.cs" /> <ProjectReference Include="..\..\..\common\localloc_common.ilproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>PdbOnly</DebugType> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> <DefineConstants>$(DefineConstants);LOCALLOC_DYNAMIC</DefineConstants> <NoWarn>$(NoWarn),8002</NoWarn> </PropertyGroup> <ItemGroup> <Compile Include="unwind01.cs" /> <ProjectReference Include="..\..\..\common\localloc_common.ilproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./.github/workflows/markdownlint.yml
name: Markdownlint permissions: contents: read on: pull_request: paths: - "**/*.md" - ".markdownlint.json" - ".github/workflows/markdownlint.yml" - ".github/workflows/markdownlint-problem-matcher.json" jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Use Node.js uses: actions/setup-node@v1 with: node-version: 12.x - name: Run Markdownlint run: | echo "::add-matcher::.github/workflows/markdownlint-problem-matcher.json" npm i -g markdownlint-cli markdownlint "**/*.md"
name: Markdownlint permissions: contents: read on: pull_request: paths: - "**/*.md" - ".markdownlint.json" - ".github/workflows/markdownlint.yml" - ".github/workflows/markdownlint-problem-matcher.json" jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Use Node.js uses: actions/setup-node@v1 with: node-version: 12.x - name: Run Markdownlint run: | echo "::add-matcher::.github/workflows/markdownlint-problem-matcher.json" npm i -g markdownlint-cli markdownlint "**/*.md"
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/libraries/System.Private.Xml/tests/XmlReaderLib/TCReadElementContentAsBinHex.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; namespace System.Xml.Tests { public partial class TCReadElementContentAsBinHex : TCXMLReaderBaseGeneral { // Type is System.Xml.Tests.TCReadElementContentAsBinHex // Test Case public override void AddChildren() { // for function TestReadBinHex_1 { this.AddChild(new CVariation(TestReadBinHex_1) { Attribute = new Variation("ReadBinHex Element with all valid value") }); } // for function TestReadBinHex_2 { this.AddChild(new CVariation(TestReadBinHex_2) { Attribute = new Variation("ReadBinHex Element with all valid Num value") { Pri = 0 } }); } // for function TestReadBinHex_3 { this.AddChild(new CVariation(TestReadBinHex_3) { Attribute = new Variation("ReadBinHex Element with all valid Text value") }); } // for function TestReadBinHex_4 { this.AddChild(new CVariation(TestReadBinHex_4) { Attribute = new Variation("ReadBinHex Element with Comments and PIs") { Pri = 0 } }); } // for function TestReadBinHex_5 { this.AddChild(new CVariation(TestReadBinHex_5) { Attribute = new Variation("ReadBinHex Element with all valid value (from concatenation), Pri=0") }); } // for function TestReadBinHex_6 { this.AddChild(new CVariation(TestReadBinHex_6) { Attribute = new Variation("ReadBinHex Element with all long valid value (from concatenation)") }); } // for function TestReadBinHex_7 { this.AddChild(new CVariation(TestReadBinHex_7) { Attribute = new Variation("ReadBinHex with count > buffer size") }); } // for function TestReadBinHex_8 { this.AddChild(new CVariation(TestReadBinHex_8) { Attribute = new Variation("ReadBinHex with count < 0") }); } // for function vReadBinHex_9 { this.AddChild(new CVariation(vReadBinHex_9) { Attribute = new Variation("ReadBinHex with index > buffer size") }); } // for function TestReadBinHex_10 { this.AddChild(new CVariation(TestReadBinHex_10) { Attribute = new Variation("ReadBinHex with index < 0") }); } // for function TestReadBinHex_11 { this.AddChild(new CVariation(TestReadBinHex_11) { Attribute = new Variation("ReadBinHex with index + count exceeds buffer") }); } // for function TestReadBinHex_12 { this.AddChild(new CVariation(TestReadBinHex_12) { Attribute = new Variation("ReadBinHex index & count =0") }); } // for function TestReadBinHex_13 { this.AddChild(new CVariation(TestReadBinHex_13) { Attribute = new Variation("ReadBinHex Element multiple into same buffer (using offset), Pri=0") }); } // for function TestReadBinHex_14 { this.AddChild(new CVariation(TestReadBinHex_14) { Attribute = new Variation("ReadBinHex with buffer == null") }); } // for function TestReadBinHex_16 { this.AddChild(new CVariation(TestReadBinHex_16) { Attribute = new Variation("Read after partial ReadBinHex") }); } // for function TestReadBinHex_18 { this.AddChild(new CVariation(TestReadBinHex_18) { Attribute = new Variation("No op node types") }); } // for function TestTextReadBinHex_21 { this.AddChild(new CVariation(TestTextReadBinHex_21) { Attribute = new Variation("ReadBinHex with whitespace") }); } // for function TestTextReadBinHex_22 { this.AddChild(new CVariation(TestTextReadBinHex_22) { Attribute = new Variation("ReadBinHex with odd number of chars") }); } // for function TestTextReadBinHex_23 { this.AddChild(new CVariation(TestTextReadBinHex_23) { Attribute = new Variation("ReadBinHex when end tag doesn't exist") }); } // for function TestTextReadBinHex_24 { this.AddChild(new CVariation(TestTextReadBinHex_24) { Attribute = new Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes") }); } // for function TestReadBinHex_430329 { this.AddChild(new CVariation(TestReadBinHex_430329) { Attribute = new Variation("SubtreeReader inserted attributes don't work with ReadContentAsBinHex") }); } // for function TestReadBinHex_27 { this.AddChild(new CVariation(TestReadBinHex_27) { Attribute = new Variation("ReadBinHex with = in the middle") }); } // for function TestReadBinHex_105376 { this.AddChild(new CVariation(TestReadBinHex_105376) { Attribute = new Variation("ReadBinHex runs into an Overflow") { Params = new object[] { "1000000" } } }); this.AddChild(new CVariation(TestReadBinHex_105376) { Attribute = new Variation("ReadBinHex runs into an Overflow") { Params = new object[] { "10000000" } } }); } // for function TestReadBinHex_28 { this.AddChild(new CVariation(TestReadBinHex_28) { Attribute = new Variation("call ReadContentAsBinHex on two or more nodes") }); } // for function TestReadBinHex_29 { this.AddChild(new CVariation(TestReadBinHex_29) { Attribute = new Variation("read BinHex over invalid text node") }); } // for function TestReadBinHex_30 { this.AddChild(new CVariation(TestReadBinHex_30) { Attribute = new Variation("goto to text node, ask got.Value, readcontentasBinHex") }); } // for function TestReadBinHex_31 { this.AddChild(new CVariation(TestReadBinHex_31) { Attribute = new Variation("goto to text node, readcontentasBinHex, ask got.Value") }); } // for function TestReadBinHex_32 { this.AddChild(new CVariation(TestReadBinHex_32) { Attribute = new Variation("goto to huge text node, read several chars with ReadContentAsBinHex and Move forward with .Read()") }); } // for function TestReadBinHex_33 { this.AddChild(new CVariation(TestReadBinHex_33) { Attribute = new Variation("goto to huge text node with invalid chars, read several chars with ReadContentAsBinHex and Move forward with .Read()") }); } // for function TestBinHex_34 { this.AddChild(new CVariation(TestBinHex_34) { Attribute = new Variation("ReadContentAsBinHex on an xmlns attribute") { Param = "<foo xmlns='default'> <bar > id='1'/> </foo>" } }); this.AddChild(new CVariation(TestBinHex_34) { Attribute = new Variation("ReadContentAsBinHex on an xmlns:k attribute") { Param = "<k:foo xmlns:k='default'> <k:bar id='1'/> </k:foo>" } }); this.AddChild(new CVariation(TestBinHex_34) { Attribute = new Variation("ReadContentAsBinHex on an xml:space attribute") { Param = "<foo xml:space='default'> <bar > id='1'/> </foo>" } }); this.AddChild(new CVariation(TestBinHex_34) { Attribute = new Variation("ReadContentAsBinHex on an xml:lang attribute") { Param = "<foo xml:lang='default'> <bar > id='1'/> </foo>" } }); } // for function TestReadBinHex_35 { this.AddChild(new CVariation(TestReadBinHex_35) { Attribute = new Variation("call ReadContentAsBinHex on two or more nodes and whitespace") }); } // for function TestReadBinHex_36 { this.AddChild(new CVariation(TestReadBinHex_36) { Attribute = new Variation("call ReadContentAsBinHex on two or more nodes and whitespace after call Value") }); } } } }
// 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; namespace System.Xml.Tests { public partial class TCReadElementContentAsBinHex : TCXMLReaderBaseGeneral { // Type is System.Xml.Tests.TCReadElementContentAsBinHex // Test Case public override void AddChildren() { // for function TestReadBinHex_1 { this.AddChild(new CVariation(TestReadBinHex_1) { Attribute = new Variation("ReadBinHex Element with all valid value") }); } // for function TestReadBinHex_2 { this.AddChild(new CVariation(TestReadBinHex_2) { Attribute = new Variation("ReadBinHex Element with all valid Num value") { Pri = 0 } }); } // for function TestReadBinHex_3 { this.AddChild(new CVariation(TestReadBinHex_3) { Attribute = new Variation("ReadBinHex Element with all valid Text value") }); } // for function TestReadBinHex_4 { this.AddChild(new CVariation(TestReadBinHex_4) { Attribute = new Variation("ReadBinHex Element with Comments and PIs") { Pri = 0 } }); } // for function TestReadBinHex_5 { this.AddChild(new CVariation(TestReadBinHex_5) { Attribute = new Variation("ReadBinHex Element with all valid value (from concatenation), Pri=0") }); } // for function TestReadBinHex_6 { this.AddChild(new CVariation(TestReadBinHex_6) { Attribute = new Variation("ReadBinHex Element with all long valid value (from concatenation)") }); } // for function TestReadBinHex_7 { this.AddChild(new CVariation(TestReadBinHex_7) { Attribute = new Variation("ReadBinHex with count > buffer size") }); } // for function TestReadBinHex_8 { this.AddChild(new CVariation(TestReadBinHex_8) { Attribute = new Variation("ReadBinHex with count < 0") }); } // for function vReadBinHex_9 { this.AddChild(new CVariation(vReadBinHex_9) { Attribute = new Variation("ReadBinHex with index > buffer size") }); } // for function TestReadBinHex_10 { this.AddChild(new CVariation(TestReadBinHex_10) { Attribute = new Variation("ReadBinHex with index < 0") }); } // for function TestReadBinHex_11 { this.AddChild(new CVariation(TestReadBinHex_11) { Attribute = new Variation("ReadBinHex with index + count exceeds buffer") }); } // for function TestReadBinHex_12 { this.AddChild(new CVariation(TestReadBinHex_12) { Attribute = new Variation("ReadBinHex index & count =0") }); } // for function TestReadBinHex_13 { this.AddChild(new CVariation(TestReadBinHex_13) { Attribute = new Variation("ReadBinHex Element multiple into same buffer (using offset), Pri=0") }); } // for function TestReadBinHex_14 { this.AddChild(new CVariation(TestReadBinHex_14) { Attribute = new Variation("ReadBinHex with buffer == null") }); } // for function TestReadBinHex_16 { this.AddChild(new CVariation(TestReadBinHex_16) { Attribute = new Variation("Read after partial ReadBinHex") }); } // for function TestReadBinHex_18 { this.AddChild(new CVariation(TestReadBinHex_18) { Attribute = new Variation("No op node types") }); } // for function TestTextReadBinHex_21 { this.AddChild(new CVariation(TestTextReadBinHex_21) { Attribute = new Variation("ReadBinHex with whitespace") }); } // for function TestTextReadBinHex_22 { this.AddChild(new CVariation(TestTextReadBinHex_22) { Attribute = new Variation("ReadBinHex with odd number of chars") }); } // for function TestTextReadBinHex_23 { this.AddChild(new CVariation(TestTextReadBinHex_23) { Attribute = new Variation("ReadBinHex when end tag doesn't exist") }); } // for function TestTextReadBinHex_24 { this.AddChild(new CVariation(TestTextReadBinHex_24) { Attribute = new Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes") }); } // for function TestReadBinHex_430329 { this.AddChild(new CVariation(TestReadBinHex_430329) { Attribute = new Variation("SubtreeReader inserted attributes don't work with ReadContentAsBinHex") }); } // for function TestReadBinHex_27 { this.AddChild(new CVariation(TestReadBinHex_27) { Attribute = new Variation("ReadBinHex with = in the middle") }); } // for function TestReadBinHex_105376 { this.AddChild(new CVariation(TestReadBinHex_105376) { Attribute = new Variation("ReadBinHex runs into an Overflow") { Params = new object[] { "1000000" } } }); this.AddChild(new CVariation(TestReadBinHex_105376) { Attribute = new Variation("ReadBinHex runs into an Overflow") { Params = new object[] { "10000000" } } }); } // for function TestReadBinHex_28 { this.AddChild(new CVariation(TestReadBinHex_28) { Attribute = new Variation("call ReadContentAsBinHex on two or more nodes") }); } // for function TestReadBinHex_29 { this.AddChild(new CVariation(TestReadBinHex_29) { Attribute = new Variation("read BinHex over invalid text node") }); } // for function TestReadBinHex_30 { this.AddChild(new CVariation(TestReadBinHex_30) { Attribute = new Variation("goto to text node, ask got.Value, readcontentasBinHex") }); } // for function TestReadBinHex_31 { this.AddChild(new CVariation(TestReadBinHex_31) { Attribute = new Variation("goto to text node, readcontentasBinHex, ask got.Value") }); } // for function TestReadBinHex_32 { this.AddChild(new CVariation(TestReadBinHex_32) { Attribute = new Variation("goto to huge text node, read several chars with ReadContentAsBinHex and Move forward with .Read()") }); } // for function TestReadBinHex_33 { this.AddChild(new CVariation(TestReadBinHex_33) { Attribute = new Variation("goto to huge text node with invalid chars, read several chars with ReadContentAsBinHex and Move forward with .Read()") }); } // for function TestBinHex_34 { this.AddChild(new CVariation(TestBinHex_34) { Attribute = new Variation("ReadContentAsBinHex on an xmlns attribute") { Param = "<foo xmlns='default'> <bar > id='1'/> </foo>" } }); this.AddChild(new CVariation(TestBinHex_34) { Attribute = new Variation("ReadContentAsBinHex on an xmlns:k attribute") { Param = "<k:foo xmlns:k='default'> <k:bar id='1'/> </k:foo>" } }); this.AddChild(new CVariation(TestBinHex_34) { Attribute = new Variation("ReadContentAsBinHex on an xml:space attribute") { Param = "<foo xml:space='default'> <bar > id='1'/> </foo>" } }); this.AddChild(new CVariation(TestBinHex_34) { Attribute = new Variation("ReadContentAsBinHex on an xml:lang attribute") { Param = "<foo xml:lang='default'> <bar > id='1'/> </foo>" } }); } // for function TestReadBinHex_35 { this.AddChild(new CVariation(TestReadBinHex_35) { Attribute = new Variation("call ReadContentAsBinHex on two or more nodes and whitespace") }); } // for function TestReadBinHex_36 { this.AddChild(new CVariation(TestReadBinHex_36) { Attribute = new Variation("call ReadContentAsBinHex on two or more nodes and whitespace after call Value") }); } } } }
-1
dotnet/runtime
66,308
Add tests for `ijwhost`
- Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
elinor-fung
2022-03-07T19:28:56Z
2022-03-08T17:14:44Z
fa5dcda23c681031b5d2bd68482702baef80b836
627851323fe8f15539c163aabd7d7c644766c549
Add tests for `ijwhost`. - Move IJW build files from `src/tests/Interop/IJW` to `eng/native/ijw` - Add IJW test library to corehost/test - Add tests using actual `ijwhost` loaded by: - native host - managed, framework-dependent host - managed, self-contained host - Remove test explicitly calling into SPCL to load - `ijwhost` handles that cc @AaronRobinsonMSFT @jkoritzinsky
./src/tests/JIT/Directed/shift/uint8_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType /> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="uint8.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType /> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="uint8.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./docs/project/list-of-diagnostics.md
# List of Diagnostics Produced by .NET Libraries APIs ## Obsoletions Per https://github.com/dotnet/designs/blob/master/accepted/2020/better-obsoletion/better-obsoletion.md, we now have a strategy for marking existing APIs as `[Obsolete]`. This takes advantage of the new diagnostic id and URL template mechanisms introduced to `ObsoleteAttribute` in .NET 5. The diagnostic id values reserved for obsoletions are `SYSLIB0001` through `SYSLIB0999`. When obsoleting an API, claim the next three-digit identifier in the `SYSLIB0###` sequence and add it to the list below. The URL template for all obsoletions is `https://aka.ms/dotnet-warnings/{0}`. The `{0}` placeholder is replaced by the compiler with the `SYSLIB0###` identifier. The acceptance criteria for adding an obsoletion includes: * Add the obsoletion to the table below, claiming the next diagnostic id * Ensure the description is meaningful within the context of this table, and without requiring the context of the calling code * Add new constants to `src\libraries\Common\src\System\Obsoletions.cs`, following the existing conventions * A `...Message` const using the same description added to the table below * A `...DiagId` const for the `SYSLIB0###` id * Annotate `src` files by referring to the constants defined from `Obsoletions.cs` * Specify the `UrlFormat = Obsoletions.SharedUrlFormat` * Example: `[Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]` * If the `Obsoletions` type is not available in the project, link it into the project * `<Compile Include="$(CommonPath)System\Obsoletions.cs" Link="Common\System\Obsoletions.cs" />` * Annotate `ref` files using the hard-coded strings copied from `Obsoletions.cs` * This matches our general pattern of `ref` files using hard-coded attribute strings * Example: `[System.ObsoleteAttribute("The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead.", DiagnosticId = "SYSLIB0001", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")]` * If the library builds against downlevel targets earlier than .NET 5.0, then add an internal copy of `ObsoleteAttribute` * The compiler recognizes internal implementations of `ObsoleteAttribute` to enable the `DiagnosticId` and `UrlFormat` properties to light up downlevel * An MSBuild property can be added to the project's first `<PropertyGroup>` to achieve this easily * Example: `<IncludeInternalObsoleteAttribute>true</IncludeInternalObsoleteAttribute>` * This will need to be specified in both the `src` and `ref` projects * If the library contains types that are forwarded within a generated shim * Errors will be received when running `build libs`, with obsoletion errors in `src/libraries/shims/generated` files * This is resolved by adding the obsoletion's diagnostic id to the `<NoWarn>` property for partial facade assemblies * That property is found in `src/libraries/Directory.Build.targets` * Search for the "Ignore Obsolete errors within the generated shims that type-forward types" comment and add the appropriate diagnostic id to the comment and the `<NoWarn>` property (other SYSLIB diagnostics already exist there) * Apply the `breaking-change` label to the PR that introduces the obsoletion * A bot will automatically apply the `needs-breaking-change-doc-created` label when the `breaking-change` label is detected * Follow up with the breaking change process to communicate and document the breaking change * In the breaking-change issue filed in [dotnet/docs](https://github.com/dotnet/docs), specifically mention that this breaking change is an obsoletion with a `SYSLIB` diagnostic id * The documentation team will produce a PR that adds the obsoletion to the [SYSLIB warnings](https://docs.microsoft.com/en-us/dotnet/core/compatibility/syslib-obsoletions) page * That PR will also add a new URL specific to this diagnostic ID; e.g. [SYSLIB0001](https://docs.microsoft.com/en-us/dotnet/core/compatibility/syslib-warnings/syslib0001) * Connect with `@gewarren` or `@BillWagner` with any questions * Register the `SYSLIB0###` URL in `aka.ms` * The vanity name will be `dotnet-warnings/syslib0###` * Ensure the link's group owner matches the group owner of `dotnet-warnings/syslib0001` * Connect with `@jeffhandley`, `@GrabYourPitchforks`, or `@gewarren` with any questions An example obsoletion PR that can be referenced where each of the above criteria was met is: * [Implement new GetContextAPI overloads (#49186)](https://github.com/dotnet/runtime/pull/49186/files) The PR that reveals the implementation of the `<IncludeInternalObsoleteAttribute>` property was: * [Mark DirectoryServices CAS APIs as Obsolete (#40756)](https://github.com/dotnet/runtime/pull/40756/files) ### Obsoletion Diagnostics (`SYSLIB0001` - `SYSLIB0999`) | Diagnostic ID | Description | | :---------------- | :---------- | | __`SYSLIB0001`__ | The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead. | | __`SYSLIB0002`__ | PrincipalPermissionAttribute is not honored by the runtime and must not be used. | | __`SYSLIB0003`__ | Code Access Security is not supported or honored by the runtime. | | __`SYSLIB0004`__ | The Constrained Execution Region (CER) feature is not supported. | | __`SYSLIB0005`__ | The Global Assembly Cache is not supported. | | __`SYSLIB0006`__ | Thread.Abort is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0007`__ | The default implementation of this cryptography algorithm is not supported. | | __`SYSLIB0008`__ | The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0009`__ | The AuthenticationManager Authenticate and PreAuthenticate methods are not supported and throw PlatformNotSupportedException. | | __`SYSLIB0010`__ | This Remoting API is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0011`__ | `BinaryFormatter` serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for recommended alternatives. | | __`SYSLIB0012`__ | Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead. | | __`SYSLIB0013`__ | Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead. | | __`SYSLIB0014`__ | WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead. | | __`SYSLIB0015`__ | DisablePrivateReflectionAttribute has no effect in .NET 6.0+. | | __`SYSLIB0016`__ | Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations. | | __`SYSLIB0017`__ | Strong name signing is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0018`__ | ReflectionOnly loading is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0019`__ | RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException. | | __`SYSLIB0020`__ | JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull. | | __`SYSLIB0021`__ | Derived cryptographic types are obsolete. Use the Create method on the base type instead. | | __`SYSLIB0022`__ | The Rijndael and RijndaelManaged types are obsolete. Use Aes instead. | | __`SYSLIB0023`__ | RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead. | | __`SYSLIB0024`__ | Creating and unloading AppDomains is not supported and throws an exception. | | __`SYSLIB0025`__ | SuppressIldasmAttribute has no effect in .NET 6.0+. | | __`SYSLIB0026`__ | X509Certificate and X509Certificate2 are immutable. Use the appropriate constructor to create a new certificate. | | __`SYSLIB0027`__ | PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey. | | __`SYSLIB0028`__ | X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key. | | __`SYSLIB0029`__ | ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported. | | __`SYSLIB0030`__ | HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter. | | __`SYSLIB0031`__ | EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1. | | __`SYSLIB0032`__ | Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored. | | __`SYSLIB0033`__ | Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead. | | __`SYSLIB0034`__ | CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead. | | __`SYSLIB0035`__ | ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner. | | __`SYSLIB0036`__ | Regex.CompileToAssembly is obsolete and not supported. Use RegexGeneratorAttribute with the regular expression source generator instead. | | __`SYSLIB0037`__ | AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported. | | __`SYSLIB0038`__ | SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information. | | __`SYSLIB0039`__ | TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults. | ## Analyzer Warnings The diagnostic id values reserved for .NET Libraries analyzer warnings are `SYSLIB1001` through `SYSLIB1999`. When creating a new analyzer that ships as part of the Libraries (and not part of the SDK), claim the next three-digit identifier in the `SYSLIB1###` sequence and add it to the list below. ### Analyzer Diagnostics (`SYSLIB1001` - `SYSLIB1999`) | Diagnostic ID | Description | | :---------------- | :---------- | | __`SYSLIB1001`__ | Logging method names cannot start with _ | | __`SYSLIB1002`__ | Don't include log level parameters as templates in the logging message | | __`SYSLIB1003`__ | InvalidLoggingMethodParameterNameTitle | | __`SYSLIB1004`__ | Logging class cannot be in nested types | | __`SYSLIB1005`__ | Could not find a required type definition | | __`SYSLIB1006`__ | Multiple logging methods cannot use the same event id within a class | | __`SYSLIB1007`__ | Logging methods must return void | | __`SYSLIB1008`__ | One of the arguments to a logging method must implement the Microsoft.Extensions.Logging.ILogger interface | | __`SYSLIB1009`__ | Logging methods must be static | | __`SYSLIB1010`__ | Logging methods must be partial | | __`SYSLIB1011`__ | Logging methods cannot be generic | | __`SYSLIB1012`__ | Redundant qualifier in logging message | | __`SYSLIB1013`__ | Don't include exception parameters as templates in the logging message | | __`SYSLIB1014`__ | Logging template has no corresponding method argument | | __`SYSLIB1015`__ | Argument is not referenced from the logging message | | __`SYSLIB1016`__ | Logging methods cannot have a body | | __`SYSLIB1017`__ | A LogLevel value must be supplied in the LoggerMessage attribute or as a parameter to the logging method | | __`SYSLIB1018`__ | Don't include logger parameters as templates in the logging message | | __`SYSLIB1019`__ | Couldn't find a field of type Microsoft.Extensions.Logging.ILogger | | __`SYSLIB1020`__ | Found multiple fields of type Microsoft.Extensions.Logging.ILogger | | __`SYSLIB1021`__ | Can't have the same template with different casing | | __`SYSLIB1022`__ | Can't have malformed format strings (like dangling {, etc) | | __`SYSLIB1023`__ | Generating more than 6 arguments is not supported | | __`SYSLIB1024`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1025`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1026`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1027`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1028`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1029`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1030`__ | JsonSourceGenerator did not generate serialization metadata for type | | __`SYSLIB1031`__ | JsonSourceGenerator encountered a duplicate JsonTypeInfo property name | | __`SYSLIB1032`__ | JsonSourceGenerator encountered a context class that is not partial | | __`SYSLIB1033`__ | JsonSourceGenerator encountered a type that has multiple [JsonConstructor] annotations| | __`SYSLIB1034`__ | *_`SYSLIB1034` reserved for System.Text.Json.SourceGeneration._* | | __`SYSLIB1035`__ | JsonSourceGenerator encountered a type that has multiple [JsonExtensionData] annotations | | __`SYSLIB1036`__ | JsonSourceGenerator encountered an invalid [JsonExtensionData] annotation | | __`SYSLIB1037`__ | JsonSourceGenerator encountered a type with init-only properties for which deserialization is not supported | | __`SYSLIB1038`__ | JsonSourceGenerator encountered a property annotated with [JsonInclude] that has inaccessible accessors | | __`SYSLIB1039`__ | *_`SYSLIB1039` reserved for System.Text.Json.SourceGeneration._* | | __`SYSLIB1040`__ | Invalid RegexGenerator attribute | | __`SYSLIB1041`__ | Multiple RegexGenerator attribute | | __`SYSLIB1042`__ | Invalid RegexGenerator arguments | | __`SYSLIB1043`__ | RegexGenerator method must have a valid signature | | __`SYSLIB1044`__ | RegexGenerator only supports C# 10 and newer | | __`SYSLIB1045`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1046`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1047`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1048`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1049`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1050`__ | Invalid LibraryImportAttribute usage | | __`SYSLIB1051`__ | Specified type is not supported by source-generated P/Invokes | | __`SYSLIB1052`__ | Specified configuration is not supported by source-generated P/Invokes | | __`SYSLIB1053`__ | Current target framework is not supported by source-generated P/Invokes | | __`SYSLIB1054`__ | Specified LibraryImportAttribute arguments cannot be forwarded to DllImportAttribute | | __`SYSLIB1055`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1056`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1057`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1058`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1059`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1060`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1061`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1062`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1063`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1064`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1065`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1066`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1067`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1068`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1069`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* |
# List of Diagnostics Produced by .NET Libraries APIs ## Obsoletions Per https://github.com/dotnet/designs/blob/master/accepted/2020/better-obsoletion/better-obsoletion.md, we now have a strategy for marking existing APIs as `[Obsolete]`. This takes advantage of the new diagnostic id and URL template mechanisms introduced to `ObsoleteAttribute` in .NET 5. The diagnostic id values reserved for obsoletions are `SYSLIB0001` through `SYSLIB0999`. When obsoleting an API, claim the next three-digit identifier in the `SYSLIB0###` sequence and add it to the list below. The URL template for all obsoletions is `https://aka.ms/dotnet-warnings/{0}`. The `{0}` placeholder is replaced by the compiler with the `SYSLIB0###` identifier. The acceptance criteria for adding an obsoletion includes: * Add the obsoletion to the table below, claiming the next diagnostic id * Ensure the description is meaningful within the context of this table, and without requiring the context of the calling code * Add new constants to `src\libraries\Common\src\System\Obsoletions.cs`, following the existing conventions * A `...Message` const using the same description added to the table below * A `...DiagId` const for the `SYSLIB0###` id * Annotate `src` files by referring to the constants defined from `Obsoletions.cs` * Specify the `UrlFormat = Obsoletions.SharedUrlFormat` * Example: `[Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]` * If the `Obsoletions` type is not available in the project, link it into the project * `<Compile Include="$(CommonPath)System\Obsoletions.cs" Link="Common\System\Obsoletions.cs" />` * Annotate `ref` files using the hard-coded strings copied from `Obsoletions.cs` * This matches our general pattern of `ref` files using hard-coded attribute strings * Example: `[System.ObsoleteAttribute("The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead.", DiagnosticId = "SYSLIB0001", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")]` * If the library builds against downlevel targets earlier than .NET 5.0, then add an internal copy of `ObsoleteAttribute` * The compiler recognizes internal implementations of `ObsoleteAttribute` to enable the `DiagnosticId` and `UrlFormat` properties to light up downlevel * An MSBuild property can be added to the project's first `<PropertyGroup>` to achieve this easily * Example: `<IncludeInternalObsoleteAttribute>true</IncludeInternalObsoleteAttribute>` * This will need to be specified in both the `src` and `ref` projects * If the library contains types that are forwarded within a generated shim * Errors will be received when running `build libs`, with obsoletion errors in `src/libraries/shims/generated` files * This is resolved by adding the obsoletion's diagnostic id to the `<NoWarn>` property for partial facade assemblies * That property is found in `src/libraries/Directory.Build.targets` * Search for the "Ignore Obsolete errors within the generated shims that type-forward types" comment and add the appropriate diagnostic id to the comment and the `<NoWarn>` property (other SYSLIB diagnostics already exist there) * Apply the `breaking-change` label to the PR that introduces the obsoletion * A bot will automatically apply the `needs-breaking-change-doc-created` label when the `breaking-change` label is detected * Follow up with the breaking change process to communicate and document the breaking change * In the breaking-change issue filed in [dotnet/docs](https://github.com/dotnet/docs), specifically mention that this breaking change is an obsoletion with a `SYSLIB` diagnostic id * The documentation team will produce a PR that adds the obsoletion to the [SYSLIB warnings](https://docs.microsoft.com/en-us/dotnet/core/compatibility/syslib-obsoletions) page * That PR will also add a new URL specific to this diagnostic ID; e.g. [SYSLIB0001](https://docs.microsoft.com/en-us/dotnet/core/compatibility/syslib-warnings/syslib0001) * Connect with `@gewarren` or `@BillWagner` with any questions * Register the `SYSLIB0###` URL in `aka.ms` * The vanity name will be `dotnet-warnings/syslib0###` * Ensure the link's group owner matches the group owner of `dotnet-warnings/syslib0001` * Connect with `@jeffhandley`, `@GrabYourPitchforks`, or `@gewarren` with any questions An example obsoletion PR that can be referenced where each of the above criteria was met is: * [Implement new GetContextAPI overloads (#49186)](https://github.com/dotnet/runtime/pull/49186/files) The PR that reveals the implementation of the `<IncludeInternalObsoleteAttribute>` property was: * [Mark DirectoryServices CAS APIs as Obsolete (#40756)](https://github.com/dotnet/runtime/pull/40756/files) ### Obsoletion Diagnostics (`SYSLIB0001` - `SYSLIB0999`) | Diagnostic ID | Description | | :---------------- | :---------- | | __`SYSLIB0001`__ | The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead. | | __`SYSLIB0002`__ | PrincipalPermissionAttribute is not honored by the runtime and must not be used. | | __`SYSLIB0003`__ | Code Access Security is not supported or honored by the runtime. | | __`SYSLIB0004`__ | The Constrained Execution Region (CER) feature is not supported. | | __`SYSLIB0005`__ | The Global Assembly Cache is not supported. | | __`SYSLIB0006`__ | Thread.Abort is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0007`__ | The default implementation of this cryptography algorithm is not supported. | | __`SYSLIB0008`__ | The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0009`__ | The AuthenticationManager Authenticate and PreAuthenticate methods are not supported and throw PlatformNotSupportedException. | | __`SYSLIB0010`__ | This Remoting API is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0011`__ | `BinaryFormatter` serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for recommended alternatives. | | __`SYSLIB0012`__ | Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead. | | __`SYSLIB0013`__ | Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead. | | __`SYSLIB0014`__ | WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead. | | __`SYSLIB0015`__ | DisablePrivateReflectionAttribute has no effect in .NET 6.0+. | | __`SYSLIB0016`__ | Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations. | | __`SYSLIB0017`__ | Strong name signing is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0018`__ | ReflectionOnly loading is not supported and throws PlatformNotSupportedException. | | __`SYSLIB0019`__ | RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException. | | __`SYSLIB0020`__ | JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull. | | __`SYSLIB0021`__ | Derived cryptographic types are obsolete. Use the Create method on the base type instead. | | __`SYSLIB0022`__ | The Rijndael and RijndaelManaged types are obsolete. Use Aes instead. | | __`SYSLIB0023`__ | RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead. | | __`SYSLIB0024`__ | Creating and unloading AppDomains is not supported and throws an exception. | | __`SYSLIB0025`__ | SuppressIldasmAttribute has no effect in .NET 6.0+. | | __`SYSLIB0026`__ | X509Certificate and X509Certificate2 are immutable. Use the appropriate constructor to create a new certificate. | | __`SYSLIB0027`__ | PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey. | | __`SYSLIB0028`__ | X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key. | | __`SYSLIB0029`__ | ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported. | | __`SYSLIB0030`__ | HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter. | | __`SYSLIB0031`__ | EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1. | | __`SYSLIB0032`__ | Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored. | | __`SYSLIB0033`__ | Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead. | | __`SYSLIB0034`__ | CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead. | | __`SYSLIB0035`__ | ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner. | | __`SYSLIB0036`__ | Regex.CompileToAssembly is obsolete and not supported. Use RegexGeneratorAttribute with the regular expression source generator instead. | | __`SYSLIB0037`__ | AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported. | | __`SYSLIB0038`__ | SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information. | | __`SYSLIB0039`__ | TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults. | | __`SYSLIB0040`__ | EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code. | ## Analyzer Warnings The diagnostic id values reserved for .NET Libraries analyzer warnings are `SYSLIB1001` through `SYSLIB1999`. When creating a new analyzer that ships as part of the Libraries (and not part of the SDK), claim the next three-digit identifier in the `SYSLIB1###` sequence and add it to the list below. ### Analyzer Diagnostics (`SYSLIB1001` - `SYSLIB1999`) | Diagnostic ID | Description | | :---------------- | :---------- | | __`SYSLIB1001`__ | Logging method names cannot start with _ | | __`SYSLIB1002`__ | Don't include log level parameters as templates in the logging message | | __`SYSLIB1003`__ | InvalidLoggingMethodParameterNameTitle | | __`SYSLIB1004`__ | Logging class cannot be in nested types | | __`SYSLIB1005`__ | Could not find a required type definition | | __`SYSLIB1006`__ | Multiple logging methods cannot use the same event id within a class | | __`SYSLIB1007`__ | Logging methods must return void | | __`SYSLIB1008`__ | One of the arguments to a logging method must implement the Microsoft.Extensions.Logging.ILogger interface | | __`SYSLIB1009`__ | Logging methods must be static | | __`SYSLIB1010`__ | Logging methods must be partial | | __`SYSLIB1011`__ | Logging methods cannot be generic | | __`SYSLIB1012`__ | Redundant qualifier in logging message | | __`SYSLIB1013`__ | Don't include exception parameters as templates in the logging message | | __`SYSLIB1014`__ | Logging template has no corresponding method argument | | __`SYSLIB1015`__ | Argument is not referenced from the logging message | | __`SYSLIB1016`__ | Logging methods cannot have a body | | __`SYSLIB1017`__ | A LogLevel value must be supplied in the LoggerMessage attribute or as a parameter to the logging method | | __`SYSLIB1018`__ | Don't include logger parameters as templates in the logging message | | __`SYSLIB1019`__ | Couldn't find a field of type Microsoft.Extensions.Logging.ILogger | | __`SYSLIB1020`__ | Found multiple fields of type Microsoft.Extensions.Logging.ILogger | | __`SYSLIB1021`__ | Can't have the same template with different casing | | __`SYSLIB1022`__ | Can't have malformed format strings (like dangling {, etc) | | __`SYSLIB1023`__ | Generating more than 6 arguments is not supported | | __`SYSLIB1024`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1025`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1026`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1027`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1028`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1029`__ | *_`SYSLIB1024`-`SYSLIB1029` reserved for logging._* | | __`SYSLIB1030`__ | JsonSourceGenerator did not generate serialization metadata for type | | __`SYSLIB1031`__ | JsonSourceGenerator encountered a duplicate JsonTypeInfo property name | | __`SYSLIB1032`__ | JsonSourceGenerator encountered a context class that is not partial | | __`SYSLIB1033`__ | JsonSourceGenerator encountered a type that has multiple [JsonConstructor] annotations| | __`SYSLIB1034`__ | *_`SYSLIB1034` reserved for System.Text.Json.SourceGeneration._* | | __`SYSLIB1035`__ | JsonSourceGenerator encountered a type that has multiple [JsonExtensionData] annotations | | __`SYSLIB1036`__ | JsonSourceGenerator encountered an invalid [JsonExtensionData] annotation | | __`SYSLIB1037`__ | JsonSourceGenerator encountered a type with init-only properties for which deserialization is not supported | | __`SYSLIB1038`__ | JsonSourceGenerator encountered a property annotated with [JsonInclude] that has inaccessible accessors | | __`SYSLIB1039`__ | *_`SYSLIB1039` reserved for System.Text.Json.SourceGeneration._* | | __`SYSLIB1040`__ | Invalid RegexGenerator attribute | | __`SYSLIB1041`__ | Multiple RegexGenerator attribute | | __`SYSLIB1042`__ | Invalid RegexGenerator arguments | | __`SYSLIB1043`__ | RegexGenerator method must have a valid signature | | __`SYSLIB1044`__ | RegexGenerator only supports C# 10 and newer | | __`SYSLIB1045`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1046`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1047`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1048`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1049`__ | *_`SYSLIB1045`-`SYSLIB1049` reserved for System.Text.RegularExpressions.Generator._* | | __`SYSLIB1050`__ | Invalid LibraryImportAttribute usage | | __`SYSLIB1051`__ | Specified type is not supported by source-generated P/Invokes | | __`SYSLIB1052`__ | Specified configuration is not supported by source-generated P/Invokes | | __`SYSLIB1053`__ | Current target framework is not supported by source-generated P/Invokes | | __`SYSLIB1054`__ | Specified LibraryImportAttribute arguments cannot be forwarded to DllImportAttribute | | __`SYSLIB1055`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1056`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1057`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1058`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1059`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1060`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1061`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1062`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1063`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1064`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1065`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1066`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1067`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1068`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* | | __`SYSLIB1069`__ | *_`SYSLIB1055`-`SYSLIB1069` reserved for Microsoft.Interop.LibraryImportGenerator._* |
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/Common/src/System/Obsoletions.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 { internal static class Obsoletions { internal const string SharedUrlFormat = "https://aka.ms/dotnet-warnings/{0}"; // Please see docs\project\list-of-diagnostics.md for instructions on the steps required // to introduce a new obsoletion, apply it to downlevel builds, claim a diagnostic id, // and ensure the "aka.ms/dotnet-warnings/{0}" URL points to documentation for the obsoletion // The diagnostic ids reserved for obsoletions are SYSLIB0### (SYSLIB0001 - SYSLIB0999). internal const string SystemTextEncodingUTF7Message = "The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead."; internal const string SystemTextEncodingUTF7DiagId = "SYSLIB0001"; internal const string PrincipalPermissionAttributeMessage = "PrincipalPermissionAttribute is not honored by the runtime and must not be used."; internal const string PrincipalPermissionAttributeDiagId = "SYSLIB0002"; internal const string CodeAccessSecurityMessage = "Code Access Security is not supported or honored by the runtime."; internal const string CodeAccessSecurityDiagId = "SYSLIB0003"; internal const string ConstrainedExecutionRegionMessage = "The Constrained Execution Region (CER) feature is not supported."; internal const string ConstrainedExecutionRegionDiagId = "SYSLIB0004"; internal const string GlobalAssemblyCacheMessage = "The Global Assembly Cache is not supported."; internal const string GlobalAssemblyCacheDiagId = "SYSLIB0005"; internal const string ThreadAbortMessage = "Thread.Abort is not supported and throws PlatformNotSupportedException."; internal const string ThreadResetAbortMessage = "Thread.ResetAbort is not supported and throws PlatformNotSupportedException."; internal const string ThreadAbortDiagId = "SYSLIB0006"; internal const string DefaultCryptoAlgorithmsMessage = "The default implementation of this cryptography algorithm is not supported."; internal const string DefaultCryptoAlgorithmsDiagId = "SYSLIB0007"; internal const string CreatePdbGeneratorMessage = "The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException."; internal const string CreatePdbGeneratorDiagId = "SYSLIB0008"; internal const string AuthenticationManagerMessage = "The AuthenticationManager Authenticate and PreAuthenticate methods are not supported and throw PlatformNotSupportedException."; internal const string AuthenticationManagerDiagId = "SYSLIB0009"; internal const string RemotingApisMessage = "This Remoting API is not supported and throws PlatformNotSupportedException."; internal const string RemotingApisDiagId = "SYSLIB0010"; internal const string BinaryFormatterMessage = "BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information."; internal const string BinaryFormatterDiagId = "SYSLIB0011"; internal const string CodeBaseMessage = "Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead."; internal const string CodeBaseDiagId = "SYSLIB0012"; internal const string EscapeUriStringMessage = "Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead."; internal const string EscapeUriStringDiagId = "SYSLIB0013"; internal const string WebRequestMessage = "WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead."; internal const string WebRequestDiagId = "SYSLIB0014"; internal const string DisablePrivateReflectionAttributeMessage = "DisablePrivateReflectionAttribute has no effect in .NET 6.0+."; internal const string DisablePrivateReflectionAttributeDiagId = "SYSLIB0015"; internal const string GetContextInfoMessage = "Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations."; internal const string GetContextInfoDiagId = "SYSLIB0016"; internal const string StrongNameKeyPairMessage = "Strong name signing is not supported and throws PlatformNotSupportedException."; internal const string StrongNameKeyPairDiagId = "SYSLIB0017"; internal const string ReflectionOnlyLoadingMessage = "ReflectionOnly loading is not supported and throws PlatformNotSupportedException."; internal const string ReflectionOnlyLoadingDiagId = "SYSLIB0018"; internal const string RuntimeEnvironmentMessage = "RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException."; internal const string RuntimeEnvironmentDiagId = "SYSLIB0019"; internal const string JsonSerializerOptionsIgnoreNullValuesMessage = "JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull."; internal const string JsonSerializerOptionsIgnoreNullValuesDiagId = "SYSLIB0020"; internal const string DerivedCryptographicTypesMessage = "Derived cryptographic types are obsolete. Use the Create method on the base type instead."; internal const string DerivedCryptographicTypesDiagId = "SYSLIB0021"; internal const string RijndaelMessage = "The Rijndael and RijndaelManaged types are obsolete. Use Aes instead."; internal const string RijndaelDiagId = "SYSLIB0022"; internal const string RNGCryptoServiceProviderMessage = "RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead."; internal const string RNGCryptoServiceProviderDiagId = "SYSLIB0023"; internal const string AppDomainCreateUnloadMessage = "Creating and unloading AppDomains is not supported and throws an exception."; internal const string AppDomainCreateUnloadDiagId = "SYSLIB0024"; internal const string SuppressIldasmAttributeMessage = "SuppressIldasmAttribute has no effect in .NET 6.0+."; internal const string SuppressIldasmAttributeDiagId = "SYSLIB0025"; internal const string X509CertificateImmutableMessage = "X509Certificate and X509Certificate2 are immutable. Use the appropriate constructor to create a new certificate."; internal const string X509CertificateImmutableDiagId = "SYSLIB0026"; internal const string PublicKeyPropertyMessage = "PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey."; internal const string PublicKeyPropertyDiagId = "SYSLIB0027"; internal const string X509CertificatePrivateKeyMessage = "X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key."; internal const string X509CertificatePrivateKeyDiagId = "SYSLIB0028"; internal const string ProduceLegacyHmacValuesMessage = "ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported."; internal const string ProduceLegacyHmacValuesDiagId = "SYSLIB0029"; internal const string UseManagedSha1Message = "HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter."; internal const string UseManagedSha1DiagId = "SYSLIB0030"; internal const string CryptoConfigEncodeOIDMessage = "EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1."; internal const string CryptoConfigEncodeOIDDiagId = "SYSLIB0031"; internal const string CorruptedStateRecoveryMessage = "Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored."; internal const string CorruptedStateRecoveryDiagId = "SYSLIB0032"; internal const string Rfc2898CryptDeriveKeyMessage = "Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead."; internal const string Rfc2898CryptDeriveKeyDiagId = "SYSLIB0033"; internal const string CmsSignerCspParamsCtorMessage = "CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead."; internal const string CmsSignerCspParamsCtorDiagId = "SYSLIB0034"; internal const string SignerInfoCounterSigMessage = "ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner."; internal const string SignerInfoCounterSigDiagId = "SYSLIB0035"; internal const string RegexCompileToAssemblyMessage = "Regex.CompileToAssembly is obsolete and not supported. Use the RegexGeneratorAttribute with the regular expression source generator instead."; internal const string RegexCompileToAssemblyDiagId = "SYSLIB0036"; internal const string AssemblyNameMembersMessage = "AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported."; internal const string AssemblyNameMembersDiagId = "SYSLIB0037"; internal const string SystemDataSerializationFormatBinaryMessage = "SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information."; internal const string SystemDataSerializationFormatBinaryDiagId = "SYSLIB0038"; internal const string TlsVersion10and11Message = "TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults."; internal const string TlsVersion10and11DiagId = "SYSLIB0039"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System { internal static class Obsoletions { internal const string SharedUrlFormat = "https://aka.ms/dotnet-warnings/{0}"; // Please see docs\project\list-of-diagnostics.md for instructions on the steps required // to introduce a new obsoletion, apply it to downlevel builds, claim a diagnostic id, // and ensure the "aka.ms/dotnet-warnings/{0}" URL points to documentation for the obsoletion // The diagnostic ids reserved for obsoletions are SYSLIB0### (SYSLIB0001 - SYSLIB0999). internal const string SystemTextEncodingUTF7Message = "The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead."; internal const string SystemTextEncodingUTF7DiagId = "SYSLIB0001"; internal const string PrincipalPermissionAttributeMessage = "PrincipalPermissionAttribute is not honored by the runtime and must not be used."; internal const string PrincipalPermissionAttributeDiagId = "SYSLIB0002"; internal const string CodeAccessSecurityMessage = "Code Access Security is not supported or honored by the runtime."; internal const string CodeAccessSecurityDiagId = "SYSLIB0003"; internal const string ConstrainedExecutionRegionMessage = "The Constrained Execution Region (CER) feature is not supported."; internal const string ConstrainedExecutionRegionDiagId = "SYSLIB0004"; internal const string GlobalAssemblyCacheMessage = "The Global Assembly Cache is not supported."; internal const string GlobalAssemblyCacheDiagId = "SYSLIB0005"; internal const string ThreadAbortMessage = "Thread.Abort is not supported and throws PlatformNotSupportedException."; internal const string ThreadResetAbortMessage = "Thread.ResetAbort is not supported and throws PlatformNotSupportedException."; internal const string ThreadAbortDiagId = "SYSLIB0006"; internal const string DefaultCryptoAlgorithmsMessage = "The default implementation of this cryptography algorithm is not supported."; internal const string DefaultCryptoAlgorithmsDiagId = "SYSLIB0007"; internal const string CreatePdbGeneratorMessage = "The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException."; internal const string CreatePdbGeneratorDiagId = "SYSLIB0008"; internal const string AuthenticationManagerMessage = "The AuthenticationManager Authenticate and PreAuthenticate methods are not supported and throw PlatformNotSupportedException."; internal const string AuthenticationManagerDiagId = "SYSLIB0009"; internal const string RemotingApisMessage = "This Remoting API is not supported and throws PlatformNotSupportedException."; internal const string RemotingApisDiagId = "SYSLIB0010"; internal const string BinaryFormatterMessage = "BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information."; internal const string BinaryFormatterDiagId = "SYSLIB0011"; internal const string CodeBaseMessage = "Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead."; internal const string CodeBaseDiagId = "SYSLIB0012"; internal const string EscapeUriStringMessage = "Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead."; internal const string EscapeUriStringDiagId = "SYSLIB0013"; internal const string WebRequestMessage = "WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead."; internal const string WebRequestDiagId = "SYSLIB0014"; internal const string DisablePrivateReflectionAttributeMessage = "DisablePrivateReflectionAttribute has no effect in .NET 6.0+."; internal const string DisablePrivateReflectionAttributeDiagId = "SYSLIB0015"; internal const string GetContextInfoMessage = "Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations."; internal const string GetContextInfoDiagId = "SYSLIB0016"; internal const string StrongNameKeyPairMessage = "Strong name signing is not supported and throws PlatformNotSupportedException."; internal const string StrongNameKeyPairDiagId = "SYSLIB0017"; internal const string ReflectionOnlyLoadingMessage = "ReflectionOnly loading is not supported and throws PlatformNotSupportedException."; internal const string ReflectionOnlyLoadingDiagId = "SYSLIB0018"; internal const string RuntimeEnvironmentMessage = "RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException."; internal const string RuntimeEnvironmentDiagId = "SYSLIB0019"; internal const string JsonSerializerOptionsIgnoreNullValuesMessage = "JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull."; internal const string JsonSerializerOptionsIgnoreNullValuesDiagId = "SYSLIB0020"; internal const string DerivedCryptographicTypesMessage = "Derived cryptographic types are obsolete. Use the Create method on the base type instead."; internal const string DerivedCryptographicTypesDiagId = "SYSLIB0021"; internal const string RijndaelMessage = "The Rijndael and RijndaelManaged types are obsolete. Use Aes instead."; internal const string RijndaelDiagId = "SYSLIB0022"; internal const string RNGCryptoServiceProviderMessage = "RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead."; internal const string RNGCryptoServiceProviderDiagId = "SYSLIB0023"; internal const string AppDomainCreateUnloadMessage = "Creating and unloading AppDomains is not supported and throws an exception."; internal const string AppDomainCreateUnloadDiagId = "SYSLIB0024"; internal const string SuppressIldasmAttributeMessage = "SuppressIldasmAttribute has no effect in .NET 6.0+."; internal const string SuppressIldasmAttributeDiagId = "SYSLIB0025"; internal const string X509CertificateImmutableMessage = "X509Certificate and X509Certificate2 are immutable. Use the appropriate constructor to create a new certificate."; internal const string X509CertificateImmutableDiagId = "SYSLIB0026"; internal const string PublicKeyPropertyMessage = "PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey."; internal const string PublicKeyPropertyDiagId = "SYSLIB0027"; internal const string X509CertificatePrivateKeyMessage = "X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key."; internal const string X509CertificatePrivateKeyDiagId = "SYSLIB0028"; internal const string ProduceLegacyHmacValuesMessage = "ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported."; internal const string ProduceLegacyHmacValuesDiagId = "SYSLIB0029"; internal const string UseManagedSha1Message = "HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter."; internal const string UseManagedSha1DiagId = "SYSLIB0030"; internal const string CryptoConfigEncodeOIDMessage = "EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1."; internal const string CryptoConfigEncodeOIDDiagId = "SYSLIB0031"; internal const string CorruptedStateRecoveryMessage = "Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored."; internal const string CorruptedStateRecoveryDiagId = "SYSLIB0032"; internal const string Rfc2898CryptDeriveKeyMessage = "Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead."; internal const string Rfc2898CryptDeriveKeyDiagId = "SYSLIB0033"; internal const string CmsSignerCspParamsCtorMessage = "CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead."; internal const string CmsSignerCspParamsCtorDiagId = "SYSLIB0034"; internal const string SignerInfoCounterSigMessage = "ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner."; internal const string SignerInfoCounterSigDiagId = "SYSLIB0035"; internal const string RegexCompileToAssemblyMessage = "Regex.CompileToAssembly is obsolete and not supported. Use the RegexGeneratorAttribute with the regular expression source generator instead."; internal const string RegexCompileToAssemblyDiagId = "SYSLIB0036"; internal const string AssemblyNameMembersMessage = "AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported."; internal const string AssemblyNameMembersDiagId = "SYSLIB0037"; internal const string SystemDataSerializationFormatBinaryMessage = "SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information."; internal const string SystemDataSerializationFormatBinaryDiagId = "SYSLIB0038"; internal const string TlsVersion10and11Message = "TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults."; internal const string TlsVersion10and11DiagId = "SYSLIB0039"; internal const string EncryptionPolicyMessage = "EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code."; internal const string EncryptionPolicyDiagId = "SYSLIB0040"; } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Interop/SafeMsQuicConfigurationHandle.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Net.Security; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using static System.Net.Quic.Implementations.MsQuic.Internal.MsQuicNativeMethods; namespace System.Net.Quic.Implementations.MsQuic.Internal { internal sealed class SafeMsQuicConfigurationHandle : SafeHandle { private static readonly FieldInfo _contextCertificate = typeof(SslStreamCertificateContext).GetField("Certificate", BindingFlags.NonPublic | BindingFlags.Instance)!; private static readonly FieldInfo _contextChain = typeof(SslStreamCertificateContext).GetField("IntermediateCertificates", BindingFlags.NonPublic | BindingFlags.Instance)!; public override bool IsInvalid => handle == IntPtr.Zero; public SafeMsQuicConfigurationHandle() : base(IntPtr.Zero, ownsHandle: true) { } protected override bool ReleaseHandle() { MsQuicApi.Api.ConfigurationCloseDelegate(handle); SetHandle(IntPtr.Zero); return true; } // TODO: consider moving the static code from here to keep all the handle classes small and simple. public static SafeMsQuicConfigurationHandle Create(QuicClientConnectionOptions options) { X509Certificate? certificate = null; if (options.ClientAuthenticationOptions != null) { if (options.ClientAuthenticationOptions.CipherSuitesPolicy != null) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(options.ClientAuthenticationOptions.CipherSuitesPolicy))); } if (options.ClientAuthenticationOptions.EncryptionPolicy == EncryptionPolicy.NoEncryption) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(options.ClientAuthenticationOptions.EncryptionPolicy))); } if (options.ClientAuthenticationOptions.ClientCertificates != null) { foreach (var cert in options.ClientAuthenticationOptions.ClientCertificates) { try { if (((X509Certificate2)cert).HasPrivateKey) { // Pick first certificate with private key. certificate = cert; break; } } catch { } } } } return Create(options, QUIC_CREDENTIAL_FLAGS.CLIENT, certificate: certificate, certificateContext: null, options.ClientAuthenticationOptions?.ApplicationProtocols); } public static SafeMsQuicConfigurationHandle Create(QuicOptions options, SslServerAuthenticationOptions? serverAuthenticationOptions, string? targetHost = null) { QUIC_CREDENTIAL_FLAGS flags = QUIC_CREDENTIAL_FLAGS.NONE; X509Certificate? certificate = serverAuthenticationOptions?.ServerCertificate; if (serverAuthenticationOptions != null) { if (serverAuthenticationOptions.CipherSuitesPolicy != null) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(serverAuthenticationOptions.CipherSuitesPolicy))); } if (serverAuthenticationOptions.EncryptionPolicy == EncryptionPolicy.NoEncryption) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(serverAuthenticationOptions.EncryptionPolicy))); } if (serverAuthenticationOptions.ClientCertificateRequired) { flags |= QUIC_CREDENTIAL_FLAGS.REQUIRE_CLIENT_AUTHENTICATION | QUIC_CREDENTIAL_FLAGS.INDICATE_CERTIFICATE_RECEIVED | QUIC_CREDENTIAL_FLAGS.NO_CERTIFICATE_VALIDATION; } if (certificate == null && serverAuthenticationOptions?.ServerCertificateSelectionCallback != null && targetHost != null) { certificate = serverAuthenticationOptions.ServerCertificateSelectionCallback(options, targetHost); } } return Create(options, flags, certificate, serverAuthenticationOptions?.ServerCertificateContext, serverAuthenticationOptions?.ApplicationProtocols); } // TODO: this is called from MsQuicListener and when it fails it wreaks havoc in MsQuicListener finalizer. // Consider moving bigger logic like this outside of constructor call chains. private static unsafe SafeMsQuicConfigurationHandle Create(QuicOptions options, QUIC_CREDENTIAL_FLAGS flags, X509Certificate? certificate, SslStreamCertificateContext? certificateContext, List<SslApplicationProtocol>? alpnProtocols) { // TODO: some of these checks should be done by the QuicOptions type. if (alpnProtocols == null || alpnProtocols.Count == 0) { throw new Exception("At least one SslApplicationProtocol value must be present in SslClientAuthenticationOptions or SslServerAuthenticationOptions."); } if (options.MaxBidirectionalStreams > ushort.MaxValue) { throw new Exception("MaxBidirectionalStreams overflow."); } if (options.MaxBidirectionalStreams > ushort.MaxValue) { throw new Exception("MaxBidirectionalStreams overflow."); } if ((flags & QUIC_CREDENTIAL_FLAGS.CLIENT) == 0) { if (certificate == null && certificateContext == null) { throw new Exception("Server must provide certificate"); } } else { flags |= QUIC_CREDENTIAL_FLAGS.INDICATE_CERTIFICATE_RECEIVED | QUIC_CREDENTIAL_FLAGS.NO_CERTIFICATE_VALIDATION; } if (!OperatingSystem.IsWindows()) { // Use certificate handles on Windows, fall-back to ASN1 otherwise. flags |= QUIC_CREDENTIAL_FLAGS.USE_PORTABLE_CERTIFICATES; } Debug.Assert(!MsQuicApi.Api.Registration.IsInvalid); var settings = new QuicSettings { IsSetFlags = QuicSettingsIsSetFlags.PeerBidiStreamCount | QuicSettingsIsSetFlags.PeerUnidiStreamCount, PeerBidiStreamCount = (ushort)options.MaxBidirectionalStreams, PeerUnidiStreamCount = (ushort)options.MaxUnidirectionalStreams }; if (options.IdleTimeout != Timeout.InfiniteTimeSpan) { if (options.IdleTimeout <= TimeSpan.Zero) throw new Exception("IdleTimeout must not be negative."); ulong ms = (ulong)options.IdleTimeout.Ticks / TimeSpan.TicksPerMillisecond; if (ms > (1ul << 62) - 1) throw new Exception("IdleTimeout is too large (max 2^62-1 milliseconds)"); settings.IdleTimeoutMs = (ulong)options.IdleTimeout.TotalMilliseconds; } else { settings.IdleTimeoutMs = 0; } settings.IsSetFlags |= QuicSettingsIsSetFlags.IdleTimeoutMs; uint status; SafeMsQuicConfigurationHandle? configurationHandle; X509Certificate2[]? intermediates = null; MemoryHandle[]? handles = null; QuicBuffer[]? buffers = null; try { MsQuicAlpnHelper.Prepare(alpnProtocols, out handles, out buffers); status = MsQuicApi.Api.ConfigurationOpenDelegate(MsQuicApi.Api.Registration, (QuicBuffer*)Marshal.UnsafeAddrOfPinnedArrayElement(buffers, 0), (uint)alpnProtocols.Count, ref settings, (uint)sizeof(QuicSettings), context: IntPtr.Zero, out configurationHandle); } finally { MsQuicAlpnHelper.Return(ref handles, ref buffers); } QuicExceptionHelpers.ThrowIfFailed(status, "ConfigurationOpen failed."); try { CredentialConfig config = default; config.Flags = flags; // TODO: consider using LOAD_ASYNCHRONOUS with a callback. if (certificateContext != null) { certificate = (X509Certificate2?) _contextCertificate.GetValue(certificateContext); intermediates = (X509Certificate2[]?) _contextChain.GetValue(certificateContext); if (certificate == null || intermediates == null) { throw new ArgumentException(nameof(certificateContext)); } } if (certificate != null) { if (OperatingSystem.IsWindows()) { config.Type = QUIC_CREDENTIAL_TYPE.CONTEXT; config.Certificate = certificate.Handle; status = MsQuicApi.Api.ConfigurationLoadCredentialDelegate(configurationHandle, ref config); } else { CredentialConfigCertificatePkcs12 pkcs12Config; byte[] asn1; if (intermediates?.Length > 0) { X509Certificate2Collection collection = new X509Certificate2Collection(); collection.Add(certificate); for (int i= 0; i < intermediates?.Length; i++) { collection.Add(intermediates[i]); } asn1 = collection.Export(X509ContentType.Pkcs12)!; } else { asn1 = certificate.Export(X509ContentType.Pkcs12); } fixed (void* ptr = asn1) { pkcs12Config.Asn1Blob = (IntPtr)ptr; pkcs12Config.Asn1BlobLength = (uint)asn1.Length; pkcs12Config.PrivateKeyPassword = IntPtr.Zero; config.Type = QUIC_CREDENTIAL_TYPE.PKCS12; config.Certificate = (IntPtr)(&pkcs12Config); status = MsQuicApi.Api.ConfigurationLoadCredentialDelegate(configurationHandle, ref config); } } } else { config.Type = QUIC_CREDENTIAL_TYPE.NONE; status = MsQuicApi.Api.ConfigurationLoadCredentialDelegate(configurationHandle, ref config); } QuicExceptionHelpers.ThrowIfFailed(status, "ConfigurationLoadCredential failed."); } catch { configurationHandle.Dispose(); throw; } return configurationHandle; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Net.Security; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using static System.Net.Quic.Implementations.MsQuic.Internal.MsQuicNativeMethods; namespace System.Net.Quic.Implementations.MsQuic.Internal { internal sealed class SafeMsQuicConfigurationHandle : SafeHandle { private static readonly FieldInfo _contextCertificate = typeof(SslStreamCertificateContext).GetField("Certificate", BindingFlags.NonPublic | BindingFlags.Instance)!; private static readonly FieldInfo _contextChain = typeof(SslStreamCertificateContext).GetField("IntermediateCertificates", BindingFlags.NonPublic | BindingFlags.Instance)!; public override bool IsInvalid => handle == IntPtr.Zero; public SafeMsQuicConfigurationHandle() : base(IntPtr.Zero, ownsHandle: true) { } protected override bool ReleaseHandle() { MsQuicApi.Api.ConfigurationCloseDelegate(handle); SetHandle(IntPtr.Zero); return true; } // TODO: consider moving the static code from here to keep all the handle classes small and simple. public static SafeMsQuicConfigurationHandle Create(QuicClientConnectionOptions options) { X509Certificate? certificate = null; if (options.ClientAuthenticationOptions != null) { if (options.ClientAuthenticationOptions.CipherSuitesPolicy != null) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(options.ClientAuthenticationOptions.CipherSuitesPolicy))); } #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete if (options.ClientAuthenticationOptions.EncryptionPolicy == EncryptionPolicy.NoEncryption) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(options.ClientAuthenticationOptions.EncryptionPolicy))); } #pragma warning restore SYSLIB0040 if (options.ClientAuthenticationOptions.ClientCertificates != null) { foreach (var cert in options.ClientAuthenticationOptions.ClientCertificates) { try { if (((X509Certificate2)cert).HasPrivateKey) { // Pick first certificate with private key. certificate = cert; break; } } catch { } } } } return Create(options, QUIC_CREDENTIAL_FLAGS.CLIENT, certificate: certificate, certificateContext: null, options.ClientAuthenticationOptions?.ApplicationProtocols); } public static SafeMsQuicConfigurationHandle Create(QuicOptions options, SslServerAuthenticationOptions? serverAuthenticationOptions, string? targetHost = null) { QUIC_CREDENTIAL_FLAGS flags = QUIC_CREDENTIAL_FLAGS.NONE; X509Certificate? certificate = serverAuthenticationOptions?.ServerCertificate; if (serverAuthenticationOptions != null) { if (serverAuthenticationOptions.CipherSuitesPolicy != null) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(serverAuthenticationOptions.CipherSuitesPolicy))); } #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete if (serverAuthenticationOptions.EncryptionPolicy == EncryptionPolicy.NoEncryption) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(serverAuthenticationOptions.EncryptionPolicy))); } #pragma warning restore SYSLIB0040 if (serverAuthenticationOptions.ClientCertificateRequired) { flags |= QUIC_CREDENTIAL_FLAGS.REQUIRE_CLIENT_AUTHENTICATION | QUIC_CREDENTIAL_FLAGS.INDICATE_CERTIFICATE_RECEIVED | QUIC_CREDENTIAL_FLAGS.NO_CERTIFICATE_VALIDATION; } if (certificate == null && serverAuthenticationOptions?.ServerCertificateSelectionCallback != null && targetHost != null) { certificate = serverAuthenticationOptions.ServerCertificateSelectionCallback(options, targetHost); } } return Create(options, flags, certificate, serverAuthenticationOptions?.ServerCertificateContext, serverAuthenticationOptions?.ApplicationProtocols); } // TODO: this is called from MsQuicListener and when it fails it wreaks havoc in MsQuicListener finalizer. // Consider moving bigger logic like this outside of constructor call chains. private static unsafe SafeMsQuicConfigurationHandle Create(QuicOptions options, QUIC_CREDENTIAL_FLAGS flags, X509Certificate? certificate, SslStreamCertificateContext? certificateContext, List<SslApplicationProtocol>? alpnProtocols) { // TODO: some of these checks should be done by the QuicOptions type. if (alpnProtocols == null || alpnProtocols.Count == 0) { throw new Exception("At least one SslApplicationProtocol value must be present in SslClientAuthenticationOptions or SslServerAuthenticationOptions."); } if (options.MaxBidirectionalStreams > ushort.MaxValue) { throw new Exception("MaxBidirectionalStreams overflow."); } if (options.MaxBidirectionalStreams > ushort.MaxValue) { throw new Exception("MaxBidirectionalStreams overflow."); } if ((flags & QUIC_CREDENTIAL_FLAGS.CLIENT) == 0) { if (certificate == null && certificateContext == null) { throw new Exception("Server must provide certificate"); } } else { flags |= QUIC_CREDENTIAL_FLAGS.INDICATE_CERTIFICATE_RECEIVED | QUIC_CREDENTIAL_FLAGS.NO_CERTIFICATE_VALIDATION; } if (!OperatingSystem.IsWindows()) { // Use certificate handles on Windows, fall-back to ASN1 otherwise. flags |= QUIC_CREDENTIAL_FLAGS.USE_PORTABLE_CERTIFICATES; } Debug.Assert(!MsQuicApi.Api.Registration.IsInvalid); var settings = new QuicSettings { IsSetFlags = QuicSettingsIsSetFlags.PeerBidiStreamCount | QuicSettingsIsSetFlags.PeerUnidiStreamCount, PeerBidiStreamCount = (ushort)options.MaxBidirectionalStreams, PeerUnidiStreamCount = (ushort)options.MaxUnidirectionalStreams }; if (options.IdleTimeout != Timeout.InfiniteTimeSpan) { if (options.IdleTimeout <= TimeSpan.Zero) throw new Exception("IdleTimeout must not be negative."); ulong ms = (ulong)options.IdleTimeout.Ticks / TimeSpan.TicksPerMillisecond; if (ms > (1ul << 62) - 1) throw new Exception("IdleTimeout is too large (max 2^62-1 milliseconds)"); settings.IdleTimeoutMs = (ulong)options.IdleTimeout.TotalMilliseconds; } else { settings.IdleTimeoutMs = 0; } settings.IsSetFlags |= QuicSettingsIsSetFlags.IdleTimeoutMs; uint status; SafeMsQuicConfigurationHandle? configurationHandle; X509Certificate2[]? intermediates = null; MemoryHandle[]? handles = null; QuicBuffer[]? buffers = null; try { MsQuicAlpnHelper.Prepare(alpnProtocols, out handles, out buffers); status = MsQuicApi.Api.ConfigurationOpenDelegate(MsQuicApi.Api.Registration, (QuicBuffer*)Marshal.UnsafeAddrOfPinnedArrayElement(buffers, 0), (uint)alpnProtocols.Count, ref settings, (uint)sizeof(QuicSettings), context: IntPtr.Zero, out configurationHandle); } finally { MsQuicAlpnHelper.Return(ref handles, ref buffers); } QuicExceptionHelpers.ThrowIfFailed(status, "ConfigurationOpen failed."); try { CredentialConfig config = default; config.Flags = flags; // TODO: consider using LOAD_ASYNCHRONOUS with a callback. if (certificateContext != null) { certificate = (X509Certificate2?) _contextCertificate.GetValue(certificateContext); intermediates = (X509Certificate2[]?) _contextChain.GetValue(certificateContext); if (certificate == null || intermediates == null) { throw new ArgumentException(nameof(certificateContext)); } } if (certificate != null) { if (OperatingSystem.IsWindows()) { config.Type = QUIC_CREDENTIAL_TYPE.CONTEXT; config.Certificate = certificate.Handle; status = MsQuicApi.Api.ConfigurationLoadCredentialDelegate(configurationHandle, ref config); } else { CredentialConfigCertificatePkcs12 pkcs12Config; byte[] asn1; if (intermediates?.Length > 0) { X509Certificate2Collection collection = new X509Certificate2Collection(); collection.Add(certificate); for (int i= 0; i < intermediates?.Length; i++) { collection.Add(intermediates[i]); } asn1 = collection.Export(X509ContentType.Pkcs12)!; } else { asn1 = certificate.Export(X509ContentType.Pkcs12); } fixed (void* ptr = asn1) { pkcs12Config.Asn1Blob = (IntPtr)ptr; pkcs12Config.Asn1BlobLength = (uint)asn1.Length; pkcs12Config.PrivateKeyPassword = IntPtr.Zero; config.Type = QUIC_CREDENTIAL_TYPE.PKCS12; config.Certificate = (IntPtr)(&pkcs12Config); status = MsQuicApi.Api.ConfigurationLoadCredentialDelegate(configurationHandle, ref config); } } } else { config.Type = QUIC_CREDENTIAL_TYPE.NONE; status = MsQuicApi.Api.ConfigurationLoadCredentialDelegate(configurationHandle, ref config); } QuicExceptionHelpers.ThrowIfFailed(status, "ConfigurationLoadCredential failed."); } catch { configurationHandle.Dispose(); throw; } return configurationHandle; } } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/ref/System.Net.Security.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Net.Security { public abstract partial class AuthenticatedStream : System.IO.Stream { protected AuthenticatedStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen) { } protected System.IO.Stream InnerStream { get { throw null; } } public abstract bool IsAuthenticated { get; } public abstract bool IsEncrypted { get; } public abstract bool IsMutuallyAuthenticated { get; } public abstract bool IsServer { get; } public abstract bool IsSigned { get; } public bool LeaveInnerStreamOpen { get { throw null; } } protected override void Dispose(bool disposing) { } public override System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } } public sealed partial class CipherSuitesPolicy { [System.CLSCompliantAttribute(false)] public CipherSuitesPolicy(System.Collections.Generic.IEnumerable<System.Net.Security.TlsCipherSuite> allowedCipherSuites) { } [System.CLSCompliantAttribute(false)] public System.Collections.Generic.IEnumerable<System.Net.Security.TlsCipherSuite> AllowedCipherSuites { get { throw null; } } } public enum EncryptionPolicy { RequireEncryption = 0, AllowNoEncryption = 1, NoEncryption = 2, } public delegate System.Security.Cryptography.X509Certificates.X509Certificate LocalCertificateSelectionCallback(object sender, string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection localCertificates, System.Security.Cryptography.X509Certificates.X509Certificate? remoteCertificate, string[] acceptableIssuers); [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] public partial class NegotiateStream : System.Net.Security.AuthenticatedStream { public NegotiateStream(System.IO.Stream innerStream) : base (default(System.IO.Stream), default(bool)) { } public NegotiateStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen) : base (default(System.IO.Stream), default(bool)) { } public override bool CanRead { get { throw null; } } public override bool CanSeek { get { throw null; } } public override bool CanTimeout { get { throw null; } } public override bool CanWrite { get { throw null; } } public virtual System.Security.Principal.TokenImpersonationLevel ImpersonationLevel { get { throw null; } } public override bool IsAuthenticated { get { throw null; } } public override bool IsEncrypted { get { throw null; } } public override bool IsMutuallyAuthenticated { get { throw null; } } public override bool IsServer { get { throw null; } } public override bool IsSigned { get { throw null; } } public override long Length { get { throw null; } } public override long Position { get { throw null; } set { } } public override int ReadTimeout { get { throw null; } set { } } public virtual System.Security.Principal.IIdentity RemoteIdentity { get { throw null; } } public override int WriteTimeout { get { throw null; } set { } } public virtual void AuthenticateAsClient() { } public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName) { } public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { } public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, string targetName) { } public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync() { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.NetworkCredential credential, string targetName) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.NetworkCredential credential, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { throw null; } public virtual void AuthenticateAsServer() { } public virtual void AuthenticateAsServer(System.Net.NetworkCredential credential, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { } public virtual void AuthenticateAsServer(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { } public virtual void AuthenticateAsServer(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy) { } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync() { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Net.NetworkCredential credential, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsClient(System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, string targetName, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsServer(System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Net.NetworkCredential credential, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } protected override void Dispose(bool disposing) { } public override System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } public virtual void EndAuthenticateAsClient(System.IAsyncResult asyncResult) { } public virtual void EndAuthenticateAsServer(System.IAsyncResult asyncResult) { } public override int EndRead(System.IAsyncResult asyncResult) { throw null; } public override void EndWrite(System.IAsyncResult asyncResult) { } public override void Flush() { } public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public override int Read(byte[] buffer, int offset, int count) { throw null; } public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask<int> ReadAsync(System.Memory<byte> buffer, System.Threading.CancellationToken cancellationToken = default) { throw null; } public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; } public override void SetLength(long value) { } public override void Write(byte[] buffer, int offset, int count) { } public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken = default) { throw null; } } public enum ProtectionLevel { None = 0, Sign = 1, EncryptAndSign = 2, } public readonly struct SslClientHelloInfo { public string ServerName { get; } public System.Security.Authentication.SslProtocols SslProtocols { get; } internal SslClientHelloInfo(string serverName, System.Security.Authentication.SslProtocols sslProtocol) { throw null; } } public delegate bool RemoteCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate? certificate, System.Security.Cryptography.X509Certificates.X509Chain? chain, System.Net.Security.SslPolicyErrors sslPolicyErrors); public delegate System.Security.Cryptography.X509Certificates.X509Certificate ServerCertificateSelectionCallback(object sender, string? hostName); public delegate System.Threading.Tasks.ValueTask<SslServerAuthenticationOptions> ServerOptionsSelectionCallback(SslStream stream, SslClientHelloInfo clientHelloInfo, object? state, System.Threading.CancellationToken cancellationToken); public readonly partial struct SslApplicationProtocol : System.IEquatable<System.Net.Security.SslApplicationProtocol> { private readonly object _dummy; private readonly int _dummyPrimitive; public static readonly System.Net.Security.SslApplicationProtocol Http11; public static readonly System.Net.Security.SslApplicationProtocol Http2; public static readonly System.Net.Security.SslApplicationProtocol Http3; public SslApplicationProtocol(byte[] protocol) { throw null; } public SslApplicationProtocol(string protocol) { throw null; } public System.ReadOnlyMemory<byte> Protocol { get { throw null; } } public bool Equals(System.Net.Security.SslApplicationProtocol other) { throw null; } public override bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] object? obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Net.Security.SslApplicationProtocol left, System.Net.Security.SslApplicationProtocol right) { throw null; } public static bool operator !=(System.Net.Security.SslApplicationProtocol left, System.Net.Security.SslApplicationProtocol right) { throw null; } public override string ToString() { throw null; } } public sealed partial class SslCertificateTrust { public static SslCertificateTrust CreateForX509Store( System.Security.Cryptography.X509Certificates.X509Store store, bool sendTrustInHandshake = false) { throw null; } [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] public static SslCertificateTrust CreateForX509Collection( System.Security.Cryptography.X509Certificates.X509Certificate2Collection trustList, bool sendTrustInHandshake = false) { throw null; } private SslCertificateTrust() { throw null; } } public sealed partial class SslStreamCertificateContext { internal SslStreamCertificateContext() { throw null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static SslStreamCertificateContext Create(System.Security.Cryptography.X509Certificates.X509Certificate2 target, System.Security.Cryptography.X509Certificates.X509Certificate2Collection? additionalCertificates, bool offline) { throw null; } public static SslStreamCertificateContext Create(System.Security.Cryptography.X509Certificates.X509Certificate2 target, System.Security.Cryptography.X509Certificates.X509Certificate2Collection? additionalCertificates, bool offline = false, SslCertificateTrust? trust = null) { throw null; } } public partial class SslClientAuthenticationOptions { public SslClientAuthenticationOptions() { } public bool AllowRenegotiation { get { throw null; } set { } } public System.Collections.Generic.List<System.Net.Security.SslApplicationProtocol>? ApplicationProtocols { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509RevocationMode CertificateRevocationCheckMode { get { throw null; } set { } } public System.Net.Security.CipherSuitesPolicy? CipherSuitesPolicy { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509CertificateCollection? ClientCertificates { get { throw null; } set { } } public System.Security.Authentication.SslProtocols EnabledSslProtocols { get { throw null; } set { } } public System.Net.Security.EncryptionPolicy EncryptionPolicy { get { throw null; } set { } } public System.Net.Security.LocalCertificateSelectionCallback? LocalCertificateSelectionCallback { get { throw null; } set { } } public System.Net.Security.RemoteCertificateValidationCallback? RemoteCertificateValidationCallback { get { throw null; } set { } } public string? TargetHost { get { throw null; } set { } } } public partial class SslServerAuthenticationOptions { public SslServerAuthenticationOptions() { } public bool AllowRenegotiation { get { throw null; } set { } } public System.Collections.Generic.List<System.Net.Security.SslApplicationProtocol>? ApplicationProtocols { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509RevocationMode CertificateRevocationCheckMode { get { throw null; } set { } } public System.Net.Security.CipherSuitesPolicy? CipherSuitesPolicy { get { throw null; } set { } } public bool ClientCertificateRequired { get { throw null; } set { } } public System.Security.Authentication.SslProtocols EnabledSslProtocols { get { throw null; } set { } } public System.Net.Security.EncryptionPolicy EncryptionPolicy { get { throw null; } set { } } public System.Net.Security.RemoteCertificateValidationCallback? RemoteCertificateValidationCallback { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509Certificate? ServerCertificate { get { throw null; } set { } } public System.Net.Security.SslStreamCertificateContext? ServerCertificateContext { get { throw null; } set { } } public System.Net.Security.ServerCertificateSelectionCallback? ServerCertificateSelectionCallback { get { throw null; } set { } } } public partial class SslStream : System.Net.Security.AuthenticatedStream { public SslStream(System.IO.Stream innerStream) : base (default(System.IO.Stream), default(bool)) { } public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen) : base (default(System.IO.Stream), default(bool)) { } public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback? userCertificateValidationCallback) : base (default(System.IO.Stream), default(bool)) { } public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback? userCertificateValidationCallback, System.Net.Security.LocalCertificateSelectionCallback? userCertificateSelectionCallback) : base (default(System.IO.Stream), default(bool)) { } public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback? userCertificateValidationCallback, System.Net.Security.LocalCertificateSelectionCallback? userCertificateSelectionCallback, System.Net.Security.EncryptionPolicy encryptionPolicy) : base (default(System.IO.Stream), default(bool)) { } public override bool CanRead { get { throw null; } } public override bool CanSeek { get { throw null; } } public override bool CanTimeout { get { throw null; } } public override bool CanWrite { get { throw null; } } public virtual bool CheckCertRevocationStatus { get { throw null; } } public virtual System.Security.Authentication.CipherAlgorithmType CipherAlgorithm { get { throw null; } } public virtual int CipherStrength { get { throw null; } } public virtual System.Security.Authentication.HashAlgorithmType HashAlgorithm { get { throw null; } } public virtual int HashStrength { get { throw null; } } public override bool IsAuthenticated { get { throw null; } } public override bool IsEncrypted { get { throw null; } } public override bool IsMutuallyAuthenticated { get { throw null; } } public override bool IsServer { get { throw null; } } public override bool IsSigned { get { throw null; } } public virtual System.Security.Authentication.ExchangeAlgorithmType KeyExchangeAlgorithm { get { throw null; } } public virtual int KeyExchangeStrength { get { throw null; } } public override long Length { get { throw null; } } public virtual System.Security.Cryptography.X509Certificates.X509Certificate? LocalCertificate { get { throw null; } } public System.Net.Security.SslApplicationProtocol NegotiatedApplicationProtocol { get { throw null; } } [System.CLSCompliantAttribute(false)] public virtual System.Net.Security.TlsCipherSuite NegotiatedCipherSuite { get { throw null; } } public override long Position { get { throw null; } set { } } public override int ReadTimeout { get { throw null; } set { } } public virtual System.Security.Cryptography.X509Certificates.X509Certificate? RemoteCertificate { get { throw null; } } public virtual System.Security.Authentication.SslProtocols SslProtocol { get { throw null; } } public string TargetHostName { get { throw null; } } public System.Net.TransportContext TransportContext { get { throw null; } } public override int WriteTimeout { get { throw null; } set { } } public void AuthenticateAsClient(System.Net.Security.SslClientAuthenticationOptions sslClientAuthenticationOptions) { } public virtual void AuthenticateAsClient(string targetHost) { } public virtual void AuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, bool checkCertificateRevocation) { } public virtual void AuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { } public System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.Security.SslClientAuthenticationOptions sslClientAuthenticationOptions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, bool checkCertificateRevocation) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { throw null; } public void AuthenticateAsServer(System.Net.Security.SslServerAuthenticationOptions sslServerAuthenticationOptions) { } public virtual void AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate) { } public virtual void AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) { } public virtual void AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { } public System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Net.Security.SslServerAuthenticationOptions sslServerAuthenticationOptions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { throw null; } public System.Threading.Tasks.Task AuthenticateAsServerAsync(ServerOptionsSelectionCallback optionsCallback, object? state, System.Threading.CancellationToken cancellationToken = default) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, bool checkCertificateRevocation, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } protected override void Dispose(bool disposing) { } public override System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } public virtual void EndAuthenticateAsClient(System.IAsyncResult asyncResult) { } public virtual void EndAuthenticateAsServer(System.IAsyncResult asyncResult) { } public override int EndRead(System.IAsyncResult asyncResult) { throw null; } public override void EndWrite(System.IAsyncResult asyncResult) { } ~SslStream() { } public override void Flush() { } public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public virtual System.Threading.Tasks.Task NegotiateClientCertificateAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override int Read(byte[] buffer, int offset, int count) { throw null; } public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask<int> ReadAsync(System.Memory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override int ReadByte() { throw null; } public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; } public override void SetLength(long value) { } public virtual System.Threading.Tasks.Task ShutdownAsync() { throw null; } public void Write(byte[] buffer) { } public override void Write(byte[] buffer, int offset, int count) { } public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } [System.CLSCompliantAttribute(false)] public enum TlsCipherSuite : ushort { TLS_NULL_WITH_NULL_NULL = (ushort)0, TLS_RSA_WITH_NULL_MD5 = (ushort)1, TLS_RSA_WITH_NULL_SHA = (ushort)2, TLS_RSA_EXPORT_WITH_RC4_40_MD5 = (ushort)3, TLS_RSA_WITH_RC4_128_MD5 = (ushort)4, TLS_RSA_WITH_RC4_128_SHA = (ushort)5, TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 = (ushort)6, TLS_RSA_WITH_IDEA_CBC_SHA = (ushort)7, TLS_RSA_EXPORT_WITH_DES40_CBC_SHA = (ushort)8, TLS_RSA_WITH_DES_CBC_SHA = (ushort)9, TLS_RSA_WITH_3DES_EDE_CBC_SHA = (ushort)10, TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA = (ushort)11, TLS_DH_DSS_WITH_DES_CBC_SHA = (ushort)12, TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA = (ushort)13, TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA = (ushort)14, TLS_DH_RSA_WITH_DES_CBC_SHA = (ushort)15, TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA = (ushort)16, TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA = (ushort)17, TLS_DHE_DSS_WITH_DES_CBC_SHA = (ushort)18, TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA = (ushort)19, TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA = (ushort)20, TLS_DHE_RSA_WITH_DES_CBC_SHA = (ushort)21, TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = (ushort)22, TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 = (ushort)23, TLS_DH_anon_WITH_RC4_128_MD5 = (ushort)24, TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA = (ushort)25, TLS_DH_anon_WITH_DES_CBC_SHA = (ushort)26, TLS_DH_anon_WITH_3DES_EDE_CBC_SHA = (ushort)27, TLS_KRB5_WITH_DES_CBC_SHA = (ushort)30, TLS_KRB5_WITH_3DES_EDE_CBC_SHA = (ushort)31, TLS_KRB5_WITH_RC4_128_SHA = (ushort)32, TLS_KRB5_WITH_IDEA_CBC_SHA = (ushort)33, TLS_KRB5_WITH_DES_CBC_MD5 = (ushort)34, TLS_KRB5_WITH_3DES_EDE_CBC_MD5 = (ushort)35, TLS_KRB5_WITH_RC4_128_MD5 = (ushort)36, TLS_KRB5_WITH_IDEA_CBC_MD5 = (ushort)37, TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA = (ushort)38, TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA = (ushort)39, TLS_KRB5_EXPORT_WITH_RC4_40_SHA = (ushort)40, TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 = (ushort)41, TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5 = (ushort)42, TLS_KRB5_EXPORT_WITH_RC4_40_MD5 = (ushort)43, TLS_PSK_WITH_NULL_SHA = (ushort)44, TLS_DHE_PSK_WITH_NULL_SHA = (ushort)45, TLS_RSA_PSK_WITH_NULL_SHA = (ushort)46, TLS_RSA_WITH_AES_128_CBC_SHA = (ushort)47, TLS_DH_DSS_WITH_AES_128_CBC_SHA = (ushort)48, TLS_DH_RSA_WITH_AES_128_CBC_SHA = (ushort)49, TLS_DHE_DSS_WITH_AES_128_CBC_SHA = (ushort)50, TLS_DHE_RSA_WITH_AES_128_CBC_SHA = (ushort)51, TLS_DH_anon_WITH_AES_128_CBC_SHA = (ushort)52, TLS_RSA_WITH_AES_256_CBC_SHA = (ushort)53, TLS_DH_DSS_WITH_AES_256_CBC_SHA = (ushort)54, TLS_DH_RSA_WITH_AES_256_CBC_SHA = (ushort)55, TLS_DHE_DSS_WITH_AES_256_CBC_SHA = (ushort)56, TLS_DHE_RSA_WITH_AES_256_CBC_SHA = (ushort)57, TLS_DH_anon_WITH_AES_256_CBC_SHA = (ushort)58, TLS_RSA_WITH_NULL_SHA256 = (ushort)59, TLS_RSA_WITH_AES_128_CBC_SHA256 = (ushort)60, TLS_RSA_WITH_AES_256_CBC_SHA256 = (ushort)61, TLS_DH_DSS_WITH_AES_128_CBC_SHA256 = (ushort)62, TLS_DH_RSA_WITH_AES_128_CBC_SHA256 = (ushort)63, TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 = (ushort)64, TLS_RSA_WITH_CAMELLIA_128_CBC_SHA = (ushort)65, TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA = (ushort)66, TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA = (ushort)67, TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA = (ushort)68, TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA = (ushort)69, TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA = (ushort)70, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = (ushort)103, TLS_DH_DSS_WITH_AES_256_CBC_SHA256 = (ushort)104, TLS_DH_RSA_WITH_AES_256_CBC_SHA256 = (ushort)105, TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 = (ushort)106, TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = (ushort)107, TLS_DH_anon_WITH_AES_128_CBC_SHA256 = (ushort)108, TLS_DH_anon_WITH_AES_256_CBC_SHA256 = (ushort)109, TLS_RSA_WITH_CAMELLIA_256_CBC_SHA = (ushort)132, TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA = (ushort)133, TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA = (ushort)134, TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA = (ushort)135, TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA = (ushort)136, TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA = (ushort)137, TLS_PSK_WITH_RC4_128_SHA = (ushort)138, TLS_PSK_WITH_3DES_EDE_CBC_SHA = (ushort)139, TLS_PSK_WITH_AES_128_CBC_SHA = (ushort)140, TLS_PSK_WITH_AES_256_CBC_SHA = (ushort)141, TLS_DHE_PSK_WITH_RC4_128_SHA = (ushort)142, TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA = (ushort)143, TLS_DHE_PSK_WITH_AES_128_CBC_SHA = (ushort)144, TLS_DHE_PSK_WITH_AES_256_CBC_SHA = (ushort)145, TLS_RSA_PSK_WITH_RC4_128_SHA = (ushort)146, TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA = (ushort)147, TLS_RSA_PSK_WITH_AES_128_CBC_SHA = (ushort)148, TLS_RSA_PSK_WITH_AES_256_CBC_SHA = (ushort)149, TLS_RSA_WITH_SEED_CBC_SHA = (ushort)150, TLS_DH_DSS_WITH_SEED_CBC_SHA = (ushort)151, TLS_DH_RSA_WITH_SEED_CBC_SHA = (ushort)152, TLS_DHE_DSS_WITH_SEED_CBC_SHA = (ushort)153, TLS_DHE_RSA_WITH_SEED_CBC_SHA = (ushort)154, TLS_DH_anon_WITH_SEED_CBC_SHA = (ushort)155, TLS_RSA_WITH_AES_128_GCM_SHA256 = (ushort)156, TLS_RSA_WITH_AES_256_GCM_SHA384 = (ushort)157, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = (ushort)158, TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = (ushort)159, TLS_DH_RSA_WITH_AES_128_GCM_SHA256 = (ushort)160, TLS_DH_RSA_WITH_AES_256_GCM_SHA384 = (ushort)161, TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 = (ushort)162, TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 = (ushort)163, TLS_DH_DSS_WITH_AES_128_GCM_SHA256 = (ushort)164, TLS_DH_DSS_WITH_AES_256_GCM_SHA384 = (ushort)165, TLS_DH_anon_WITH_AES_128_GCM_SHA256 = (ushort)166, TLS_DH_anon_WITH_AES_256_GCM_SHA384 = (ushort)167, TLS_PSK_WITH_AES_128_GCM_SHA256 = (ushort)168, TLS_PSK_WITH_AES_256_GCM_SHA384 = (ushort)169, TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 = (ushort)170, TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 = (ushort)171, TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 = (ushort)172, TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 = (ushort)173, TLS_PSK_WITH_AES_128_CBC_SHA256 = (ushort)174, TLS_PSK_WITH_AES_256_CBC_SHA384 = (ushort)175, TLS_PSK_WITH_NULL_SHA256 = (ushort)176, TLS_PSK_WITH_NULL_SHA384 = (ushort)177, TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 = (ushort)178, TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 = (ushort)179, TLS_DHE_PSK_WITH_NULL_SHA256 = (ushort)180, TLS_DHE_PSK_WITH_NULL_SHA384 = (ushort)181, TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 = (ushort)182, TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 = (ushort)183, TLS_RSA_PSK_WITH_NULL_SHA256 = (ushort)184, TLS_RSA_PSK_WITH_NULL_SHA384 = (ushort)185, TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)186, TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)187, TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)188, TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)189, TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)190, TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)191, TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 = (ushort)192, TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 = (ushort)193, TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 = (ushort)194, TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 = (ushort)195, TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 = (ushort)196, TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256 = (ushort)197, TLS_AES_128_GCM_SHA256 = (ushort)4865, TLS_AES_256_GCM_SHA384 = (ushort)4866, TLS_CHACHA20_POLY1305_SHA256 = (ushort)4867, TLS_AES_128_CCM_SHA256 = (ushort)4868, TLS_AES_128_CCM_8_SHA256 = (ushort)4869, TLS_ECDH_ECDSA_WITH_NULL_SHA = (ushort)49153, TLS_ECDH_ECDSA_WITH_RC4_128_SHA = (ushort)49154, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA = (ushort)49155, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA = (ushort)49156, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA = (ushort)49157, TLS_ECDHE_ECDSA_WITH_NULL_SHA = (ushort)49158, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA = (ushort)49159, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA = (ushort)49160, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = (ushort)49161, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = (ushort)49162, TLS_ECDH_RSA_WITH_NULL_SHA = (ushort)49163, TLS_ECDH_RSA_WITH_RC4_128_SHA = (ushort)49164, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA = (ushort)49165, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA = (ushort)49166, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA = (ushort)49167, TLS_ECDHE_RSA_WITH_NULL_SHA = (ushort)49168, TLS_ECDHE_RSA_WITH_RC4_128_SHA = (ushort)49169, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA = (ushort)49170, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = (ushort)49171, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = (ushort)49172, TLS_ECDH_anon_WITH_NULL_SHA = (ushort)49173, TLS_ECDH_anon_WITH_RC4_128_SHA = (ushort)49174, TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA = (ushort)49175, TLS_ECDH_anon_WITH_AES_128_CBC_SHA = (ushort)49176, TLS_ECDH_anon_WITH_AES_256_CBC_SHA = (ushort)49177, TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA = (ushort)49178, TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA = (ushort)49179, TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA = (ushort)49180, TLS_SRP_SHA_WITH_AES_128_CBC_SHA = (ushort)49181, TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA = (ushort)49182, TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA = (ushort)49183, TLS_SRP_SHA_WITH_AES_256_CBC_SHA = (ushort)49184, TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA = (ushort)49185, TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA = (ushort)49186, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = (ushort)49187, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = (ushort)49188, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 = (ushort)49189, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 = (ushort)49190, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = (ushort)49191, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = (ushort)49192, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 = (ushort)49193, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 = (ushort)49194, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = (ushort)49195, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = (ushort)49196, TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 = (ushort)49197, TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 = (ushort)49198, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = (ushort)49199, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = (ushort)49200, TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 = (ushort)49201, TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 = (ushort)49202, TLS_ECDHE_PSK_WITH_RC4_128_SHA = (ushort)49203, TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA = (ushort)49204, TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA = (ushort)49205, TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA = (ushort)49206, TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 = (ushort)49207, TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 = (ushort)49208, TLS_ECDHE_PSK_WITH_NULL_SHA = (ushort)49209, TLS_ECDHE_PSK_WITH_NULL_SHA256 = (ushort)49210, TLS_ECDHE_PSK_WITH_NULL_SHA384 = (ushort)49211, TLS_RSA_WITH_ARIA_128_CBC_SHA256 = (ushort)49212, TLS_RSA_WITH_ARIA_256_CBC_SHA384 = (ushort)49213, TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256 = (ushort)49214, TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384 = (ushort)49215, TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256 = (ushort)49216, TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384 = (ushort)49217, TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256 = (ushort)49218, TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384 = (ushort)49219, TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 = (ushort)49220, TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 = (ushort)49221, TLS_DH_anon_WITH_ARIA_128_CBC_SHA256 = (ushort)49222, TLS_DH_anon_WITH_ARIA_256_CBC_SHA384 = (ushort)49223, TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 = (ushort)49224, TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 = (ushort)49225, TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 = (ushort)49226, TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 = (ushort)49227, TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 = (ushort)49228, TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 = (ushort)49229, TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 = (ushort)49230, TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 = (ushort)49231, TLS_RSA_WITH_ARIA_128_GCM_SHA256 = (ushort)49232, TLS_RSA_WITH_ARIA_256_GCM_SHA384 = (ushort)49233, TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 = (ushort)49234, TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 = (ushort)49235, TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256 = (ushort)49236, TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384 = (ushort)49237, TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256 = (ushort)49238, TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384 = (ushort)49239, TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256 = (ushort)49240, TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384 = (ushort)49241, TLS_DH_anon_WITH_ARIA_128_GCM_SHA256 = (ushort)49242, TLS_DH_anon_WITH_ARIA_256_GCM_SHA384 = (ushort)49243, TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 = (ushort)49244, TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 = (ushort)49245, TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 = (ushort)49246, TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 = (ushort)49247, TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 = (ushort)49248, TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 = (ushort)49249, TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 = (ushort)49250, TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 = (ushort)49251, TLS_PSK_WITH_ARIA_128_CBC_SHA256 = (ushort)49252, TLS_PSK_WITH_ARIA_256_CBC_SHA384 = (ushort)49253, TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 = (ushort)49254, TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 = (ushort)49255, TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 = (ushort)49256, TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 = (ushort)49257, TLS_PSK_WITH_ARIA_128_GCM_SHA256 = (ushort)49258, TLS_PSK_WITH_ARIA_256_GCM_SHA384 = (ushort)49259, TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 = (ushort)49260, TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 = (ushort)49261, TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 = (ushort)49262, TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 = (ushort)49263, TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 = (ushort)49264, TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 = (ushort)49265, TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)49266, TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 = (ushort)49267, TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)49268, TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 = (ushort)49269, TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)49270, TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 = (ushort)49271, TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)49272, TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 = (ushort)49273, TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49274, TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49275, TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49276, TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49277, TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49278, TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49279, TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49280, TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49281, TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49282, TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49283, TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49284, TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49285, TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49286, TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49287, TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49288, TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49289, TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49290, TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49291, TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49292, TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49293, TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49294, TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49295, TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49296, TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49297, TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49298, TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49299, TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)49300, TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 = (ushort)49301, TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)49302, TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 = (ushort)49303, TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)49304, TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 = (ushort)49305, TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)49306, TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 = (ushort)49307, TLS_RSA_WITH_AES_128_CCM = (ushort)49308, TLS_RSA_WITH_AES_256_CCM = (ushort)49309, TLS_DHE_RSA_WITH_AES_128_CCM = (ushort)49310, TLS_DHE_RSA_WITH_AES_256_CCM = (ushort)49311, TLS_RSA_WITH_AES_128_CCM_8 = (ushort)49312, TLS_RSA_WITH_AES_256_CCM_8 = (ushort)49313, TLS_DHE_RSA_WITH_AES_128_CCM_8 = (ushort)49314, TLS_DHE_RSA_WITH_AES_256_CCM_8 = (ushort)49315, TLS_PSK_WITH_AES_128_CCM = (ushort)49316, TLS_PSK_WITH_AES_256_CCM = (ushort)49317, TLS_DHE_PSK_WITH_AES_128_CCM = (ushort)49318, TLS_DHE_PSK_WITH_AES_256_CCM = (ushort)49319, TLS_PSK_WITH_AES_128_CCM_8 = (ushort)49320, TLS_PSK_WITH_AES_256_CCM_8 = (ushort)49321, TLS_PSK_DHE_WITH_AES_128_CCM_8 = (ushort)49322, TLS_PSK_DHE_WITH_AES_256_CCM_8 = (ushort)49323, TLS_ECDHE_ECDSA_WITH_AES_128_CCM = (ushort)49324, TLS_ECDHE_ECDSA_WITH_AES_256_CCM = (ushort)49325, TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 = (ushort)49326, TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 = (ushort)49327, TLS_ECCPWD_WITH_AES_128_GCM_SHA256 = (ushort)49328, TLS_ECCPWD_WITH_AES_256_GCM_SHA384 = (ushort)49329, TLS_ECCPWD_WITH_AES_128_CCM_SHA256 = (ushort)49330, TLS_ECCPWD_WITH_AES_256_CCM_SHA384 = (ushort)49331, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = (ushort)52392, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = (ushort)52393, TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = (ushort)52394, TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 = (ushort)52395, TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 = (ushort)52396, TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 = (ushort)52397, TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 = (ushort)52398, TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256 = (ushort)53249, TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384 = (ushort)53250, TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256 = (ushort)53251, TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256 = (ushort)53253, } } namespace System.Security.Authentication { public partial class AuthenticationException : System.SystemException { public AuthenticationException() { } protected AuthenticationException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public AuthenticationException(string? message) { } public AuthenticationException(string? message, System.Exception? innerException) { } } public partial class InvalidCredentialException : System.Security.Authentication.AuthenticationException { public InvalidCredentialException() { } protected InvalidCredentialException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public InvalidCredentialException(string? message) { } public InvalidCredentialException(string? message, System.Exception? innerException) { } } } namespace System.Security.Authentication.ExtendedProtection { public partial class ExtendedProtectionPolicy : System.Runtime.Serialization.ISerializable { protected ExtendedProtectionPolicy(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement) { } public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement, System.Security.Authentication.ExtendedProtection.ChannelBinding customChannelBinding) { } public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement, System.Security.Authentication.ExtendedProtection.ProtectionScenario protectionScenario, System.Collections.ICollection? customServiceNames) { } public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement, System.Security.Authentication.ExtendedProtection.ProtectionScenario protectionScenario, System.Security.Authentication.ExtendedProtection.ServiceNameCollection? customServiceNames) { } public System.Security.Authentication.ExtendedProtection.ChannelBinding? CustomChannelBinding { get { throw null; } } public System.Security.Authentication.ExtendedProtection.ServiceNameCollection? CustomServiceNames { get { throw null; } } public static bool OSSupportsExtendedProtection { get { throw null; } } public System.Security.Authentication.ExtendedProtection.PolicyEnforcement PolicyEnforcement { get { throw null; } } public System.Security.Authentication.ExtendedProtection.ProtectionScenario ProtectionScenario { get { throw null; } } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo? info, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } } public enum PolicyEnforcement { Never = 0, WhenSupported = 1, Always = 2, } public enum ProtectionScenario { TransportSelected = 0, TrustedProxy = 1, } public partial class ServiceNameCollection : System.Collections.ReadOnlyCollectionBase { public ServiceNameCollection(System.Collections.ICollection items) { } public bool Contains(string? searchServiceName) { throw null; } public System.Security.Authentication.ExtendedProtection.ServiceNameCollection Merge(System.Collections.IEnumerable serviceNames) { throw null; } public System.Security.Authentication.ExtendedProtection.ServiceNameCollection Merge(string serviceName) { throw null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Net.Security { public abstract partial class AuthenticatedStream : System.IO.Stream { protected AuthenticatedStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen) { } protected System.IO.Stream InnerStream { get { throw null; } } public abstract bool IsAuthenticated { get; } public abstract bool IsEncrypted { get; } public abstract bool IsMutuallyAuthenticated { get; } public abstract bool IsServer { get; } public abstract bool IsSigned { get; } public bool LeaveInnerStreamOpen { get { throw null; } } protected override void Dispose(bool disposing) { } public override System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } } public sealed partial class CipherSuitesPolicy { [System.CLSCompliantAttribute(false)] public CipherSuitesPolicy(System.Collections.Generic.IEnumerable<System.Net.Security.TlsCipherSuite> allowedCipherSuites) { } [System.CLSCompliantAttribute(false)] public System.Collections.Generic.IEnumerable<System.Net.Security.TlsCipherSuite> AllowedCipherSuites { get { throw null; } } } public enum EncryptionPolicy { RequireEncryption = 0, [System.ObsoleteAttribute("EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code.", DiagnosticId = "SYSLIB0040", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] AllowNoEncryption = 1, [System.ObsoleteAttribute("EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code.", DiagnosticId = "SYSLIB0040", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] NoEncryption = 2, } public delegate System.Security.Cryptography.X509Certificates.X509Certificate LocalCertificateSelectionCallback(object sender, string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection localCertificates, System.Security.Cryptography.X509Certificates.X509Certificate? remoteCertificate, string[] acceptableIssuers); [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] public partial class NegotiateStream : System.Net.Security.AuthenticatedStream { public NegotiateStream(System.IO.Stream innerStream) : base (default(System.IO.Stream), default(bool)) { } public NegotiateStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen) : base (default(System.IO.Stream), default(bool)) { } public override bool CanRead { get { throw null; } } public override bool CanSeek { get { throw null; } } public override bool CanTimeout { get { throw null; } } public override bool CanWrite { get { throw null; } } public virtual System.Security.Principal.TokenImpersonationLevel ImpersonationLevel { get { throw null; } } public override bool IsAuthenticated { get { throw null; } } public override bool IsEncrypted { get { throw null; } } public override bool IsMutuallyAuthenticated { get { throw null; } } public override bool IsServer { get { throw null; } } public override bool IsSigned { get { throw null; } } public override long Length { get { throw null; } } public override long Position { get { throw null; } set { } } public override int ReadTimeout { get { throw null; } set { } } public virtual System.Security.Principal.IIdentity RemoteIdentity { get { throw null; } } public override int WriteTimeout { get { throw null; } set { } } public virtual void AuthenticateAsClient() { } public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName) { } public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { } public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, string targetName) { } public virtual void AuthenticateAsClient(System.Net.NetworkCredential credential, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync() { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.NetworkCredential credential, string targetName) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.NetworkCredential credential, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel) { throw null; } public virtual void AuthenticateAsServer() { } public virtual void AuthenticateAsServer(System.Net.NetworkCredential credential, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { } public virtual void AuthenticateAsServer(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { } public virtual void AuthenticateAsServer(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy) { } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync() { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Net.NetworkCredential credential, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsClient(System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding? binding, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, string targetName, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsClient(System.Net.NetworkCredential credential, string targetName, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsServer(System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Net.NetworkCredential credential, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy, System.Net.Security.ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel requiredImpersonationLevel, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy? policy, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } protected override void Dispose(bool disposing) { } public override System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } public virtual void EndAuthenticateAsClient(System.IAsyncResult asyncResult) { } public virtual void EndAuthenticateAsServer(System.IAsyncResult asyncResult) { } public override int EndRead(System.IAsyncResult asyncResult) { throw null; } public override void EndWrite(System.IAsyncResult asyncResult) { } public override void Flush() { } public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public override int Read(byte[] buffer, int offset, int count) { throw null; } public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask<int> ReadAsync(System.Memory<byte> buffer, System.Threading.CancellationToken cancellationToken = default) { throw null; } public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; } public override void SetLength(long value) { } public override void Write(byte[] buffer, int offset, int count) { } public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken = default) { throw null; } } public enum ProtectionLevel { None = 0, Sign = 1, EncryptAndSign = 2, } public readonly struct SslClientHelloInfo { public string ServerName { get; } public System.Security.Authentication.SslProtocols SslProtocols { get; } internal SslClientHelloInfo(string serverName, System.Security.Authentication.SslProtocols sslProtocol) { throw null; } } public delegate bool RemoteCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate? certificate, System.Security.Cryptography.X509Certificates.X509Chain? chain, System.Net.Security.SslPolicyErrors sslPolicyErrors); public delegate System.Security.Cryptography.X509Certificates.X509Certificate ServerCertificateSelectionCallback(object sender, string? hostName); public delegate System.Threading.Tasks.ValueTask<SslServerAuthenticationOptions> ServerOptionsSelectionCallback(SslStream stream, SslClientHelloInfo clientHelloInfo, object? state, System.Threading.CancellationToken cancellationToken); public readonly partial struct SslApplicationProtocol : System.IEquatable<System.Net.Security.SslApplicationProtocol> { private readonly object _dummy; private readonly int _dummyPrimitive; public static readonly System.Net.Security.SslApplicationProtocol Http11; public static readonly System.Net.Security.SslApplicationProtocol Http2; public static readonly System.Net.Security.SslApplicationProtocol Http3; public SslApplicationProtocol(byte[] protocol) { throw null; } public SslApplicationProtocol(string protocol) { throw null; } public System.ReadOnlyMemory<byte> Protocol { get { throw null; } } public bool Equals(System.Net.Security.SslApplicationProtocol other) { throw null; } public override bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] object? obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Net.Security.SslApplicationProtocol left, System.Net.Security.SslApplicationProtocol right) { throw null; } public static bool operator !=(System.Net.Security.SslApplicationProtocol left, System.Net.Security.SslApplicationProtocol right) { throw null; } public override string ToString() { throw null; } } public sealed partial class SslCertificateTrust { public static SslCertificateTrust CreateForX509Store( System.Security.Cryptography.X509Certificates.X509Store store, bool sendTrustInHandshake = false) { throw null; } [System.Runtime.Versioning.UnsupportedOSPlatform("windows")] public static SslCertificateTrust CreateForX509Collection( System.Security.Cryptography.X509Certificates.X509Certificate2Collection trustList, bool sendTrustInHandshake = false) { throw null; } private SslCertificateTrust() { throw null; } } public sealed partial class SslStreamCertificateContext { internal SslStreamCertificateContext() { throw null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static SslStreamCertificateContext Create(System.Security.Cryptography.X509Certificates.X509Certificate2 target, System.Security.Cryptography.X509Certificates.X509Certificate2Collection? additionalCertificates, bool offline) { throw null; } public static SslStreamCertificateContext Create(System.Security.Cryptography.X509Certificates.X509Certificate2 target, System.Security.Cryptography.X509Certificates.X509Certificate2Collection? additionalCertificates, bool offline = false, SslCertificateTrust? trust = null) { throw null; } } public partial class SslClientAuthenticationOptions { public SslClientAuthenticationOptions() { } public bool AllowRenegotiation { get { throw null; } set { } } public System.Collections.Generic.List<System.Net.Security.SslApplicationProtocol>? ApplicationProtocols { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509RevocationMode CertificateRevocationCheckMode { get { throw null; } set { } } public System.Net.Security.CipherSuitesPolicy? CipherSuitesPolicy { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509CertificateCollection? ClientCertificates { get { throw null; } set { } } public System.Security.Authentication.SslProtocols EnabledSslProtocols { get { throw null; } set { } } public System.Net.Security.EncryptionPolicy EncryptionPolicy { get { throw null; } set { } } public System.Net.Security.LocalCertificateSelectionCallback? LocalCertificateSelectionCallback { get { throw null; } set { } } public System.Net.Security.RemoteCertificateValidationCallback? RemoteCertificateValidationCallback { get { throw null; } set { } } public string? TargetHost { get { throw null; } set { } } } public partial class SslServerAuthenticationOptions { public SslServerAuthenticationOptions() { } public bool AllowRenegotiation { get { throw null; } set { } } public System.Collections.Generic.List<System.Net.Security.SslApplicationProtocol>? ApplicationProtocols { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509RevocationMode CertificateRevocationCheckMode { get { throw null; } set { } } public System.Net.Security.CipherSuitesPolicy? CipherSuitesPolicy { get { throw null; } set { } } public bool ClientCertificateRequired { get { throw null; } set { } } public System.Security.Authentication.SslProtocols EnabledSslProtocols { get { throw null; } set { } } public System.Net.Security.EncryptionPolicy EncryptionPolicy { get { throw null; } set { } } public System.Net.Security.RemoteCertificateValidationCallback? RemoteCertificateValidationCallback { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509Certificate? ServerCertificate { get { throw null; } set { } } public System.Net.Security.SslStreamCertificateContext? ServerCertificateContext { get { throw null; } set { } } public System.Net.Security.ServerCertificateSelectionCallback? ServerCertificateSelectionCallback { get { throw null; } set { } } } public partial class SslStream : System.Net.Security.AuthenticatedStream { public SslStream(System.IO.Stream innerStream) : base (default(System.IO.Stream), default(bool)) { } public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen) : base (default(System.IO.Stream), default(bool)) { } public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback? userCertificateValidationCallback) : base (default(System.IO.Stream), default(bool)) { } public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback? userCertificateValidationCallback, System.Net.Security.LocalCertificateSelectionCallback? userCertificateSelectionCallback) : base (default(System.IO.Stream), default(bool)) { } public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback? userCertificateValidationCallback, System.Net.Security.LocalCertificateSelectionCallback? userCertificateSelectionCallback, System.Net.Security.EncryptionPolicy encryptionPolicy) : base (default(System.IO.Stream), default(bool)) { } public override bool CanRead { get { throw null; } } public override bool CanSeek { get { throw null; } } public override bool CanTimeout { get { throw null; } } public override bool CanWrite { get { throw null; } } public virtual bool CheckCertRevocationStatus { get { throw null; } } public virtual System.Security.Authentication.CipherAlgorithmType CipherAlgorithm { get { throw null; } } public virtual int CipherStrength { get { throw null; } } public virtual System.Security.Authentication.HashAlgorithmType HashAlgorithm { get { throw null; } } public virtual int HashStrength { get { throw null; } } public override bool IsAuthenticated { get { throw null; } } public override bool IsEncrypted { get { throw null; } } public override bool IsMutuallyAuthenticated { get { throw null; } } public override bool IsServer { get { throw null; } } public override bool IsSigned { get { throw null; } } public virtual System.Security.Authentication.ExchangeAlgorithmType KeyExchangeAlgorithm { get { throw null; } } public virtual int KeyExchangeStrength { get { throw null; } } public override long Length { get { throw null; } } public virtual System.Security.Cryptography.X509Certificates.X509Certificate? LocalCertificate { get { throw null; } } public System.Net.Security.SslApplicationProtocol NegotiatedApplicationProtocol { get { throw null; } } [System.CLSCompliantAttribute(false)] public virtual System.Net.Security.TlsCipherSuite NegotiatedCipherSuite { get { throw null; } } public override long Position { get { throw null; } set { } } public override int ReadTimeout { get { throw null; } set { } } public virtual System.Security.Cryptography.X509Certificates.X509Certificate? RemoteCertificate { get { throw null; } } public virtual System.Security.Authentication.SslProtocols SslProtocol { get { throw null; } } public string TargetHostName { get { throw null; } } public System.Net.TransportContext TransportContext { get { throw null; } } public override int WriteTimeout { get { throw null; } set { } } public void AuthenticateAsClient(System.Net.Security.SslClientAuthenticationOptions sslClientAuthenticationOptions) { } public virtual void AuthenticateAsClient(string targetHost) { } public virtual void AuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, bool checkCertificateRevocation) { } public virtual void AuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { } public System.Threading.Tasks.Task AuthenticateAsClientAsync(System.Net.Security.SslClientAuthenticationOptions sslClientAuthenticationOptions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, bool checkCertificateRevocation) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsClientAsync(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { throw null; } public void AuthenticateAsServer(System.Net.Security.SslServerAuthenticationOptions sslServerAuthenticationOptions) { } public virtual void AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate) { } public virtual void AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) { } public virtual void AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { } public System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Net.Security.SslServerAuthenticationOptions sslServerAuthenticationOptions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) { throw null; } public virtual System.Threading.Tasks.Task AuthenticateAsServerAsync(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { throw null; } public System.Threading.Tasks.Task AuthenticateAsServerAsync(ServerOptionsSelectionCallback optionsCallback, object? state, System.Threading.CancellationToken cancellationToken = default) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, bool checkCertificateRevocation, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsClient(string targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection? clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public virtual System.IAsyncResult BeginAuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate, bool clientCertificateRequired, System.Security.Authentication.SslProtocols enabledSslProtocols, bool checkCertificateRevocation, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback? asyncCallback, object? asyncState) { throw null; } protected override void Dispose(bool disposing) { } public override System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } public virtual void EndAuthenticateAsClient(System.IAsyncResult asyncResult) { } public virtual void EndAuthenticateAsServer(System.IAsyncResult asyncResult) { } public override int EndRead(System.IAsyncResult asyncResult) { throw null; } public override void EndWrite(System.IAsyncResult asyncResult) { } ~SslStream() { } public override void Flush() { } public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public virtual System.Threading.Tasks.Task NegotiateClientCertificateAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override int Read(byte[] buffer, int offset, int count) { throw null; } public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask<int> ReadAsync(System.Memory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override int ReadByte() { throw null; } public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; } public override void SetLength(long value) { } public virtual System.Threading.Tasks.Task ShutdownAsync() { throw null; } public void Write(byte[] buffer) { } public override void Write(byte[] buffer, int offset, int count) { } public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } [System.CLSCompliantAttribute(false)] public enum TlsCipherSuite : ushort { TLS_NULL_WITH_NULL_NULL = (ushort)0, TLS_RSA_WITH_NULL_MD5 = (ushort)1, TLS_RSA_WITH_NULL_SHA = (ushort)2, TLS_RSA_EXPORT_WITH_RC4_40_MD5 = (ushort)3, TLS_RSA_WITH_RC4_128_MD5 = (ushort)4, TLS_RSA_WITH_RC4_128_SHA = (ushort)5, TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 = (ushort)6, TLS_RSA_WITH_IDEA_CBC_SHA = (ushort)7, TLS_RSA_EXPORT_WITH_DES40_CBC_SHA = (ushort)8, TLS_RSA_WITH_DES_CBC_SHA = (ushort)9, TLS_RSA_WITH_3DES_EDE_CBC_SHA = (ushort)10, TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA = (ushort)11, TLS_DH_DSS_WITH_DES_CBC_SHA = (ushort)12, TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA = (ushort)13, TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA = (ushort)14, TLS_DH_RSA_WITH_DES_CBC_SHA = (ushort)15, TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA = (ushort)16, TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA = (ushort)17, TLS_DHE_DSS_WITH_DES_CBC_SHA = (ushort)18, TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA = (ushort)19, TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA = (ushort)20, TLS_DHE_RSA_WITH_DES_CBC_SHA = (ushort)21, TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = (ushort)22, TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 = (ushort)23, TLS_DH_anon_WITH_RC4_128_MD5 = (ushort)24, TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA = (ushort)25, TLS_DH_anon_WITH_DES_CBC_SHA = (ushort)26, TLS_DH_anon_WITH_3DES_EDE_CBC_SHA = (ushort)27, TLS_KRB5_WITH_DES_CBC_SHA = (ushort)30, TLS_KRB5_WITH_3DES_EDE_CBC_SHA = (ushort)31, TLS_KRB5_WITH_RC4_128_SHA = (ushort)32, TLS_KRB5_WITH_IDEA_CBC_SHA = (ushort)33, TLS_KRB5_WITH_DES_CBC_MD5 = (ushort)34, TLS_KRB5_WITH_3DES_EDE_CBC_MD5 = (ushort)35, TLS_KRB5_WITH_RC4_128_MD5 = (ushort)36, TLS_KRB5_WITH_IDEA_CBC_MD5 = (ushort)37, TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA = (ushort)38, TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA = (ushort)39, TLS_KRB5_EXPORT_WITH_RC4_40_SHA = (ushort)40, TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 = (ushort)41, TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5 = (ushort)42, TLS_KRB5_EXPORT_WITH_RC4_40_MD5 = (ushort)43, TLS_PSK_WITH_NULL_SHA = (ushort)44, TLS_DHE_PSK_WITH_NULL_SHA = (ushort)45, TLS_RSA_PSK_WITH_NULL_SHA = (ushort)46, TLS_RSA_WITH_AES_128_CBC_SHA = (ushort)47, TLS_DH_DSS_WITH_AES_128_CBC_SHA = (ushort)48, TLS_DH_RSA_WITH_AES_128_CBC_SHA = (ushort)49, TLS_DHE_DSS_WITH_AES_128_CBC_SHA = (ushort)50, TLS_DHE_RSA_WITH_AES_128_CBC_SHA = (ushort)51, TLS_DH_anon_WITH_AES_128_CBC_SHA = (ushort)52, TLS_RSA_WITH_AES_256_CBC_SHA = (ushort)53, TLS_DH_DSS_WITH_AES_256_CBC_SHA = (ushort)54, TLS_DH_RSA_WITH_AES_256_CBC_SHA = (ushort)55, TLS_DHE_DSS_WITH_AES_256_CBC_SHA = (ushort)56, TLS_DHE_RSA_WITH_AES_256_CBC_SHA = (ushort)57, TLS_DH_anon_WITH_AES_256_CBC_SHA = (ushort)58, TLS_RSA_WITH_NULL_SHA256 = (ushort)59, TLS_RSA_WITH_AES_128_CBC_SHA256 = (ushort)60, TLS_RSA_WITH_AES_256_CBC_SHA256 = (ushort)61, TLS_DH_DSS_WITH_AES_128_CBC_SHA256 = (ushort)62, TLS_DH_RSA_WITH_AES_128_CBC_SHA256 = (ushort)63, TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 = (ushort)64, TLS_RSA_WITH_CAMELLIA_128_CBC_SHA = (ushort)65, TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA = (ushort)66, TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA = (ushort)67, TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA = (ushort)68, TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA = (ushort)69, TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA = (ushort)70, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = (ushort)103, TLS_DH_DSS_WITH_AES_256_CBC_SHA256 = (ushort)104, TLS_DH_RSA_WITH_AES_256_CBC_SHA256 = (ushort)105, TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 = (ushort)106, TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = (ushort)107, TLS_DH_anon_WITH_AES_128_CBC_SHA256 = (ushort)108, TLS_DH_anon_WITH_AES_256_CBC_SHA256 = (ushort)109, TLS_RSA_WITH_CAMELLIA_256_CBC_SHA = (ushort)132, TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA = (ushort)133, TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA = (ushort)134, TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA = (ushort)135, TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA = (ushort)136, TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA = (ushort)137, TLS_PSK_WITH_RC4_128_SHA = (ushort)138, TLS_PSK_WITH_3DES_EDE_CBC_SHA = (ushort)139, TLS_PSK_WITH_AES_128_CBC_SHA = (ushort)140, TLS_PSK_WITH_AES_256_CBC_SHA = (ushort)141, TLS_DHE_PSK_WITH_RC4_128_SHA = (ushort)142, TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA = (ushort)143, TLS_DHE_PSK_WITH_AES_128_CBC_SHA = (ushort)144, TLS_DHE_PSK_WITH_AES_256_CBC_SHA = (ushort)145, TLS_RSA_PSK_WITH_RC4_128_SHA = (ushort)146, TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA = (ushort)147, TLS_RSA_PSK_WITH_AES_128_CBC_SHA = (ushort)148, TLS_RSA_PSK_WITH_AES_256_CBC_SHA = (ushort)149, TLS_RSA_WITH_SEED_CBC_SHA = (ushort)150, TLS_DH_DSS_WITH_SEED_CBC_SHA = (ushort)151, TLS_DH_RSA_WITH_SEED_CBC_SHA = (ushort)152, TLS_DHE_DSS_WITH_SEED_CBC_SHA = (ushort)153, TLS_DHE_RSA_WITH_SEED_CBC_SHA = (ushort)154, TLS_DH_anon_WITH_SEED_CBC_SHA = (ushort)155, TLS_RSA_WITH_AES_128_GCM_SHA256 = (ushort)156, TLS_RSA_WITH_AES_256_GCM_SHA384 = (ushort)157, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = (ushort)158, TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = (ushort)159, TLS_DH_RSA_WITH_AES_128_GCM_SHA256 = (ushort)160, TLS_DH_RSA_WITH_AES_256_GCM_SHA384 = (ushort)161, TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 = (ushort)162, TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 = (ushort)163, TLS_DH_DSS_WITH_AES_128_GCM_SHA256 = (ushort)164, TLS_DH_DSS_WITH_AES_256_GCM_SHA384 = (ushort)165, TLS_DH_anon_WITH_AES_128_GCM_SHA256 = (ushort)166, TLS_DH_anon_WITH_AES_256_GCM_SHA384 = (ushort)167, TLS_PSK_WITH_AES_128_GCM_SHA256 = (ushort)168, TLS_PSK_WITH_AES_256_GCM_SHA384 = (ushort)169, TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 = (ushort)170, TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 = (ushort)171, TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 = (ushort)172, TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 = (ushort)173, TLS_PSK_WITH_AES_128_CBC_SHA256 = (ushort)174, TLS_PSK_WITH_AES_256_CBC_SHA384 = (ushort)175, TLS_PSK_WITH_NULL_SHA256 = (ushort)176, TLS_PSK_WITH_NULL_SHA384 = (ushort)177, TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 = (ushort)178, TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 = (ushort)179, TLS_DHE_PSK_WITH_NULL_SHA256 = (ushort)180, TLS_DHE_PSK_WITH_NULL_SHA384 = (ushort)181, TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 = (ushort)182, TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 = (ushort)183, TLS_RSA_PSK_WITH_NULL_SHA256 = (ushort)184, TLS_RSA_PSK_WITH_NULL_SHA384 = (ushort)185, TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)186, TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)187, TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)188, TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)189, TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)190, TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)191, TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 = (ushort)192, TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 = (ushort)193, TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 = (ushort)194, TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 = (ushort)195, TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 = (ushort)196, TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256 = (ushort)197, TLS_AES_128_GCM_SHA256 = (ushort)4865, TLS_AES_256_GCM_SHA384 = (ushort)4866, TLS_CHACHA20_POLY1305_SHA256 = (ushort)4867, TLS_AES_128_CCM_SHA256 = (ushort)4868, TLS_AES_128_CCM_8_SHA256 = (ushort)4869, TLS_ECDH_ECDSA_WITH_NULL_SHA = (ushort)49153, TLS_ECDH_ECDSA_WITH_RC4_128_SHA = (ushort)49154, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA = (ushort)49155, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA = (ushort)49156, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA = (ushort)49157, TLS_ECDHE_ECDSA_WITH_NULL_SHA = (ushort)49158, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA = (ushort)49159, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA = (ushort)49160, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = (ushort)49161, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = (ushort)49162, TLS_ECDH_RSA_WITH_NULL_SHA = (ushort)49163, TLS_ECDH_RSA_WITH_RC4_128_SHA = (ushort)49164, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA = (ushort)49165, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA = (ushort)49166, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA = (ushort)49167, TLS_ECDHE_RSA_WITH_NULL_SHA = (ushort)49168, TLS_ECDHE_RSA_WITH_RC4_128_SHA = (ushort)49169, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA = (ushort)49170, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = (ushort)49171, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = (ushort)49172, TLS_ECDH_anon_WITH_NULL_SHA = (ushort)49173, TLS_ECDH_anon_WITH_RC4_128_SHA = (ushort)49174, TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA = (ushort)49175, TLS_ECDH_anon_WITH_AES_128_CBC_SHA = (ushort)49176, TLS_ECDH_anon_WITH_AES_256_CBC_SHA = (ushort)49177, TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA = (ushort)49178, TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA = (ushort)49179, TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA = (ushort)49180, TLS_SRP_SHA_WITH_AES_128_CBC_SHA = (ushort)49181, TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA = (ushort)49182, TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA = (ushort)49183, TLS_SRP_SHA_WITH_AES_256_CBC_SHA = (ushort)49184, TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA = (ushort)49185, TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA = (ushort)49186, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = (ushort)49187, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = (ushort)49188, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 = (ushort)49189, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 = (ushort)49190, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = (ushort)49191, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = (ushort)49192, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 = (ushort)49193, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 = (ushort)49194, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = (ushort)49195, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = (ushort)49196, TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 = (ushort)49197, TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 = (ushort)49198, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = (ushort)49199, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = (ushort)49200, TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 = (ushort)49201, TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 = (ushort)49202, TLS_ECDHE_PSK_WITH_RC4_128_SHA = (ushort)49203, TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA = (ushort)49204, TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA = (ushort)49205, TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA = (ushort)49206, TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 = (ushort)49207, TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 = (ushort)49208, TLS_ECDHE_PSK_WITH_NULL_SHA = (ushort)49209, TLS_ECDHE_PSK_WITH_NULL_SHA256 = (ushort)49210, TLS_ECDHE_PSK_WITH_NULL_SHA384 = (ushort)49211, TLS_RSA_WITH_ARIA_128_CBC_SHA256 = (ushort)49212, TLS_RSA_WITH_ARIA_256_CBC_SHA384 = (ushort)49213, TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256 = (ushort)49214, TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384 = (ushort)49215, TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256 = (ushort)49216, TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384 = (ushort)49217, TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256 = (ushort)49218, TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384 = (ushort)49219, TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 = (ushort)49220, TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 = (ushort)49221, TLS_DH_anon_WITH_ARIA_128_CBC_SHA256 = (ushort)49222, TLS_DH_anon_WITH_ARIA_256_CBC_SHA384 = (ushort)49223, TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 = (ushort)49224, TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 = (ushort)49225, TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 = (ushort)49226, TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 = (ushort)49227, TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 = (ushort)49228, TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 = (ushort)49229, TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 = (ushort)49230, TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 = (ushort)49231, TLS_RSA_WITH_ARIA_128_GCM_SHA256 = (ushort)49232, TLS_RSA_WITH_ARIA_256_GCM_SHA384 = (ushort)49233, TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 = (ushort)49234, TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 = (ushort)49235, TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256 = (ushort)49236, TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384 = (ushort)49237, TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256 = (ushort)49238, TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384 = (ushort)49239, TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256 = (ushort)49240, TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384 = (ushort)49241, TLS_DH_anon_WITH_ARIA_128_GCM_SHA256 = (ushort)49242, TLS_DH_anon_WITH_ARIA_256_GCM_SHA384 = (ushort)49243, TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 = (ushort)49244, TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 = (ushort)49245, TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 = (ushort)49246, TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 = (ushort)49247, TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 = (ushort)49248, TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 = (ushort)49249, TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 = (ushort)49250, TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 = (ushort)49251, TLS_PSK_WITH_ARIA_128_CBC_SHA256 = (ushort)49252, TLS_PSK_WITH_ARIA_256_CBC_SHA384 = (ushort)49253, TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 = (ushort)49254, TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 = (ushort)49255, TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 = (ushort)49256, TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 = (ushort)49257, TLS_PSK_WITH_ARIA_128_GCM_SHA256 = (ushort)49258, TLS_PSK_WITH_ARIA_256_GCM_SHA384 = (ushort)49259, TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 = (ushort)49260, TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 = (ushort)49261, TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 = (ushort)49262, TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 = (ushort)49263, TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 = (ushort)49264, TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 = (ushort)49265, TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)49266, TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 = (ushort)49267, TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)49268, TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 = (ushort)49269, TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)49270, TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 = (ushort)49271, TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)49272, TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 = (ushort)49273, TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49274, TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49275, TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49276, TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49277, TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49278, TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49279, TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49280, TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49281, TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49282, TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49283, TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49284, TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49285, TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49286, TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49287, TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49288, TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49289, TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49290, TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49291, TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49292, TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49293, TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49294, TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49295, TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49296, TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49297, TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 = (ushort)49298, TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 = (ushort)49299, TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)49300, TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 = (ushort)49301, TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)49302, TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 = (ushort)49303, TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)49304, TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 = (ushort)49305, TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 = (ushort)49306, TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 = (ushort)49307, TLS_RSA_WITH_AES_128_CCM = (ushort)49308, TLS_RSA_WITH_AES_256_CCM = (ushort)49309, TLS_DHE_RSA_WITH_AES_128_CCM = (ushort)49310, TLS_DHE_RSA_WITH_AES_256_CCM = (ushort)49311, TLS_RSA_WITH_AES_128_CCM_8 = (ushort)49312, TLS_RSA_WITH_AES_256_CCM_8 = (ushort)49313, TLS_DHE_RSA_WITH_AES_128_CCM_8 = (ushort)49314, TLS_DHE_RSA_WITH_AES_256_CCM_8 = (ushort)49315, TLS_PSK_WITH_AES_128_CCM = (ushort)49316, TLS_PSK_WITH_AES_256_CCM = (ushort)49317, TLS_DHE_PSK_WITH_AES_128_CCM = (ushort)49318, TLS_DHE_PSK_WITH_AES_256_CCM = (ushort)49319, TLS_PSK_WITH_AES_128_CCM_8 = (ushort)49320, TLS_PSK_WITH_AES_256_CCM_8 = (ushort)49321, TLS_PSK_DHE_WITH_AES_128_CCM_8 = (ushort)49322, TLS_PSK_DHE_WITH_AES_256_CCM_8 = (ushort)49323, TLS_ECDHE_ECDSA_WITH_AES_128_CCM = (ushort)49324, TLS_ECDHE_ECDSA_WITH_AES_256_CCM = (ushort)49325, TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 = (ushort)49326, TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 = (ushort)49327, TLS_ECCPWD_WITH_AES_128_GCM_SHA256 = (ushort)49328, TLS_ECCPWD_WITH_AES_256_GCM_SHA384 = (ushort)49329, TLS_ECCPWD_WITH_AES_128_CCM_SHA256 = (ushort)49330, TLS_ECCPWD_WITH_AES_256_CCM_SHA384 = (ushort)49331, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = (ushort)52392, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = (ushort)52393, TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = (ushort)52394, TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 = (ushort)52395, TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 = (ushort)52396, TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 = (ushort)52397, TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 = (ushort)52398, TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256 = (ushort)53249, TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384 = (ushort)53250, TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256 = (ushort)53251, TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256 = (ushort)53253, } } namespace System.Security.Authentication { public partial class AuthenticationException : System.SystemException { public AuthenticationException() { } protected AuthenticationException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public AuthenticationException(string? message) { } public AuthenticationException(string? message, System.Exception? innerException) { } } public partial class InvalidCredentialException : System.Security.Authentication.AuthenticationException { public InvalidCredentialException() { } protected InvalidCredentialException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public InvalidCredentialException(string? message) { } public InvalidCredentialException(string? message, System.Exception? innerException) { } } } namespace System.Security.Authentication.ExtendedProtection { public partial class ExtendedProtectionPolicy : System.Runtime.Serialization.ISerializable { protected ExtendedProtectionPolicy(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement) { } public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement, System.Security.Authentication.ExtendedProtection.ChannelBinding customChannelBinding) { } public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement, System.Security.Authentication.ExtendedProtection.ProtectionScenario protectionScenario, System.Collections.ICollection? customServiceNames) { } public ExtendedProtectionPolicy(System.Security.Authentication.ExtendedProtection.PolicyEnforcement policyEnforcement, System.Security.Authentication.ExtendedProtection.ProtectionScenario protectionScenario, System.Security.Authentication.ExtendedProtection.ServiceNameCollection? customServiceNames) { } public System.Security.Authentication.ExtendedProtection.ChannelBinding? CustomChannelBinding { get { throw null; } } public System.Security.Authentication.ExtendedProtection.ServiceNameCollection? CustomServiceNames { get { throw null; } } public static bool OSSupportsExtendedProtection { get { throw null; } } public System.Security.Authentication.ExtendedProtection.PolicyEnforcement PolicyEnforcement { get { throw null; } } public System.Security.Authentication.ExtendedProtection.ProtectionScenario ProtectionScenario { get { throw null; } } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo? info, System.Runtime.Serialization.StreamingContext context) { } public override string ToString() { throw null; } } public enum PolicyEnforcement { Never = 0, WhenSupported = 1, Always = 2, } public enum ProtectionScenario { TransportSelected = 0, TrustedProxy = 1, } public partial class ServiceNameCollection : System.Collections.ReadOnlyCollectionBase { public ServiceNameCollection(System.Collections.ICollection items) { } public bool Contains(string? searchServiceName) { throw null; } public System.Security.Authentication.ExtendedProtection.ServiceNameCollection Merge(System.Collections.IEnumerable serviceNames) { throw null; } public System.Security.Authentication.ExtendedProtection.ServiceNameCollection Merge(string serviceName) { throw null; } } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Security.Authentication; using System.Text; using Ssl = Interop.Ssl; using OpenSsl = Interop.OpenSsl; namespace System.Net.Security { internal sealed class CipherSuitesPolicyPal { private static readonly byte[] AllowNoEncryptionDefault = Encoding.ASCII.GetBytes("ALL:eNULL\0"); private static readonly byte[] NoEncryptionDefault = Encoding.ASCII.GetBytes("eNULL\0"); private byte[] _cipherSuites; private byte[] _tls13CipherSuites; private List<TlsCipherSuite> _tlsCipherSuites = new List<TlsCipherSuite>(); internal IEnumerable<TlsCipherSuite> GetCipherSuites() => _tlsCipherSuites; internal CipherSuitesPolicyPal(IEnumerable<TlsCipherSuite> allowedCipherSuites) { if (!Interop.Ssl.Capabilities.Tls13Supported) { throw new PlatformNotSupportedException(SR.net_ssl_ciphersuites_policy_not_supported); } using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(Ssl.SslMethods.SSLv23_method)) { if (innerContext.IsInvalid) { throw OpenSsl.CreateSslException(SR.net_allocate_ssl_context_failed); } using (SafeSslHandle ssl = SafeSslHandle.Create(innerContext, false)) { if (ssl.IsInvalid) { throw OpenSsl.CreateSslException(SR.net_allocate_ssl_context_failed); } using (var tls13CipherSuites = new OpenSslStringBuilder()) using (var cipherSuites = new OpenSslStringBuilder()) { foreach (TlsCipherSuite cs in allowedCipherSuites) { string? name = Interop.Ssl.GetOpenSslCipherSuiteName( ssl, cs, out bool isTls12OrLower); if (name == null) { // we do not have a corresponding name // allowing less than user requested is OK continue; } _tlsCipherSuites.Add(cs); (isTls12OrLower ? cipherSuites : tls13CipherSuites).AllowCipherSuite(name); } _cipherSuites = cipherSuites.GetOpenSslString(); _tls13CipherSuites = tls13CipherSuites.GetOpenSslString(); } } } } internal static bool ShouldOptOutOfTls13(CipherSuitesPolicy? policy, EncryptionPolicy encryptionPolicy) { // if TLS 1.3 was explicitly requested the underlying code will throw // if default option (SslProtocols.None) is used we will opt-out of TLS 1.3 if (encryptionPolicy == EncryptionPolicy.NoEncryption) { // TLS 1.3 uses different ciphersuite restrictions than previous versions. // It has no equivalent to a NoEncryption option. return true; } if (policy == null) { // null means default, by default OpenSSL will choose if it wants to opt-out or not return false; } Debug.Assert( policy.Pal._tls13CipherSuites.Length != 0 && policy.Pal._tls13CipherSuites[policy.Pal._tls13CipherSuites.Length - 1] == 0, "null terminated string expected"); // we should opt out only when policy is empty return policy.Pal._tls13CipherSuites.Length == 1; } internal static bool ShouldOptOutOfLowerThanTls13(CipherSuitesPolicy? policy, EncryptionPolicy encryptionPolicy) { if (policy == null) { // null means default, by default OpenSSL will choose if it wants to opt-out or not return false; } Debug.Assert( policy.Pal._cipherSuites.Length != 0 && policy.Pal._cipherSuites[policy.Pal._cipherSuites.Length - 1] == 0, "null terminated string expected"); // we should opt out only when policy is empty return policy.Pal._cipherSuites.Length == 1; } private static bool IsOnlyTls13(SslProtocols protocols) => protocols == SslProtocols.Tls13; internal static bool WantsTls13(SslProtocols protocols) => protocols == SslProtocols.None || (protocols & SslProtocols.Tls13) != 0; internal static byte[]? GetOpenSslCipherList( CipherSuitesPolicy? policy, SslProtocols protocols, EncryptionPolicy encryptionPolicy) { if (IsOnlyTls13(protocols)) { // older cipher suites will be disabled through protocols return null; } if (policy == null) { return CipherListFromEncryptionPolicy(encryptionPolicy); } if (encryptionPolicy == EncryptionPolicy.NoEncryption) { throw new PlatformNotSupportedException(SR.net_ssl_ciphersuites_policy_not_supported); } return policy.Pal._cipherSuites; } internal static byte[]? GetOpenSslCipherSuites( CipherSuitesPolicy? policy, SslProtocols protocols, EncryptionPolicy encryptionPolicy) { if (!WantsTls13(protocols) || policy == null) { // do not call TLS 1.3 API, let OpenSSL choose what to do return null; } if (encryptionPolicy == EncryptionPolicy.NoEncryption) { throw new PlatformNotSupportedException(SR.net_ssl_ciphersuites_policy_not_supported); } return policy.Pal._tls13CipherSuites; } private static byte[]? CipherListFromEncryptionPolicy(EncryptionPolicy policy) { switch (policy) { case EncryptionPolicy.RequireEncryption: return null; case EncryptionPolicy.AllowNoEncryption: return AllowNoEncryptionDefault; case EncryptionPolicy.NoEncryption: return NoEncryptionDefault; default: Debug.Fail($"Unknown EncryptionPolicy value ({policy})"); return null; } } private sealed class OpenSslStringBuilder : StreamWriter { private const string SSL_TXT_Separator = ":"; private static readonly byte[] EmptyString = new byte[1] { 0 }; private MemoryStream _ms; private bool _first = true; public OpenSslStringBuilder() : base(new MemoryStream(), Encoding.ASCII) { _ms = (MemoryStream)BaseStream; } public void AllowCipherSuite(string cipherSuite) { if (_first) { _first = false; } else { Write(SSL_TXT_Separator); } Write(cipherSuite); } public byte[] GetOpenSslString() { if (_first) { return EmptyString; } Flush(); _ms.WriteByte(0); return _ms.ToArray(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Security.Authentication; using System.Text; using Ssl = Interop.Ssl; using OpenSsl = Interop.OpenSsl; namespace System.Net.Security { internal sealed class CipherSuitesPolicyPal { private static readonly byte[] AllowNoEncryptionDefault = Encoding.ASCII.GetBytes("ALL:eNULL\0"); private static readonly byte[] NoEncryptionDefault = Encoding.ASCII.GetBytes("eNULL\0"); private byte[] _cipherSuites; private byte[] _tls13CipherSuites; private List<TlsCipherSuite> _tlsCipherSuites = new List<TlsCipherSuite>(); internal IEnumerable<TlsCipherSuite> GetCipherSuites() => _tlsCipherSuites; internal CipherSuitesPolicyPal(IEnumerable<TlsCipherSuite> allowedCipherSuites) { if (!Interop.Ssl.Capabilities.Tls13Supported) { throw new PlatformNotSupportedException(SR.net_ssl_ciphersuites_policy_not_supported); } using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(Ssl.SslMethods.SSLv23_method)) { if (innerContext.IsInvalid) { throw OpenSsl.CreateSslException(SR.net_allocate_ssl_context_failed); } using (SafeSslHandle ssl = SafeSslHandle.Create(innerContext, false)) { if (ssl.IsInvalid) { throw OpenSsl.CreateSslException(SR.net_allocate_ssl_context_failed); } using (var tls13CipherSuites = new OpenSslStringBuilder()) using (var cipherSuites = new OpenSslStringBuilder()) { foreach (TlsCipherSuite cs in allowedCipherSuites) { string? name = Interop.Ssl.GetOpenSslCipherSuiteName( ssl, cs, out bool isTls12OrLower); if (name == null) { // we do not have a corresponding name // allowing less than user requested is OK continue; } _tlsCipherSuites.Add(cs); (isTls12OrLower ? cipherSuites : tls13CipherSuites).AllowCipherSuite(name); } _cipherSuites = cipherSuites.GetOpenSslString(); _tls13CipherSuites = tls13CipherSuites.GetOpenSslString(); } } } } internal static bool ShouldOptOutOfTls13(CipherSuitesPolicy? policy, EncryptionPolicy encryptionPolicy) { // if TLS 1.3 was explicitly requested the underlying code will throw // if default option (SslProtocols.None) is used we will opt-out of TLS 1.3 #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete if (encryptionPolicy == EncryptionPolicy.NoEncryption) { // TLS 1.3 uses different ciphersuite restrictions than previous versions. // It has no equivalent to a NoEncryption option. return true; } #pragma warning restore SYSLIB0040 if (policy == null) { // null means default, by default OpenSSL will choose if it wants to opt-out or not return false; } Debug.Assert( policy.Pal._tls13CipherSuites.Length != 0 && policy.Pal._tls13CipherSuites[policy.Pal._tls13CipherSuites.Length - 1] == 0, "null terminated string expected"); // we should opt out only when policy is empty return policy.Pal._tls13CipherSuites.Length == 1; } internal static bool ShouldOptOutOfLowerThanTls13(CipherSuitesPolicy? policy, EncryptionPolicy encryptionPolicy) { if (policy == null) { // null means default, by default OpenSSL will choose if it wants to opt-out or not return false; } Debug.Assert( policy.Pal._cipherSuites.Length != 0 && policy.Pal._cipherSuites[policy.Pal._cipherSuites.Length - 1] == 0, "null terminated string expected"); // we should opt out only when policy is empty return policy.Pal._cipherSuites.Length == 1; } private static bool IsOnlyTls13(SslProtocols protocols) => protocols == SslProtocols.Tls13; internal static bool WantsTls13(SslProtocols protocols) => protocols == SslProtocols.None || (protocols & SslProtocols.Tls13) != 0; internal static byte[]? GetOpenSslCipherList( CipherSuitesPolicy? policy, SslProtocols protocols, EncryptionPolicy encryptionPolicy) { if (IsOnlyTls13(protocols)) { // older cipher suites will be disabled through protocols return null; } if (policy == null) { return CipherListFromEncryptionPolicy(encryptionPolicy); } #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete if (encryptionPolicy == EncryptionPolicy.NoEncryption) { throw new PlatformNotSupportedException(SR.net_ssl_ciphersuites_policy_not_supported); } #pragma warning restore SYSLIB0040 return policy.Pal._cipherSuites; } internal static byte[]? GetOpenSslCipherSuites( CipherSuitesPolicy? policy, SslProtocols protocols, EncryptionPolicy encryptionPolicy) { if (!WantsTls13(protocols) || policy == null) { // do not call TLS 1.3 API, let OpenSSL choose what to do return null; } #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete if (encryptionPolicy == EncryptionPolicy.NoEncryption) { throw new PlatformNotSupportedException(SR.net_ssl_ciphersuites_policy_not_supported); } #pragma warning restore SYSLIB0040 return policy.Pal._tls13CipherSuites; } private static byte[]? CipherListFromEncryptionPolicy(EncryptionPolicy policy) { switch (policy) { case EncryptionPolicy.RequireEncryption: return null; #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete case EncryptionPolicy.AllowNoEncryption: return AllowNoEncryptionDefault; case EncryptionPolicy.NoEncryption: return NoEncryptionDefault; #pragma warning restore SYSLIB0040 default: Debug.Fail($"Unknown EncryptionPolicy value ({policy})"); return null; } } private sealed class OpenSslStringBuilder : StreamWriter { private const string SSL_TXT_Separator = ":"; private static readonly byte[] EmptyString = new byte[1] { 0 }; private MemoryStream _ms; private bool _first = true; public OpenSslStringBuilder() : base(new MemoryStream(), Encoding.ASCII) { _ms = (MemoryStream)BaseStream; } public void AllowCipherSuite(string cipherSuite) { if (_first) { _first = false; } else { Write(SSL_TXT_Separator); } Write(cipherSuite); } public byte[] GetOpenSslString() { if (_first) { return EmptyString; } Flush(); _ms.WriteByte(0); return _ms.ToArray(); } } } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/src/System/Net/Security/Pal.Android/SafeDeleteSslContext.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.Net.Http; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; using PAL_KeyAlgorithm = Interop.AndroidCrypto.PAL_KeyAlgorithm; using PAL_SSLStreamStatus = Interop.AndroidCrypto.PAL_SSLStreamStatus; #pragma warning disable CA1419 // TODO https://github.com/dotnet/roslyn-analyzers/issues/5232: not intended for use with P/Invoke namespace System.Net { internal sealed class SafeDeleteSslContext : SafeDeleteContext { private const int InitialBufferSize = 2048; private static readonly SslProtocols[] s_orderedSslProtocols = new SslProtocols[] { #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete SslProtocols.Tls, SslProtocols.Tls11, #pragma warning restore SYSLIB0039 SslProtocols.Tls12, SslProtocols.Tls13, }; private static readonly Lazy<SslProtocols> s_supportedSslProtocols = new Lazy<SslProtocols>(Interop.AndroidCrypto.SSLGetSupportedProtocols); private readonly SafeSslHandle _sslContext; private readonly Interop.AndroidCrypto.SSLReadCallback _readCallback; private readonly Interop.AndroidCrypto.SSLWriteCallback _writeCallback; private ArrayBuffer _inputBuffer = new ArrayBuffer(InitialBufferSize); private ArrayBuffer _outputBuffer = new ArrayBuffer(InitialBufferSize); public SafeSslHandle SslContext => _sslContext; public SafeDeleteSslContext(SafeFreeSslCredentials credential, SslAuthenticationOptions authOptions) : base(credential) { Debug.Assert((credential != null) && !credential.IsInvalid, "Invalid credential used in SafeDeleteSslContext"); try { unsafe { _readCallback = ReadFromConnection; _writeCallback = WriteToConnection; } _sslContext = CreateSslContext(credential); InitializeSslContext(_sslContext, _readCallback, _writeCallback, credential, authOptions); } catch (Exception ex) { Debug.Write("Exception Caught. - " + ex); Dispose(); throw; } } public override bool IsInvalid => _sslContext?.IsInvalid ?? true; protected override void Dispose(bool disposing) { if (disposing) { SafeSslHandle sslContext = _sslContext; if (sslContext != null) { _inputBuffer.Dispose(); _outputBuffer.Dispose(); sslContext.Dispose(); } } base.Dispose(disposing); } private unsafe void WriteToConnection(byte* data, int dataLength) { var inputBuffer = new ReadOnlySpan<byte>(data, dataLength); _outputBuffer.EnsureAvailableSpace(dataLength); inputBuffer.CopyTo(_outputBuffer.AvailableSpan); _outputBuffer.Commit(dataLength); } private unsafe PAL_SSLStreamStatus ReadFromConnection(byte* data, int* dataLength) { int toRead = *dataLength; if (toRead == 0) return PAL_SSLStreamStatus.OK; if (_inputBuffer.ActiveLength == 0) { *dataLength = 0; return PAL_SSLStreamStatus.NeedData; } toRead = Math.Min(toRead, _inputBuffer.ActiveLength); _inputBuffer.ActiveSpan.Slice(0, toRead).CopyTo(new Span<byte>(data, toRead)); _inputBuffer.Discard(toRead); *dataLength = toRead; return PAL_SSLStreamStatus.OK; } internal void Write(ReadOnlySpan<byte> buf) { _inputBuffer.EnsureAvailableSpace(buf.Length); buf.CopyTo(_inputBuffer.AvailableSpan); _inputBuffer.Commit(buf.Length); } internal int BytesReadyForConnection => _outputBuffer.ActiveLength; internal byte[]? ReadPendingWrites() { if (_outputBuffer.ActiveLength == 0) { return null; } byte[] buffer = _outputBuffer.ActiveSpan.ToArray(); _outputBuffer.Discard(_outputBuffer.ActiveLength); return buffer; } internal int ReadPendingWrites(byte[] buf, int offset, int count) { Debug.Assert(buf != null); Debug.Assert(offset >= 0); Debug.Assert(count >= 0); Debug.Assert(count <= buf.Length - offset); int limit = Math.Min(count, _outputBuffer.ActiveLength); _outputBuffer.ActiveSpan.Slice(0, limit).CopyTo(new Span<byte>(buf, offset, limit)); _outputBuffer.Discard(limit); return limit; } private static SafeSslHandle CreateSslContext(SafeFreeSslCredentials credential) { if (credential.CertificateContext == null) { return Interop.AndroidCrypto.SSLStreamCreate(); } SslStreamCertificateContext context = credential.CertificateContext; X509Certificate2 cert = context.Certificate; Debug.Assert(context.Certificate.HasPrivateKey); PAL_KeyAlgorithm algorithm; byte[] keyBytes; using (AsymmetricAlgorithm key = GetPrivateKeyAlgorithm(cert, out algorithm)) { keyBytes = key.ExportPkcs8PrivateKey(); } IntPtr[] ptrs = new IntPtr[context.IntermediateCertificates.Length + 1]; ptrs[0] = cert.Handle; for (int i = 0; i < context.IntermediateCertificates.Length; i++) { ptrs[i + 1] = context.IntermediateCertificates[i].Handle; } return Interop.AndroidCrypto.SSLStreamCreateWithCertificates(keyBytes, algorithm, ptrs); } private static AsymmetricAlgorithm GetPrivateKeyAlgorithm(X509Certificate2 cert, out PAL_KeyAlgorithm algorithm) { AsymmetricAlgorithm? key = cert.GetRSAPrivateKey(); if (key != null) { algorithm = PAL_KeyAlgorithm.RSA; return key; } key = cert.GetECDsaPrivateKey(); if (key != null) { algorithm = PAL_KeyAlgorithm.EC; return key; } key = cert.GetDSAPrivateKey(); if (key != null) { algorithm = PAL_KeyAlgorithm.DSA; return key; } throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } private static void InitializeSslContext( SafeSslHandle handle, Interop.AndroidCrypto.SSLReadCallback readCallback, Interop.AndroidCrypto.SSLWriteCallback writeCallback, SafeFreeSslCredentials credential, SslAuthenticationOptions authOptions) { switch (credential.Policy) { case EncryptionPolicy.RequireEncryption: case EncryptionPolicy.AllowNoEncryption: break; default: throw new PlatformNotSupportedException(SR.Format(SR.net_encryptionpolicy_notsupported, credential.Policy)); } bool isServer = authOptions.IsServer; if (authOptions.CipherSuitesPolicy != null) { // TODO: [AndroidCrypto] Handle non-system-default options throw new NotImplementedException(nameof(SafeDeleteSslContext)); } Interop.AndroidCrypto.SSLStreamInitialize(handle, isServer, readCallback, writeCallback, InitialBufferSize); if (credential.Protocols != SslProtocols.None) { SslProtocols protocolsToEnable = credential.Protocols & s_supportedSslProtocols.Value; if (protocolsToEnable == 0) { throw new PlatformNotSupportedException(SR.Format(SR.net_security_sslprotocol_notsupported, credential.Protocols)); } (int minIndex, int maxIndex) = protocolsToEnable.ValidateContiguous(s_orderedSslProtocols); Interop.AndroidCrypto.SSLStreamSetEnabledProtocols(handle, s_orderedSslProtocols.AsSpan(minIndex, maxIndex - minIndex + 1)); } if (authOptions.ApplicationProtocols != null && authOptions.ApplicationProtocols.Count != 0 && Interop.AndroidCrypto.SSLSupportsApplicationProtocolsConfiguration()) { // Set application protocols if the platform supports it. Otherwise, we will silently ignore the option. Interop.AndroidCrypto.SSLStreamSetApplicationProtocols(handle, authOptions.ApplicationProtocols); } if (isServer && authOptions.RemoteCertRequired) { Interop.AndroidCrypto.SSLStreamRequestClientAuthentication(handle); } if (!isServer && !string.IsNullOrEmpty(authOptions.TargetHost)) { Interop.AndroidCrypto.SSLStreamSetTargetHost(handle, authOptions.TargetHost); } } } }
// 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.Net.Http; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; using PAL_KeyAlgorithm = Interop.AndroidCrypto.PAL_KeyAlgorithm; using PAL_SSLStreamStatus = Interop.AndroidCrypto.PAL_SSLStreamStatus; #pragma warning disable CA1419 // TODO https://github.com/dotnet/roslyn-analyzers/issues/5232: not intended for use with P/Invoke namespace System.Net { internal sealed class SafeDeleteSslContext : SafeDeleteContext { private const int InitialBufferSize = 2048; private static readonly SslProtocols[] s_orderedSslProtocols = new SslProtocols[] { #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete SslProtocols.Tls, SslProtocols.Tls11, #pragma warning restore SYSLIB0039 SslProtocols.Tls12, SslProtocols.Tls13, }; private static readonly Lazy<SslProtocols> s_supportedSslProtocols = new Lazy<SslProtocols>(Interop.AndroidCrypto.SSLGetSupportedProtocols); private readonly SafeSslHandle _sslContext; private readonly Interop.AndroidCrypto.SSLReadCallback _readCallback; private readonly Interop.AndroidCrypto.SSLWriteCallback _writeCallback; private ArrayBuffer _inputBuffer = new ArrayBuffer(InitialBufferSize); private ArrayBuffer _outputBuffer = new ArrayBuffer(InitialBufferSize); public SafeSslHandle SslContext => _sslContext; public SafeDeleteSslContext(SafeFreeSslCredentials credential, SslAuthenticationOptions authOptions) : base(credential) { Debug.Assert((credential != null) && !credential.IsInvalid, "Invalid credential used in SafeDeleteSslContext"); try { unsafe { _readCallback = ReadFromConnection; _writeCallback = WriteToConnection; } _sslContext = CreateSslContext(credential); InitializeSslContext(_sslContext, _readCallback, _writeCallback, credential, authOptions); } catch (Exception ex) { Debug.Write("Exception Caught. - " + ex); Dispose(); throw; } } public override bool IsInvalid => _sslContext?.IsInvalid ?? true; protected override void Dispose(bool disposing) { if (disposing) { SafeSslHandle sslContext = _sslContext; if (sslContext != null) { _inputBuffer.Dispose(); _outputBuffer.Dispose(); sslContext.Dispose(); } } base.Dispose(disposing); } private unsafe void WriteToConnection(byte* data, int dataLength) { var inputBuffer = new ReadOnlySpan<byte>(data, dataLength); _outputBuffer.EnsureAvailableSpace(dataLength); inputBuffer.CopyTo(_outputBuffer.AvailableSpan); _outputBuffer.Commit(dataLength); } private unsafe PAL_SSLStreamStatus ReadFromConnection(byte* data, int* dataLength) { int toRead = *dataLength; if (toRead == 0) return PAL_SSLStreamStatus.OK; if (_inputBuffer.ActiveLength == 0) { *dataLength = 0; return PAL_SSLStreamStatus.NeedData; } toRead = Math.Min(toRead, _inputBuffer.ActiveLength); _inputBuffer.ActiveSpan.Slice(0, toRead).CopyTo(new Span<byte>(data, toRead)); _inputBuffer.Discard(toRead); *dataLength = toRead; return PAL_SSLStreamStatus.OK; } internal void Write(ReadOnlySpan<byte> buf) { _inputBuffer.EnsureAvailableSpace(buf.Length); buf.CopyTo(_inputBuffer.AvailableSpan); _inputBuffer.Commit(buf.Length); } internal int BytesReadyForConnection => _outputBuffer.ActiveLength; internal byte[]? ReadPendingWrites() { if (_outputBuffer.ActiveLength == 0) { return null; } byte[] buffer = _outputBuffer.ActiveSpan.ToArray(); _outputBuffer.Discard(_outputBuffer.ActiveLength); return buffer; } internal int ReadPendingWrites(byte[] buf, int offset, int count) { Debug.Assert(buf != null); Debug.Assert(offset >= 0); Debug.Assert(count >= 0); Debug.Assert(count <= buf.Length - offset); int limit = Math.Min(count, _outputBuffer.ActiveLength); _outputBuffer.ActiveSpan.Slice(0, limit).CopyTo(new Span<byte>(buf, offset, limit)); _outputBuffer.Discard(limit); return limit; } private static SafeSslHandle CreateSslContext(SafeFreeSslCredentials credential) { if (credential.CertificateContext == null) { return Interop.AndroidCrypto.SSLStreamCreate(); } SslStreamCertificateContext context = credential.CertificateContext; X509Certificate2 cert = context.Certificate; Debug.Assert(context.Certificate.HasPrivateKey); PAL_KeyAlgorithm algorithm; byte[] keyBytes; using (AsymmetricAlgorithm key = GetPrivateKeyAlgorithm(cert, out algorithm)) { keyBytes = key.ExportPkcs8PrivateKey(); } IntPtr[] ptrs = new IntPtr[context.IntermediateCertificates.Length + 1]; ptrs[0] = cert.Handle; for (int i = 0; i < context.IntermediateCertificates.Length; i++) { ptrs[i + 1] = context.IntermediateCertificates[i].Handle; } return Interop.AndroidCrypto.SSLStreamCreateWithCertificates(keyBytes, algorithm, ptrs); } private static AsymmetricAlgorithm GetPrivateKeyAlgorithm(X509Certificate2 cert, out PAL_KeyAlgorithm algorithm) { AsymmetricAlgorithm? key = cert.GetRSAPrivateKey(); if (key != null) { algorithm = PAL_KeyAlgorithm.RSA; return key; } key = cert.GetECDsaPrivateKey(); if (key != null) { algorithm = PAL_KeyAlgorithm.EC; return key; } key = cert.GetDSAPrivateKey(); if (key != null) { algorithm = PAL_KeyAlgorithm.DSA; return key; } throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } private static void InitializeSslContext( SafeSslHandle handle, Interop.AndroidCrypto.SSLReadCallback readCallback, Interop.AndroidCrypto.SSLWriteCallback writeCallback, SafeFreeSslCredentials credential, SslAuthenticationOptions authOptions) { switch (credential.Policy) { case EncryptionPolicy.RequireEncryption: #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete case EncryptionPolicy.AllowNoEncryption: break; #pragma warning restore SYSLIB0040 default: throw new PlatformNotSupportedException(SR.Format(SR.net_encryptionpolicy_notsupported, credential.Policy)); } bool isServer = authOptions.IsServer; if (authOptions.CipherSuitesPolicy != null) { // TODO: [AndroidCrypto] Handle non-system-default options throw new NotImplementedException(nameof(SafeDeleteSslContext)); } Interop.AndroidCrypto.SSLStreamInitialize(handle, isServer, readCallback, writeCallback, InitialBufferSize); if (credential.Protocols != SslProtocols.None) { SslProtocols protocolsToEnable = credential.Protocols & s_supportedSslProtocols.Value; if (protocolsToEnable == 0) { throw new PlatformNotSupportedException(SR.Format(SR.net_security_sslprotocol_notsupported, credential.Protocols)); } (int minIndex, int maxIndex) = protocolsToEnable.ValidateContiguous(s_orderedSslProtocols); Interop.AndroidCrypto.SSLStreamSetEnabledProtocols(handle, s_orderedSslProtocols.AsSpan(minIndex, maxIndex - minIndex + 1)); } if (authOptions.ApplicationProtocols != null && authOptions.ApplicationProtocols.Count != 0 && Interop.AndroidCrypto.SSLSupportsApplicationProtocolsConfiguration()) { // Set application protocols if the platform supports it. Otherwise, we will silently ignore the option. Interop.AndroidCrypto.SSLStreamSetApplicationProtocols(handle, authOptions.ApplicationProtocols); } if (isServer && authOptions.RemoteCertRequired) { Interop.AndroidCrypto.SSLStreamRequestClientAuthentication(handle); } if (!isServer && !string.IsNullOrEmpty(authOptions.TargetHost)) { Interop.AndroidCrypto.SSLStreamSetTargetHost(handle, authOptions.TargetHost); } } } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeDeleteSslContext.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.Net.Http; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; #pragma warning disable CA1419 // TODO https://github.com/dotnet/roslyn-analyzers/issues/5232: not intended for use with P/Invoke namespace System.Net { internal sealed class SafeDeleteSslContext : SafeDeleteContext { // mapped from OSX error codes private const int OSStatus_writErr = -20; private const int OSStatus_readErr = -19; private const int OSStatus_noErr = 0; private const int OSStatus_errSSLWouldBlock = -9803; private const int InitialBufferSize = 2048; private SafeSslHandle _sslContext; private ArrayBuffer _inputBuffer = new ArrayBuffer(InitialBufferSize); private ArrayBuffer _outputBuffer = new ArrayBuffer(InitialBufferSize); public SafeSslHandle SslContext => _sslContext; public SafeDeleteSslContext(SafeFreeSslCredentials credential, SslAuthenticationOptions sslAuthenticationOptions) : base(credential) { Debug.Assert((null != credential) && !credential.IsInvalid, "Invalid credential used in SafeDeleteSslContext"); try { int osStatus; _sslContext = CreateSslContext(credential, sslAuthenticationOptions.IsServer); // Make sure the class instance is associated to the session and is provided // in the Read/Write callback connection parameter SslSetConnection(_sslContext); unsafe { osStatus = Interop.AppleCrypto.SslSetIoCallbacks( _sslContext, &ReadFromConnection, &WriteToConnection); } if (osStatus != 0) { throw Interop.AppleCrypto.CreateExceptionForOSStatus(osStatus); } if (sslAuthenticationOptions.CipherSuitesPolicy != null) { uint[] tlsCipherSuites = sslAuthenticationOptions.CipherSuitesPolicy.Pal.TlsCipherSuites; unsafe { fixed (uint* cipherSuites = tlsCipherSuites) { osStatus = Interop.AppleCrypto.SslSetEnabledCipherSuites( _sslContext, cipherSuites, tlsCipherSuites.Length); if (osStatus != 0) { throw Interop.AppleCrypto.CreateExceptionForOSStatus(osStatus); } } } } if (sslAuthenticationOptions.ApplicationProtocols != null && sslAuthenticationOptions.ApplicationProtocols.Count != 0) { // On OSX coretls supports only client side. For server, we will silently ignore the option. if (!sslAuthenticationOptions.IsServer) { Interop.AppleCrypto.SslCtxSetAlpnProtos(_sslContext, sslAuthenticationOptions.ApplicationProtocols); } } } catch (Exception ex) { Debug.Write("Exception Caught. - " + ex); Dispose(); throw; } if (!string.IsNullOrEmpty(sslAuthenticationOptions.TargetHost) && !sslAuthenticationOptions.IsServer) { Interop.AppleCrypto.SslSetTargetName(_sslContext, sslAuthenticationOptions.TargetHost); } if (sslAuthenticationOptions.CertificateContext == null && sslAuthenticationOptions.CertSelectionDelegate != null) { // certificate was not provided but there is user callback. We can break handshake if server asks for certificate // and we can try to get it based on remote certificate and trusted issuers. Interop.AppleCrypto.SslBreakOnCertRequested(_sslContext, true); } if (sslAuthenticationOptions.IsServer) { if (sslAuthenticationOptions.RemoteCertRequired) { Interop.AppleCrypto.SslSetAcceptClientCert(_sslContext); } if (sslAuthenticationOptions.CertificateContext?.Trust?._sendTrustInHandshake == true) { SslCertificateTrust trust = sslAuthenticationOptions.CertificateContext!.Trust!; X509Certificate2Collection certList = (trust._trustList ?? trust._store!.Certificates); Debug.Assert(certList != null, "certList != null"); Span<IntPtr> handles = certList.Count <= 256 ? stackalloc IntPtr[256] : new IntPtr[certList.Count]; for (int i = 0; i < certList.Count; i++) { handles[i] = certList[i].Handle; } Interop.AppleCrypto.SslSetCertificateAuthorities(_sslContext, handles.Slice(0, certList.Count), true); } } } private static SafeSslHandle CreateSslContext(SafeFreeSslCredentials credential, bool isServer) { switch (credential.Policy) { case EncryptionPolicy.RequireEncryption: case EncryptionPolicy.AllowNoEncryption: // SecureTransport doesn't allow TLS_NULL_NULL_WITH_NULL, but // since AllowNoEncryption intersect OS-supported isn't nothing, // let it pass. break; default: throw new PlatformNotSupportedException(SR.Format(SR.net_encryptionpolicy_notsupported, credential.Policy)); } SafeSslHandle sslContext = Interop.AppleCrypto.SslCreateContext(isServer ? 1 : 0); try { if (sslContext.IsInvalid) { // This is as likely as anything. No error conditions are defined for // the OS function, and our shim only adds a NULL if isServer isn't a normalized bool. throw new OutOfMemoryException(); } // Let None mean "system default" if (credential.Protocols != SslProtocols.None) { SetProtocols(sslContext, credential.Protocols); } if (credential.CertificateContext != null) { SetCertificate(sslContext, credential.CertificateContext); } Interop.AppleCrypto.SslBreakOnCertRequested(sslContext, true); Interop.AppleCrypto.SslBreakOnServerAuth(sslContext, true); Interop.AppleCrypto.SslBreakOnClientAuth(sslContext, true); } catch { sslContext.Dispose(); throw; } return sslContext; } private void SslSetConnection(SafeSslHandle sslContext) { GCHandle handle = GCHandle.Alloc(this, GCHandleType.Weak); Interop.AppleCrypto.SslSetConnection(sslContext, GCHandle.ToIntPtr(handle)); } public override bool IsInvalid => _sslContext?.IsInvalid ?? true; protected override void Dispose(bool disposing) { if (disposing) { SafeSslHandle sslContext = _sslContext; if (null != sslContext) { lock (_sslContext) { _inputBuffer.Dispose(); _outputBuffer.Dispose(); } sslContext.Dispose(); } } base.Dispose(disposing); } [UnmanagedCallersOnly] private static unsafe int WriteToConnection(IntPtr connection, byte* data, void** dataLength) { SafeDeleteSslContext? context = (SafeDeleteSslContext?)GCHandle.FromIntPtr(connection).Target; Debug.Assert(context != null); // We don't pool these buffers and we can't because there's a race between their us in the native // read/write callbacks and being disposed when the SafeHandle is disposed. This race is benign currently, // but if we were to pool the buffers we would have a potential use-after-free issue. try { lock (context) { ulong length = (ulong)*dataLength; Debug.Assert(length <= int.MaxValue); int toWrite = (int)length; var inputBuffer = new ReadOnlySpan<byte>(data, toWrite); context._outputBuffer.EnsureAvailableSpace(toWrite); inputBuffer.CopyTo(context._outputBuffer.AvailableSpan); context._outputBuffer.Commit(toWrite); // Since we can enqueue everything, no need to re-assign *dataLength. return OSStatus_noErr; } } catch (Exception e) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(context, $"WritingToConnection failed: {e.Message}"); return OSStatus_writErr; } } [UnmanagedCallersOnly] private static unsafe int ReadFromConnection(IntPtr connection, byte* data, void** dataLength) { SafeDeleteSslContext? context = (SafeDeleteSslContext?)GCHandle.FromIntPtr(connection).Target; Debug.Assert(context != null); try { lock (context) { ulong toRead = (ulong)*dataLength; if (toRead == 0) { return OSStatus_noErr; } uint transferred = 0; if (context._inputBuffer.ActiveLength == 0) { *dataLength = (void*)0; return OSStatus_errSSLWouldBlock; } int limit = Math.Min((int)toRead, context._inputBuffer.ActiveLength); context._inputBuffer.ActiveSpan.Slice(0, limit).CopyTo(new Span<byte>(data, limit)); context._inputBuffer.Discard(limit); transferred = (uint)limit; *dataLength = (void*)transferred; return OSStatus_noErr; } } catch (Exception e) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(context, $"ReadFromConnectionfailed: {e.Message}"); return OSStatus_readErr; } } internal void Write(ReadOnlySpan<byte> buf) { lock (_sslContext) { _inputBuffer.EnsureAvailableSpace(buf.Length); buf.CopyTo(_inputBuffer.AvailableSpan); _inputBuffer.Commit(buf.Length); } } internal int BytesReadyForConnection => _outputBuffer.ActiveLength; internal byte[]? ReadPendingWrites() { lock (_sslContext) { if (_outputBuffer.ActiveLength == 0) { return null; } byte[] buffer = _outputBuffer.ActiveSpan.ToArray(); _outputBuffer.Discard(_outputBuffer.ActiveLength); return buffer; } } internal int ReadPendingWrites(byte[] buf, int offset, int count) { Debug.Assert(buf != null); Debug.Assert(offset >= 0); Debug.Assert(count >= 0); Debug.Assert(count <= buf.Length - offset); lock (_sslContext) { int limit = Math.Min(count, _outputBuffer.ActiveLength); _outputBuffer.ActiveSpan.Slice(0, limit).CopyTo(new Span<byte>(buf, offset, limit)); _outputBuffer.Discard(limit); return limit; } } private static readonly SslProtocols[] s_orderedSslProtocols = new SslProtocols[5] { #pragma warning disable 0618 SslProtocols.Ssl2, SslProtocols.Ssl3, #pragma warning restore 0618 #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete SslProtocols.Tls, SslProtocols.Tls11, #pragma warning restore SYSLIB0039 SslProtocols.Tls12 }; private static void SetProtocols(SafeSslHandle sslContext, SslProtocols protocols) { (int minIndex, int maxIndex) = protocols.ValidateContiguous(s_orderedSslProtocols); SslProtocols minProtocolId = s_orderedSslProtocols[minIndex]; SslProtocols maxProtocolId = s_orderedSslProtocols[maxIndex]; // Set the min and max. Interop.AppleCrypto.SslSetMinProtocolVersion(sslContext, minProtocolId); Interop.AppleCrypto.SslSetMaxProtocolVersion(sslContext, maxProtocolId); } internal static void SetCertificate(SafeSslHandle sslContext, SslStreamCertificateContext context) { Debug.Assert(sslContext != null, "sslContext != null"); IntPtr[] ptrs = new IntPtr[context!.IntermediateCertificates!.Length + 1]; for (int i = 0; i < context.IntermediateCertificates.Length; i++) { X509Certificate2 intermediateCert = context.IntermediateCertificates[i]; if (intermediateCert.HasPrivateKey) { // In the unlikely event that we get a certificate with a private key from // a chain, clear it to the certificate. // // The current value of intermediateCert is still in elements, which will // get Disposed at the end of this method. The new value will be // in the intermediate certs array, which also gets serially Disposed. intermediateCert = new X509Certificate2(intermediateCert.RawDataMemory.Span); } ptrs[i + 1] = intermediateCert.Handle; } ptrs[0] = context!.Certificate!.Handle; Interop.AppleCrypto.SslSetCertificate(sslContext, ptrs); } } }
// 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.Net.Http; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; #pragma warning disable CA1419 // TODO https://github.com/dotnet/roslyn-analyzers/issues/5232: not intended for use with P/Invoke namespace System.Net { internal sealed class SafeDeleteSslContext : SafeDeleteContext { // mapped from OSX error codes private const int OSStatus_writErr = -20; private const int OSStatus_readErr = -19; private const int OSStatus_noErr = 0; private const int OSStatus_errSSLWouldBlock = -9803; private const int InitialBufferSize = 2048; private SafeSslHandle _sslContext; private ArrayBuffer _inputBuffer = new ArrayBuffer(InitialBufferSize); private ArrayBuffer _outputBuffer = new ArrayBuffer(InitialBufferSize); public SafeSslHandle SslContext => _sslContext; public SafeDeleteSslContext(SafeFreeSslCredentials credential, SslAuthenticationOptions sslAuthenticationOptions) : base(credential) { Debug.Assert((null != credential) && !credential.IsInvalid, "Invalid credential used in SafeDeleteSslContext"); try { int osStatus; _sslContext = CreateSslContext(credential, sslAuthenticationOptions.IsServer); // Make sure the class instance is associated to the session and is provided // in the Read/Write callback connection parameter SslSetConnection(_sslContext); unsafe { osStatus = Interop.AppleCrypto.SslSetIoCallbacks( _sslContext, &ReadFromConnection, &WriteToConnection); } if (osStatus != 0) { throw Interop.AppleCrypto.CreateExceptionForOSStatus(osStatus); } if (sslAuthenticationOptions.CipherSuitesPolicy != null) { uint[] tlsCipherSuites = sslAuthenticationOptions.CipherSuitesPolicy.Pal.TlsCipherSuites; unsafe { fixed (uint* cipherSuites = tlsCipherSuites) { osStatus = Interop.AppleCrypto.SslSetEnabledCipherSuites( _sslContext, cipherSuites, tlsCipherSuites.Length); if (osStatus != 0) { throw Interop.AppleCrypto.CreateExceptionForOSStatus(osStatus); } } } } if (sslAuthenticationOptions.ApplicationProtocols != null && sslAuthenticationOptions.ApplicationProtocols.Count != 0) { // On OSX coretls supports only client side. For server, we will silently ignore the option. if (!sslAuthenticationOptions.IsServer) { Interop.AppleCrypto.SslCtxSetAlpnProtos(_sslContext, sslAuthenticationOptions.ApplicationProtocols); } } } catch (Exception ex) { Debug.Write("Exception Caught. - " + ex); Dispose(); throw; } if (!string.IsNullOrEmpty(sslAuthenticationOptions.TargetHost) && !sslAuthenticationOptions.IsServer) { Interop.AppleCrypto.SslSetTargetName(_sslContext, sslAuthenticationOptions.TargetHost); } if (sslAuthenticationOptions.CertificateContext == null && sslAuthenticationOptions.CertSelectionDelegate != null) { // certificate was not provided but there is user callback. We can break handshake if server asks for certificate // and we can try to get it based on remote certificate and trusted issuers. Interop.AppleCrypto.SslBreakOnCertRequested(_sslContext, true); } if (sslAuthenticationOptions.IsServer) { if (sslAuthenticationOptions.RemoteCertRequired) { Interop.AppleCrypto.SslSetAcceptClientCert(_sslContext); } if (sslAuthenticationOptions.CertificateContext?.Trust?._sendTrustInHandshake == true) { SslCertificateTrust trust = sslAuthenticationOptions.CertificateContext!.Trust!; X509Certificate2Collection certList = (trust._trustList ?? trust._store!.Certificates); Debug.Assert(certList != null, "certList != null"); Span<IntPtr> handles = certList.Count <= 256 ? stackalloc IntPtr[256] : new IntPtr[certList.Count]; for (int i = 0; i < certList.Count; i++) { handles[i] = certList[i].Handle; } Interop.AppleCrypto.SslSetCertificateAuthorities(_sslContext, handles.Slice(0, certList.Count), true); } } } private static SafeSslHandle CreateSslContext(SafeFreeSslCredentials credential, bool isServer) { switch (credential.Policy) { case EncryptionPolicy.RequireEncryption: #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete case EncryptionPolicy.AllowNoEncryption: // SecureTransport doesn't allow TLS_NULL_NULL_WITH_NULL, but // since AllowNoEncryption intersect OS-supported isn't nothing, // let it pass. break; #pragma warning restore SYSLIB0040 default: throw new PlatformNotSupportedException(SR.Format(SR.net_encryptionpolicy_notsupported, credential.Policy)); } SafeSslHandle sslContext = Interop.AppleCrypto.SslCreateContext(isServer ? 1 : 0); try { if (sslContext.IsInvalid) { // This is as likely as anything. No error conditions are defined for // the OS function, and our shim only adds a NULL if isServer isn't a normalized bool. throw new OutOfMemoryException(); } // Let None mean "system default" if (credential.Protocols != SslProtocols.None) { SetProtocols(sslContext, credential.Protocols); } if (credential.CertificateContext != null) { SetCertificate(sslContext, credential.CertificateContext); } Interop.AppleCrypto.SslBreakOnCertRequested(sslContext, true); Interop.AppleCrypto.SslBreakOnServerAuth(sslContext, true); Interop.AppleCrypto.SslBreakOnClientAuth(sslContext, true); } catch { sslContext.Dispose(); throw; } return sslContext; } private void SslSetConnection(SafeSslHandle sslContext) { GCHandle handle = GCHandle.Alloc(this, GCHandleType.Weak); Interop.AppleCrypto.SslSetConnection(sslContext, GCHandle.ToIntPtr(handle)); } public override bool IsInvalid => _sslContext?.IsInvalid ?? true; protected override void Dispose(bool disposing) { if (disposing) { SafeSslHandle sslContext = _sslContext; if (null != sslContext) { lock (_sslContext) { _inputBuffer.Dispose(); _outputBuffer.Dispose(); } sslContext.Dispose(); } } base.Dispose(disposing); } [UnmanagedCallersOnly] private static unsafe int WriteToConnection(IntPtr connection, byte* data, void** dataLength) { SafeDeleteSslContext? context = (SafeDeleteSslContext?)GCHandle.FromIntPtr(connection).Target; Debug.Assert(context != null); // We don't pool these buffers and we can't because there's a race between their us in the native // read/write callbacks and being disposed when the SafeHandle is disposed. This race is benign currently, // but if we were to pool the buffers we would have a potential use-after-free issue. try { lock (context) { ulong length = (ulong)*dataLength; Debug.Assert(length <= int.MaxValue); int toWrite = (int)length; var inputBuffer = new ReadOnlySpan<byte>(data, toWrite); context._outputBuffer.EnsureAvailableSpace(toWrite); inputBuffer.CopyTo(context._outputBuffer.AvailableSpan); context._outputBuffer.Commit(toWrite); // Since we can enqueue everything, no need to re-assign *dataLength. return OSStatus_noErr; } } catch (Exception e) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(context, $"WritingToConnection failed: {e.Message}"); return OSStatus_writErr; } } [UnmanagedCallersOnly] private static unsafe int ReadFromConnection(IntPtr connection, byte* data, void** dataLength) { SafeDeleteSslContext? context = (SafeDeleteSslContext?)GCHandle.FromIntPtr(connection).Target; Debug.Assert(context != null); try { lock (context) { ulong toRead = (ulong)*dataLength; if (toRead == 0) { return OSStatus_noErr; } uint transferred = 0; if (context._inputBuffer.ActiveLength == 0) { *dataLength = (void*)0; return OSStatus_errSSLWouldBlock; } int limit = Math.Min((int)toRead, context._inputBuffer.ActiveLength); context._inputBuffer.ActiveSpan.Slice(0, limit).CopyTo(new Span<byte>(data, limit)); context._inputBuffer.Discard(limit); transferred = (uint)limit; *dataLength = (void*)transferred; return OSStatus_noErr; } } catch (Exception e) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(context, $"ReadFromConnectionfailed: {e.Message}"); return OSStatus_readErr; } } internal void Write(ReadOnlySpan<byte> buf) { lock (_sslContext) { _inputBuffer.EnsureAvailableSpace(buf.Length); buf.CopyTo(_inputBuffer.AvailableSpan); _inputBuffer.Commit(buf.Length); } } internal int BytesReadyForConnection => _outputBuffer.ActiveLength; internal byte[]? ReadPendingWrites() { lock (_sslContext) { if (_outputBuffer.ActiveLength == 0) { return null; } byte[] buffer = _outputBuffer.ActiveSpan.ToArray(); _outputBuffer.Discard(_outputBuffer.ActiveLength); return buffer; } } internal int ReadPendingWrites(byte[] buf, int offset, int count) { Debug.Assert(buf != null); Debug.Assert(offset >= 0); Debug.Assert(count >= 0); Debug.Assert(count <= buf.Length - offset); lock (_sslContext) { int limit = Math.Min(count, _outputBuffer.ActiveLength); _outputBuffer.ActiveSpan.Slice(0, limit).CopyTo(new Span<byte>(buf, offset, limit)); _outputBuffer.Discard(limit); return limit; } } private static readonly SslProtocols[] s_orderedSslProtocols = new SslProtocols[5] { #pragma warning disable 0618 SslProtocols.Ssl2, SslProtocols.Ssl3, #pragma warning restore 0618 #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete SslProtocols.Tls, SslProtocols.Tls11, #pragma warning restore SYSLIB0039 SslProtocols.Tls12 }; private static void SetProtocols(SafeSslHandle sslContext, SslProtocols protocols) { (int minIndex, int maxIndex) = protocols.ValidateContiguous(s_orderedSslProtocols); SslProtocols minProtocolId = s_orderedSslProtocols[minIndex]; SslProtocols maxProtocolId = s_orderedSslProtocols[maxIndex]; // Set the min and max. Interop.AppleCrypto.SslSetMinProtocolVersion(sslContext, minProtocolId); Interop.AppleCrypto.SslSetMaxProtocolVersion(sslContext, maxProtocolId); } internal static void SetCertificate(SafeSslHandle sslContext, SslStreamCertificateContext context) { Debug.Assert(sslContext != null, "sslContext != null"); IntPtr[] ptrs = new IntPtr[context!.IntermediateCertificates!.Length + 1]; for (int i = 0; i < context.IntermediateCertificates.Length; i++) { X509Certificate2 intermediateCert = context.IntermediateCertificates[i]; if (intermediateCert.HasPrivateKey) { // In the unlikely event that we get a certificate with a private key from // a chain, clear it to the certificate. // // The current value of intermediateCert is still in elements, which will // get Disposed at the end of this method. The new value will be // in the intermediate certs array, which also gets serially Disposed. intermediateCert = new X509Certificate2(intermediateCert.RawDataMemory.Span); } ptrs[i + 1] = intermediateCert.Handle; } ptrs[0] = context!.Certificate!.Handle; Interop.AppleCrypto.SslSetCertificate(sslContext, ptrs); } } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/src/System/Net/Security/SslClientAuthenticationOptions.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.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; namespace System.Net.Security { public class SslClientAuthenticationOptions { private EncryptionPolicy _encryptionPolicy = EncryptionPolicy.RequireEncryption; private X509RevocationMode _checkCertificateRevocation = X509RevocationMode.NoCheck; private SslProtocols _enabledSslProtocols = SecurityProtocol.SystemDefaultSecurityProtocols; private bool _allowRenegotiation = true; public bool AllowRenegotiation { get => _allowRenegotiation; set => _allowRenegotiation = value; } public LocalCertificateSelectionCallback? LocalCertificateSelectionCallback { get; set; } public RemoteCertificateValidationCallback? RemoteCertificateValidationCallback { get; set; } public List<SslApplicationProtocol>? ApplicationProtocols { get; set; } public string? TargetHost { get; set; } public X509CertificateCollection? ClientCertificates { get; set; } public X509RevocationMode CertificateRevocationCheckMode { get => _checkCertificateRevocation; set { if (value != X509RevocationMode.NoCheck && value != X509RevocationMode.Offline && value != X509RevocationMode.Online) { throw new ArgumentException(SR.Format(SR.net_invalid_enum, nameof(X509RevocationMode)), nameof(value)); } _checkCertificateRevocation = value; } } public EncryptionPolicy EncryptionPolicy { get => _encryptionPolicy; set { if (value != EncryptionPolicy.RequireEncryption && value != EncryptionPolicy.AllowNoEncryption && value != EncryptionPolicy.NoEncryption) { throw new ArgumentException(SR.Format(SR.net_invalid_enum, nameof(EncryptionPolicy)), nameof(value)); } _encryptionPolicy = value; } } public SslProtocols EnabledSslProtocols { get => _enabledSslProtocols; set => _enabledSslProtocols = value; } /// <summary> /// Specifies cipher suites allowed to be used for TLS. /// When set to null operating system default will be used. /// Use extreme caution when changing this setting. /// </summary> public CipherSuitesPolicy? CipherSuitesPolicy { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; namespace System.Net.Security { public class SslClientAuthenticationOptions { private EncryptionPolicy _encryptionPolicy = EncryptionPolicy.RequireEncryption; private X509RevocationMode _checkCertificateRevocation = X509RevocationMode.NoCheck; private SslProtocols _enabledSslProtocols = SecurityProtocol.SystemDefaultSecurityProtocols; private bool _allowRenegotiation = true; public bool AllowRenegotiation { get => _allowRenegotiation; set => _allowRenegotiation = value; } public LocalCertificateSelectionCallback? LocalCertificateSelectionCallback { get; set; } public RemoteCertificateValidationCallback? RemoteCertificateValidationCallback { get; set; } public List<SslApplicationProtocol>? ApplicationProtocols { get; set; } public string? TargetHost { get; set; } public X509CertificateCollection? ClientCertificates { get; set; } public X509RevocationMode CertificateRevocationCheckMode { get => _checkCertificateRevocation; set { if (value != X509RevocationMode.NoCheck && value != X509RevocationMode.Offline && value != X509RevocationMode.Online) { throw new ArgumentException(SR.Format(SR.net_invalid_enum, nameof(X509RevocationMode)), nameof(value)); } _checkCertificateRevocation = value; } } public EncryptionPolicy EncryptionPolicy { get => _encryptionPolicy; set { #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete if (value != EncryptionPolicy.RequireEncryption && value != EncryptionPolicy.AllowNoEncryption && value != EncryptionPolicy.NoEncryption) { throw new ArgumentException(SR.Format(SR.net_invalid_enum, nameof(EncryptionPolicy)), nameof(value)); } #pragma warning restore SYSLIB0040 _encryptionPolicy = value; } } public SslProtocols EnabledSslProtocols { get => _enabledSslProtocols; set => _enabledSslProtocols = value; } /// <summary> /// Specifies cipher suites allowed to be used for TLS. /// When set to null operating system default will be used. /// Use extreme caution when changing this setting. /// </summary> public CipherSuitesPolicy? CipherSuitesPolicy { get; set; } } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/src/System/Net/Security/SslServerAuthenticationOptions.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.Authentication; using System.Security.Cryptography.X509Certificates; namespace System.Net.Security { public class SslServerAuthenticationOptions { private X509RevocationMode _checkCertificateRevocation = X509RevocationMode.NoCheck; private SslProtocols _enabledSslProtocols = SecurityProtocol.SystemDefaultSecurityProtocols; private EncryptionPolicy _encryptionPolicy = EncryptionPolicy.RequireEncryption; private bool _allowRenegotiation; public bool AllowRenegotiation { get => _allowRenegotiation; set => _allowRenegotiation = value; } public bool ClientCertificateRequired { get; set; } public List<SslApplicationProtocol>? ApplicationProtocols { get; set; } public RemoteCertificateValidationCallback? RemoteCertificateValidationCallback { get; set; } public ServerCertificateSelectionCallback? ServerCertificateSelectionCallback { get; set; } public X509Certificate? ServerCertificate { get; set; } public SslStreamCertificateContext? ServerCertificateContext { get; set; } public SslProtocols EnabledSslProtocols { get => _enabledSslProtocols; set => _enabledSslProtocols = value; } public X509RevocationMode CertificateRevocationCheckMode { get => _checkCertificateRevocation; set { if (value != X509RevocationMode.NoCheck && value != X509RevocationMode.Offline && value != X509RevocationMode.Online) { throw new ArgumentException(SR.Format(SR.net_invalid_enum, nameof(X509RevocationMode)), nameof(value)); } _checkCertificateRevocation = value; } } public EncryptionPolicy EncryptionPolicy { get => _encryptionPolicy; set { if (value != EncryptionPolicy.RequireEncryption && value != EncryptionPolicy.AllowNoEncryption && value != EncryptionPolicy.NoEncryption) { throw new ArgumentException(SR.Format(SR.net_invalid_enum, nameof(EncryptionPolicy)), nameof(value)); } _encryptionPolicy = value; } } /// <summary> /// Specifies cipher suites allowed to be used for TLS. /// When set to null operating system default will be used. /// Use extreme caution when changing this setting. /// </summary> public CipherSuitesPolicy? CipherSuitesPolicy { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; namespace System.Net.Security { public class SslServerAuthenticationOptions { private X509RevocationMode _checkCertificateRevocation = X509RevocationMode.NoCheck; private SslProtocols _enabledSslProtocols = SecurityProtocol.SystemDefaultSecurityProtocols; private EncryptionPolicy _encryptionPolicy = EncryptionPolicy.RequireEncryption; private bool _allowRenegotiation; public bool AllowRenegotiation { get => _allowRenegotiation; set => _allowRenegotiation = value; } public bool ClientCertificateRequired { get; set; } public List<SslApplicationProtocol>? ApplicationProtocols { get; set; } public RemoteCertificateValidationCallback? RemoteCertificateValidationCallback { get; set; } public ServerCertificateSelectionCallback? ServerCertificateSelectionCallback { get; set; } public X509Certificate? ServerCertificate { get; set; } public SslStreamCertificateContext? ServerCertificateContext { get; set; } public SslProtocols EnabledSslProtocols { get => _enabledSslProtocols; set => _enabledSslProtocols = value; } public X509RevocationMode CertificateRevocationCheckMode { get => _checkCertificateRevocation; set { if (value != X509RevocationMode.NoCheck && value != X509RevocationMode.Offline && value != X509RevocationMode.Online) { throw new ArgumentException(SR.Format(SR.net_invalid_enum, nameof(X509RevocationMode)), nameof(value)); } _checkCertificateRevocation = value; } } public EncryptionPolicy EncryptionPolicy { get => _encryptionPolicy; set { #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete if (value != EncryptionPolicy.RequireEncryption && value != EncryptionPolicy.AllowNoEncryption && value != EncryptionPolicy.NoEncryption) { throw new ArgumentException(SR.Format(SR.net_invalid_enum, nameof(EncryptionPolicy)), nameof(value)); } #pragma warning restore SYSLIB0040 _encryptionPolicy = value; } } /// <summary> /// Specifies cipher suites allowed to be used for TLS. /// When set to null operating system default will be used. /// Use extreme caution when changing this setting. /// </summary> public CipherSuitesPolicy? CipherSuitesPolicy { get; set; } } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/src/System/Net/Security/SslStream.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.IO; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace System.Net.Security { public enum EncryptionPolicy { // Prohibit null ciphers (current system defaults) RequireEncryption = 0, // Add null ciphers to current system defaults AllowNoEncryption, // Request null ciphers only NoEncryption } // A user delegate used to verify remote SSL certificate. public delegate bool RemoteCertificateValidationCallback(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors); // A user delegate used to select local SSL certificate. public delegate X509Certificate LocalCertificateSelectionCallback(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate? remoteCertificate, string[] acceptableIssuers); public delegate X509Certificate ServerCertificateSelectionCallback(object sender, string? hostName); public delegate ValueTask<SslServerAuthenticationOptions> ServerOptionsSelectionCallback(SslStream stream, SslClientHelloInfo clientHelloInfo, object? state, CancellationToken cancellationToken); // Internal versions of the above delegates. internal delegate X509Certificate LocalCertSelectionCallback(string targetHost, X509CertificateCollection localCertificates, X509Certificate2? remoteCertificate, string[] acceptableIssuers); internal delegate X509Certificate ServerCertSelectionCallback(string? hostName); public partial class SslStream : AuthenticatedStream { /// <summary>Set as the _exception when the instance is disposed.</summary> private static readonly ExceptionDispatchInfo s_disposedSentinel = ExceptionDispatchInfo.Capture(new ObjectDisposedException(nameof(SslStream), (string?)null)); internal RemoteCertificateValidationCallback? _userCertificateValidationCallback; internal LocalCertificateSelectionCallback? _userCertificateSelectionCallback; internal ServerCertificateSelectionCallback? _userServerCertificateSelectionCallback; internal LocalCertSelectionCallback? _certSelectionDelegate; internal EncryptionPolicy _encryptionPolicy; private SecureChannel? _context; private ExceptionDispatchInfo? _exception; private bool _shutdown; private bool _handshakeCompleted; // FrameOverhead = 5 byte header + HMAC trailer + padding (if block cipher) // HMAC: 32 bytes for SHA-256 or 20 bytes for SHA-1 or 16 bytes for the MD5 private const int FrameOverhead = 64; private const int InitialHandshakeBufferSize = 4096 + FrameOverhead; // try to fit at least 4K ServerCertificate private const int ReadBufferSize = 4096 * 4 + FrameOverhead; // We read in 16K chunks + headers. private SslBuffer _buffer; // internal buffer for storing incoming data. Wrapper around ArrayBuffer which adds // separation between decrypted and still encrypted part of the active region. // - Encrypted: Contains incoming TLS frames, the last such frame may be incomplete // - Decrypted: Contains decrypted data from *one* TLS frame which have not been read by the user yet. private struct SslBuffer { private ArrayBuffer _buffer; private int _decryptedLength; // padding between decrypted part of the active memory and following undecrypted TLS frame. private int _decryptedPadding; private bool _isValid; public SslBuffer(int initialSize) { _buffer = new ArrayBuffer(initialSize, true); _decryptedLength = 0; _decryptedPadding = 0; _isValid = true; } public bool IsValid => _isValid; public Span<byte> DecryptedSpan => _buffer.ActiveSpan.Slice(0, _decryptedLength); public ReadOnlySpan<byte> DecryptedReadOnlySpanSliced(int length) { Debug.Assert(length <= DecryptedLength, "length <= DecryptedLength"); return _buffer.ActiveSpan.Slice(0, length); } public int DecryptedLength => _decryptedLength; public int ActiveLength => _buffer.ActiveLength; public Span<byte> EncryptedSpanSliced(int length) => _buffer.ActiveSpan.Slice(_decryptedLength + _decryptedPadding, length); public ReadOnlySpan<byte> EncryptedReadOnlySpan => _buffer.ActiveSpan.Slice(_decryptedLength + _decryptedPadding); public int EncryptedLength => _buffer.ActiveLength - _decryptedPadding - _decryptedLength; public Memory<byte> AvailableMemory => _buffer.AvailableMemory; public int AvailableLength => _buffer.AvailableLength; public int Capacity => _buffer.Capacity; public void Commit(int byteCount) => _buffer.Commit(byteCount); public void EnsureAvailableSpace(int byteCount) { if (_isValid) { _buffer.EnsureAvailableSpace(byteCount); } else { _isValid = true; _buffer = new ArrayBuffer(byteCount, true); } } public void Discard(int byteCount) { Debug.Assert(byteCount <= _decryptedLength, "byteCount <= _decryptedBytes"); _buffer.Discard(byteCount); _decryptedLength -= byteCount; // if drained all decrypted data, discard also the tail of the frame so that only // encrypted part of the active memory of the _buffer remains if (_decryptedLength == 0) { _buffer.Discard(_decryptedPadding); _decryptedPadding = 0; } } public void DiscardEncrypted(int byteCount) { // should be called only during handshake -> no pending decrypted data Debug.Assert(_decryptedLength == 0, "_decryptedBytes == 0"); Debug.Assert(_decryptedPadding == 0, "_encryptedOffset == 0"); _buffer.Discard(byteCount); } public void OnDecrypted(int decryptedOffset, int decryptedCount, int frameSize) { Debug.Assert(_decryptedLength == 0, "_decryptedBytes == 0"); Debug.Assert(_decryptedPadding == 0, "_encryptedOffset == 0"); if (decryptedCount > 0) { // discard padding before decrypted contents _buffer.Discard(decryptedOffset); _decryptedPadding = frameSize - decryptedOffset - decryptedCount; _decryptedLength = decryptedCount; } else { // No user data available, discard entire frame _buffer.Discard(frameSize); } } public void ReturnBuffer() { _buffer.Dispose(); _decryptedLength = 0; _decryptedPadding = 0; _isValid = false; } } private int _nestedWrite; private int _nestedRead; public SslStream(Stream innerStream) : this(innerStream, false, null, null) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen) : this(innerStream, leaveInnerStreamOpen, null, null, EncryptionPolicy.RequireEncryption) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback? userCertificateValidationCallback) : this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, null, EncryptionPolicy.RequireEncryption) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback? userCertificateValidationCallback, LocalCertificateSelectionCallback? userCertificateSelectionCallback) : this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback, EncryptionPolicy.RequireEncryption) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback? userCertificateValidationCallback, LocalCertificateSelectionCallback? userCertificateSelectionCallback, EncryptionPolicy encryptionPolicy) : base(innerStream, leaveInnerStreamOpen) { if (encryptionPolicy != EncryptionPolicy.RequireEncryption && encryptionPolicy != EncryptionPolicy.AllowNoEncryption && encryptionPolicy != EncryptionPolicy.NoEncryption) { throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), nameof(encryptionPolicy)); } _userCertificateValidationCallback = userCertificateValidationCallback; _userCertificateSelectionCallback = userCertificateSelectionCallback; _encryptionPolicy = encryptionPolicy; _certSelectionDelegate = userCertificateSelectionCallback == null ? null : new LocalCertSelectionCallback(UserCertSelectionCallbackWrapper); if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.SslStreamCtor(this, innerStream); } public SslApplicationProtocol NegotiatedApplicationProtocol { get { if (_context == null) return default; return _context.NegotiatedApplicationProtocol; } } private void SetAndVerifyValidationCallback(RemoteCertificateValidationCallback? callback) { if (_userCertificateValidationCallback == null) { _userCertificateValidationCallback = callback; } else if (callback != null && _userCertificateValidationCallback != callback) { throw new InvalidOperationException(SR.Format(SR.net_conflicting_options, nameof(RemoteCertificateValidationCallback))); } } private void SetAndVerifySelectionCallback(LocalCertificateSelectionCallback? callback) { if (_userCertificateSelectionCallback == null) { _userCertificateSelectionCallback = callback; _certSelectionDelegate = _userCertificateSelectionCallback == null ? null : new LocalCertSelectionCallback(UserCertSelectionCallbackWrapper); } else if (callback != null && _userCertificateSelectionCallback != callback) { throw new InvalidOperationException(SR.Format(SR.net_conflicting_options, nameof(LocalCertificateSelectionCallback))); } } private X509Certificate UserCertSelectionCallbackWrapper(string targetHost, X509CertificateCollection localCertificates, X509Certificate? remoteCertificate, string[] acceptableIssuers) { return _userCertificateSelectionCallback!(this, targetHost, localCertificates, remoteCertificate, acceptableIssuers); } private X509Certificate ServerCertSelectionCallbackWrapper(string? targetHost) => _userServerCertificateSelectionCallback!(this, targetHost); private SslAuthenticationOptions CreateAuthenticationOptions(SslServerAuthenticationOptions sslServerAuthenticationOptions) { if (sslServerAuthenticationOptions.ServerCertificate == null && sslServerAuthenticationOptions.ServerCertificateContext == null && sslServerAuthenticationOptions.ServerCertificateSelectionCallback == null && _certSelectionDelegate == null) { throw new ArgumentNullException(nameof(sslServerAuthenticationOptions.ServerCertificate)); } if ((sslServerAuthenticationOptions.ServerCertificate != null || sslServerAuthenticationOptions.ServerCertificateContext != null || _certSelectionDelegate != null) && sslServerAuthenticationOptions.ServerCertificateSelectionCallback != null) { throw new InvalidOperationException(SR.Format(SR.net_conflicting_options, nameof(ServerCertificateSelectionCallback))); } var authOptions = new SslAuthenticationOptions(sslServerAuthenticationOptions); _userServerCertificateSelectionCallback = sslServerAuthenticationOptions.ServerCertificateSelectionCallback; authOptions.ServerCertSelectionDelegate = _userServerCertificateSelectionCallback == null ? null : new ServerCertSelectionCallback(ServerCertSelectionCallbackWrapper); authOptions.CertValidationDelegate = _userCertificateValidationCallback; authOptions.CertSelectionDelegate = _certSelectionDelegate; return authOptions; } // // Client side auth. // public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsClient(targetHost, null, SecurityProtocol.SystemDefaultSecurityProtocols, false, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection? clientCertificates, bool checkCertificateRevocation, AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsClient(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection? clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback? asyncCallback, object? asyncState) { SslClientAuthenticationOptions options = new SslClientAuthenticationOptions { TargetHost = targetHost, ClientCertificates = clientCertificates, EnabledSslProtocols = enabledSslProtocols, CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, EncryptionPolicy = _encryptionPolicy, }; return BeginAuthenticateAsClient(options, CancellationToken.None, asyncCallback, asyncState); } internal IAsyncResult BeginAuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback? asyncCallback, object? asyncState) => TaskToApm.Begin(AuthenticateAsClientApm(sslClientAuthenticationOptions, cancellationToken)!, asyncCallback, asyncState); public virtual void EndAuthenticateAsClient(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); // // Server side auth. // public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsServer(serverCertificate, false, SecurityProtocol.SystemDefaultSecurityProtocols, false, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback? asyncCallback, object? asyncState) { SslServerAuthenticationOptions options = new SslServerAuthenticationOptions { ServerCertificate = serverCertificate, ClientCertificateRequired = clientCertificateRequired, EnabledSslProtocols = enabledSslProtocols, CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, EncryptionPolicy = _encryptionPolicy, }; return BeginAuthenticateAsServer(options, CancellationToken.None, asyncCallback, asyncState); } private IAsyncResult BeginAuthenticateAsServer(SslServerAuthenticationOptions sslServerAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback? asyncCallback, object? asyncState) => TaskToApm.Begin(AuthenticateAsServerApm(sslServerAuthenticationOptions, cancellationToken)!, asyncCallback, asyncState); public virtual void EndAuthenticateAsServer(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); internal IAsyncResult BeginShutdown(AsyncCallback? asyncCallback, object? asyncState) => TaskToApm.Begin(ShutdownAsync(), asyncCallback, asyncState); internal void EndShutdown(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); public TransportContext TransportContext => new SslStreamContext(this); internal ChannelBinding? GetChannelBinding(ChannelBindingKind kind) => _context?.GetChannelBinding(kind); #region Synchronous methods public virtual void AuthenticateAsClient(string targetHost) { AuthenticateAsClient(targetHost, null, SecurityProtocol.SystemDefaultSecurityProtocols, false); } public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection? clientCertificates, bool checkCertificateRevocation) { AuthenticateAsClient(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation); } public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection? clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SslClientAuthenticationOptions options = new SslClientAuthenticationOptions { TargetHost = targetHost, ClientCertificates = clientCertificates, EnabledSslProtocols = enabledSslProtocols, CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, EncryptionPolicy = _encryptionPolicy, }; AuthenticateAsClient(options); } public void AuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions!!) { SetAndVerifyValidationCallback(sslClientAuthenticationOptions.RemoteCertificateValidationCallback); SetAndVerifySelectionCallback(sslClientAuthenticationOptions.LocalCertificateSelectionCallback); ValidateCreateContext(sslClientAuthenticationOptions, _userCertificateValidationCallback, _certSelectionDelegate); ProcessAuthenticationAsync().GetAwaiter().GetResult(); } public virtual void AuthenticateAsServer(X509Certificate serverCertificate) { AuthenticateAsServer(serverCertificate, false, SecurityProtocol.SystemDefaultSecurityProtocols, false); } public virtual void AuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) { AuthenticateAsServer(serverCertificate, clientCertificateRequired, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation); } public virtual void AuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SslServerAuthenticationOptions options = new SslServerAuthenticationOptions { ServerCertificate = serverCertificate, ClientCertificateRequired = clientCertificateRequired, EnabledSslProtocols = enabledSslProtocols, CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, EncryptionPolicy = _encryptionPolicy, }; AuthenticateAsServer(options); } public void AuthenticateAsServer(SslServerAuthenticationOptions sslServerAuthenticationOptions!!) { SetAndVerifyValidationCallback(sslServerAuthenticationOptions.RemoteCertificateValidationCallback); ValidateCreateContext(CreateAuthenticationOptions(sslServerAuthenticationOptions)); ProcessAuthenticationAsync().GetAwaiter().GetResult(); } #endregion #region Task-based async public methods public virtual Task AuthenticateAsClientAsync(string targetHost) => AuthenticateAsClientAsync(targetHost, null, false); public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection? clientCertificates, bool checkCertificateRevocation) => AuthenticateAsClientAsync(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation); public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection? clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SslClientAuthenticationOptions options = new SslClientAuthenticationOptions() { TargetHost = targetHost, ClientCertificates = clientCertificates, EnabledSslProtocols = enabledSslProtocols, CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, EncryptionPolicy = _encryptionPolicy, }; return AuthenticateAsClientAsync(options); } public Task AuthenticateAsClientAsync(SslClientAuthenticationOptions sslClientAuthenticationOptions!!, CancellationToken cancellationToken = default) { SetAndVerifyValidationCallback(sslClientAuthenticationOptions.RemoteCertificateValidationCallback); SetAndVerifySelectionCallback(sslClientAuthenticationOptions.LocalCertificateSelectionCallback); ValidateCreateContext(sslClientAuthenticationOptions, _userCertificateValidationCallback, _certSelectionDelegate); return ProcessAuthenticationAsync(isAsync: true, cancellationToken); } private Task AuthenticateAsClientApm(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken = default) { SetAndVerifyValidationCallback(sslClientAuthenticationOptions.RemoteCertificateValidationCallback); SetAndVerifySelectionCallback(sslClientAuthenticationOptions.LocalCertificateSelectionCallback); ValidateCreateContext(sslClientAuthenticationOptions, _userCertificateValidationCallback, _certSelectionDelegate); return ProcessAuthenticationAsync(isAsync: true, cancellationToken); } public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate) => AuthenticateAsServerAsync(serverCertificate, false, SecurityProtocol.SystemDefaultSecurityProtocols, false); public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) { SslServerAuthenticationOptions options = new SslServerAuthenticationOptions { ServerCertificate = serverCertificate, ClientCertificateRequired = clientCertificateRequired, CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, EncryptionPolicy = _encryptionPolicy, }; return AuthenticateAsServerAsync(options); } public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SslServerAuthenticationOptions options = new SslServerAuthenticationOptions { ServerCertificate = serverCertificate, ClientCertificateRequired = clientCertificateRequired, EnabledSslProtocols = enabledSslProtocols, CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, EncryptionPolicy = _encryptionPolicy, }; return AuthenticateAsServerAsync(options); } public Task AuthenticateAsServerAsync(SslServerAuthenticationOptions sslServerAuthenticationOptions!!, CancellationToken cancellationToken = default) { SetAndVerifyValidationCallback(sslServerAuthenticationOptions.RemoteCertificateValidationCallback); ValidateCreateContext(CreateAuthenticationOptions(sslServerAuthenticationOptions)); return ProcessAuthenticationAsync(isAsync: true, cancellationToken); } private Task AuthenticateAsServerApm(SslServerAuthenticationOptions sslServerAuthenticationOptions, CancellationToken cancellationToken = default) { SetAndVerifyValidationCallback(sslServerAuthenticationOptions.RemoteCertificateValidationCallback); ValidateCreateContext(CreateAuthenticationOptions(sslServerAuthenticationOptions)); return ProcessAuthenticationAsync(isAsync: true, cancellationToken); } public Task AuthenticateAsServerAsync(ServerOptionsSelectionCallback optionsCallback, object? state, CancellationToken cancellationToken = default) { ValidateCreateContext(new SslAuthenticationOptions(optionsCallback, state, _userCertificateValidationCallback)); return ProcessAuthenticationAsync(isAsync: true, cancellationToken); } public virtual Task ShutdownAsync() { ThrowIfExceptionalOrNotAuthenticatedOrShutdown(); ProtocolToken message = _context!.CreateShutdownToken()!; _shutdown = true; return InnerStream.WriteAsync(message.Payload, default).AsTask(); } #endregion public override bool IsAuthenticated => _context != null && _context.IsValidContext && _exception == null && _handshakeCompleted; public override bool IsMutuallyAuthenticated { get { return IsAuthenticated && (_context!.IsServer ? _context.LocalServerCertificate : _context.LocalClientCertificate) != null && _context.IsRemoteCertificateAvailable; /* does not work: Context.IsMutualAuthFlag;*/ } } public override bool IsEncrypted => IsAuthenticated; public override bool IsSigned => IsAuthenticated; public override bool IsServer => _context != null && _context.IsServer; public virtual SslProtocols SslProtocol { get { ThrowIfExceptionalOrNotHandshake(); return GetSslProtocolInternal(); } } // Skips the ThrowIfExceptionalOrNotHandshake() check private SslProtocols GetSslProtocolInternal() { SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return SslProtocols.None; } SslProtocols proto = (SslProtocols)info.Protocol; SslProtocols ret = SslProtocols.None; #pragma warning disable 0618 // Ssl2, Ssl3 are deprecated. // Restore client/server bits so the result maps exactly on published constants. if ((proto & SslProtocols.Ssl2) != 0) { ret |= SslProtocols.Ssl2; } if ((proto & SslProtocols.Ssl3) != 0) { ret |= SslProtocols.Ssl3; } #pragma warning restore #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete if ((proto & SslProtocols.Tls) != 0) { ret |= SslProtocols.Tls; } if ((proto & SslProtocols.Tls11) != 0) { ret |= SslProtocols.Tls11; } #pragma warning restore SYSLIB0039 if ((proto & SslProtocols.Tls12) != 0) { ret |= SslProtocols.Tls12; } if ((proto & SslProtocols.Tls13) != 0) { ret |= SslProtocols.Tls13; } return ret; } public virtual bool CheckCertRevocationStatus => _context != null && _context.CheckCertRevocationStatus != X509RevocationMode.NoCheck; // // This will return selected local cert for both client/server streams // public virtual X509Certificate? LocalCertificate { get { ThrowIfExceptionalOrNotAuthenticated(); return _context!.IsServer ? _context.LocalServerCertificate : _context.LocalClientCertificate; } } public virtual X509Certificate? RemoteCertificate { get { ThrowIfExceptionalOrNotAuthenticated(); return _context?.RemoteCertificate; } } [CLSCompliant(false)] public virtual TlsCipherSuite NegotiatedCipherSuite { get { ThrowIfExceptionalOrNotHandshake(); return _context!.ConnectionInfo?.TlsCipherSuite ?? default(TlsCipherSuite); } } public virtual CipherAlgorithmType CipherAlgorithm { get { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return CipherAlgorithmType.None; } return (CipherAlgorithmType)info.DataCipherAlg; } } public virtual int CipherStrength { get { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return 0; } return info.DataKeySize; } } public virtual HashAlgorithmType HashAlgorithm { get { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return (HashAlgorithmType)0; } return (HashAlgorithmType)info.DataHashAlg; } } public virtual int HashStrength { get { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return 0; } return info.DataHashKeySize; } } public virtual ExchangeAlgorithmType KeyExchangeAlgorithm { get { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return (ExchangeAlgorithmType)0; } return (ExchangeAlgorithmType)info.KeyExchangeAlg; } } public virtual int KeyExchangeStrength { get { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return 0; } return info.KeyExchKeySize; } } public string TargetHostName { get { return _sslAuthenticationOptions != null ? _sslAuthenticationOptions.TargetHost : string.Empty; } } // // Stream contract implementation. // public override bool CanSeek => false; public override bool CanRead => IsAuthenticated && InnerStream.CanRead; public override bool CanTimeout => InnerStream.CanTimeout; public override bool CanWrite => IsAuthenticated && InnerStream.CanWrite && !_shutdown; public override int ReadTimeout { get => InnerStream.ReadTimeout; set => InnerStream.ReadTimeout = value; } public override int WriteTimeout { get => InnerStream.WriteTimeout; set => InnerStream.WriteTimeout = value; } public override long Length => InnerStream.Length; public override long Position { get => InnerStream.Position; set => throw new NotSupportedException(SR.net_noseek); } public override void SetLength(long value) => InnerStream.SetLength(value); public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(SR.net_noseek); public override void Flush() => InnerStream.Flush(); public override Task FlushAsync(CancellationToken cancellationToken) => InnerStream.FlushAsync(cancellationToken); public virtual Task NegotiateClientCertificateAsync(CancellationToken cancellationToken = default) { ThrowIfExceptionalOrNotAuthenticated(); if (RemoteCertificate != null) { throw new InvalidOperationException(SR.net_ssl_certificate_exist); } return RenegotiateAsync<AsyncReadWriteAdapter>(cancellationToken); } protected override void Dispose(bool disposing) { try { CloseInternal(); } finally { base.Dispose(disposing); } } public override async ValueTask DisposeAsync() { try { CloseInternal(); } finally { await base.DisposeAsync().ConfigureAwait(false); } } public override int ReadByte() { ThrowIfExceptionalOrNotAuthenticated(); if (Interlocked.Exchange(ref _nestedRead, 1) == 1) { throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "read")); } // If there's any data in the buffer, take one byte, and we're done. try { if (_buffer.DecryptedLength > 0) { int b = _buffer.DecryptedSpan[0]; _buffer.Discard(1); ReturnReadBufferIfEmpty(); return b; } } finally { // Regardless of whether we were able to read a byte from the buffer, // reset the read tracking. If we weren't able to read a byte, the // subsequent call to Read will set the flag again. _nestedRead = 0; } // Otherwise, fall back to reading a byte via Read, the same way Stream.ReadByte does. // This allocation is unfortunate but should be relatively rare, as it'll only occur once // per buffer fill internally by Read. byte[] oneByte = new byte[1]; int bytesRead = Read(oneByte, 0, 1); Debug.Assert(bytesRead == 0 || bytesRead == 1); return bytesRead == 1 ? oneByte[0] : -1; } public override int Read(byte[] buffer, int offset, int count) { ThrowIfExceptionalOrNotAuthenticated(); ValidateBufferArguments(buffer, offset, count); ValueTask<int> vt = ReadAsyncInternal<SyncReadWriteAdapter>(new Memory<byte>(buffer, offset, count), default(CancellationToken)); Debug.Assert(vt.IsCompleted, "Sync operation must have completed synchronously"); return vt.GetAwaiter().GetResult(); } public void Write(byte[] buffer) => Write(buffer, 0, buffer.Length); public override void Write(byte[] buffer, int offset, int count) { ThrowIfExceptionalOrNotAuthenticated(); ValidateBufferArguments(buffer, offset, count); ValueTask vt = WriteAsyncInternal<SyncReadWriteAdapter>(new ReadOnlyMemory<byte>(buffer, offset, count), default(CancellationToken)); Debug.Assert(vt.IsCompleted, "Sync operation must have completed synchronously"); vt.GetAwaiter().GetResult(); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) { ThrowIfExceptionalOrNotAuthenticated(); return TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); } public override int EndRead(IAsyncResult asyncResult) { ThrowIfExceptionalOrNotAuthenticated(); return TaskToApm.End<int>(asyncResult); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) { ThrowIfExceptionalOrNotAuthenticated(); return TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); } public override void EndWrite(IAsyncResult asyncResult) { ThrowIfExceptionalOrNotAuthenticated(); TaskToApm.End(asyncResult); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { ThrowIfExceptionalOrNotAuthenticated(); ValidateBufferArguments(buffer, offset, count); return WriteAsyncInternal<AsyncReadWriteAdapter>(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken).AsTask(); } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) { ThrowIfExceptionalOrNotAuthenticated(); return WriteAsyncInternal<AsyncReadWriteAdapter>(buffer, cancellationToken); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { ThrowIfExceptionalOrNotAuthenticated(); ValidateBufferArguments(buffer, offset, count); return ReadAsyncInternal<AsyncReadWriteAdapter>(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask(); } public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) { ThrowIfExceptionalOrNotAuthenticated(); return ReadAsyncInternal<AsyncReadWriteAdapter>(buffer, cancellationToken); } private void ThrowIfExceptional() { ExceptionDispatchInfo? e = _exception; if (e != null) { ThrowExceptional(e); } // Local function to make the check method more inline friendly. static void ThrowExceptional(ExceptionDispatchInfo e) { // If the stored exception just indicates disposal, throw a new ODE rather than the stored one, // so as to not continually build onto the shared exception's stack. if (ReferenceEquals(e, s_disposedSentinel)) { throw new ObjectDisposedException(nameof(SslStream)); } // Throw the stored exception. e.Throw(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ThrowIfExceptionalOrNotAuthenticated() { ThrowIfExceptional(); if (!IsAuthenticated) { ThrowNotAuthenticated(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ThrowIfExceptionalOrNotHandshake() { ThrowIfExceptional(); if (!IsAuthenticated && _context?.ConnectionInfo == null) { ThrowNotAuthenticated(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ThrowIfExceptionalOrNotAuthenticatedOrShutdown() { ThrowIfExceptional(); if (!IsAuthenticated) { ThrowNotAuthenticated(); } if (_shutdown) { ThrowAlreadyShutdown(); } // Local function to make the check method more inline friendly. static void ThrowAlreadyShutdown() { throw new InvalidOperationException(SR.net_ssl_io_already_shutdown); } } // Static non-returning throw method to make the check methods more inline friendly. private static void ThrowNotAuthenticated() { throw new InvalidOperationException(SR.net_auth_noauth); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace System.Net.Security { public enum EncryptionPolicy { // Prohibit null ciphers (current system defaults) RequireEncryption = 0, // Add null ciphers to current system defaults [System.ObsoleteAttribute(Obsoletions.EncryptionPolicyMessage, DiagnosticId = Obsoletions.EncryptionPolicyDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] AllowNoEncryption, // Request null ciphers only [System.ObsoleteAttribute(Obsoletions.EncryptionPolicyMessage, DiagnosticId = Obsoletions.EncryptionPolicyDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] NoEncryption } // A user delegate used to verify remote SSL certificate. public delegate bool RemoteCertificateValidationCallback(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors); // A user delegate used to select local SSL certificate. public delegate X509Certificate LocalCertificateSelectionCallback(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate? remoteCertificate, string[] acceptableIssuers); public delegate X509Certificate ServerCertificateSelectionCallback(object sender, string? hostName); public delegate ValueTask<SslServerAuthenticationOptions> ServerOptionsSelectionCallback(SslStream stream, SslClientHelloInfo clientHelloInfo, object? state, CancellationToken cancellationToken); // Internal versions of the above delegates. internal delegate X509Certificate LocalCertSelectionCallback(string targetHost, X509CertificateCollection localCertificates, X509Certificate2? remoteCertificate, string[] acceptableIssuers); internal delegate X509Certificate ServerCertSelectionCallback(string? hostName); public partial class SslStream : AuthenticatedStream { /// <summary>Set as the _exception when the instance is disposed.</summary> private static readonly ExceptionDispatchInfo s_disposedSentinel = ExceptionDispatchInfo.Capture(new ObjectDisposedException(nameof(SslStream), (string?)null)); internal RemoteCertificateValidationCallback? _userCertificateValidationCallback; internal LocalCertificateSelectionCallback? _userCertificateSelectionCallback; internal ServerCertificateSelectionCallback? _userServerCertificateSelectionCallback; internal LocalCertSelectionCallback? _certSelectionDelegate; internal EncryptionPolicy _encryptionPolicy; private SecureChannel? _context; private ExceptionDispatchInfo? _exception; private bool _shutdown; private bool _handshakeCompleted; // FrameOverhead = 5 byte header + HMAC trailer + padding (if block cipher) // HMAC: 32 bytes for SHA-256 or 20 bytes for SHA-1 or 16 bytes for the MD5 private const int FrameOverhead = 64; private const int InitialHandshakeBufferSize = 4096 + FrameOverhead; // try to fit at least 4K ServerCertificate private const int ReadBufferSize = 4096 * 4 + FrameOverhead; // We read in 16K chunks + headers. private SslBuffer _buffer; // internal buffer for storing incoming data. Wrapper around ArrayBuffer which adds // separation between decrypted and still encrypted part of the active region. // - Encrypted: Contains incoming TLS frames, the last such frame may be incomplete // - Decrypted: Contains decrypted data from *one* TLS frame which have not been read by the user yet. private struct SslBuffer { private ArrayBuffer _buffer; private int _decryptedLength; // padding between decrypted part of the active memory and following undecrypted TLS frame. private int _decryptedPadding; private bool _isValid; public SslBuffer(int initialSize) { _buffer = new ArrayBuffer(initialSize, true); _decryptedLength = 0; _decryptedPadding = 0; _isValid = true; } public bool IsValid => _isValid; public Span<byte> DecryptedSpan => _buffer.ActiveSpan.Slice(0, _decryptedLength); public ReadOnlySpan<byte> DecryptedReadOnlySpanSliced(int length) { Debug.Assert(length <= DecryptedLength, "length <= DecryptedLength"); return _buffer.ActiveSpan.Slice(0, length); } public int DecryptedLength => _decryptedLength; public int ActiveLength => _buffer.ActiveLength; public Span<byte> EncryptedSpanSliced(int length) => _buffer.ActiveSpan.Slice(_decryptedLength + _decryptedPadding, length); public ReadOnlySpan<byte> EncryptedReadOnlySpan => _buffer.ActiveSpan.Slice(_decryptedLength + _decryptedPadding); public int EncryptedLength => _buffer.ActiveLength - _decryptedPadding - _decryptedLength; public Memory<byte> AvailableMemory => _buffer.AvailableMemory; public int AvailableLength => _buffer.AvailableLength; public int Capacity => _buffer.Capacity; public void Commit(int byteCount) => _buffer.Commit(byteCount); public void EnsureAvailableSpace(int byteCount) { if (_isValid) { _buffer.EnsureAvailableSpace(byteCount); } else { _isValid = true; _buffer = new ArrayBuffer(byteCount, true); } } public void Discard(int byteCount) { Debug.Assert(byteCount <= _decryptedLength, "byteCount <= _decryptedBytes"); _buffer.Discard(byteCount); _decryptedLength -= byteCount; // if drained all decrypted data, discard also the tail of the frame so that only // encrypted part of the active memory of the _buffer remains if (_decryptedLength == 0) { _buffer.Discard(_decryptedPadding); _decryptedPadding = 0; } } public void DiscardEncrypted(int byteCount) { // should be called only during handshake -> no pending decrypted data Debug.Assert(_decryptedLength == 0, "_decryptedBytes == 0"); Debug.Assert(_decryptedPadding == 0, "_encryptedOffset == 0"); _buffer.Discard(byteCount); } public void OnDecrypted(int decryptedOffset, int decryptedCount, int frameSize) { Debug.Assert(_decryptedLength == 0, "_decryptedBytes == 0"); Debug.Assert(_decryptedPadding == 0, "_encryptedOffset == 0"); if (decryptedCount > 0) { // discard padding before decrypted contents _buffer.Discard(decryptedOffset); _decryptedPadding = frameSize - decryptedOffset - decryptedCount; _decryptedLength = decryptedCount; } else { // No user data available, discard entire frame _buffer.Discard(frameSize); } } public void ReturnBuffer() { _buffer.Dispose(); _decryptedLength = 0; _decryptedPadding = 0; _isValid = false; } } private int _nestedWrite; private int _nestedRead; public SslStream(Stream innerStream) : this(innerStream, false, null, null) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen) : this(innerStream, leaveInnerStreamOpen, null, null, EncryptionPolicy.RequireEncryption) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback? userCertificateValidationCallback) : this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, null, EncryptionPolicy.RequireEncryption) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback? userCertificateValidationCallback, LocalCertificateSelectionCallback? userCertificateSelectionCallback) : this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback, EncryptionPolicy.RequireEncryption) { } public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback? userCertificateValidationCallback, LocalCertificateSelectionCallback? userCertificateSelectionCallback, EncryptionPolicy encryptionPolicy) : base(innerStream, leaveInnerStreamOpen) { #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete if (encryptionPolicy != EncryptionPolicy.RequireEncryption && encryptionPolicy != EncryptionPolicy.AllowNoEncryption && encryptionPolicy != EncryptionPolicy.NoEncryption) { throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), nameof(encryptionPolicy)); } #pragma warning restore SYSLIB0040 _userCertificateValidationCallback = userCertificateValidationCallback; _userCertificateSelectionCallback = userCertificateSelectionCallback; _encryptionPolicy = encryptionPolicy; _certSelectionDelegate = userCertificateSelectionCallback == null ? null : new LocalCertSelectionCallback(UserCertSelectionCallbackWrapper); if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.SslStreamCtor(this, innerStream); } public SslApplicationProtocol NegotiatedApplicationProtocol { get { if (_context == null) return default; return _context.NegotiatedApplicationProtocol; } } private void SetAndVerifyValidationCallback(RemoteCertificateValidationCallback? callback) { if (_userCertificateValidationCallback == null) { _userCertificateValidationCallback = callback; } else if (callback != null && _userCertificateValidationCallback != callback) { throw new InvalidOperationException(SR.Format(SR.net_conflicting_options, nameof(RemoteCertificateValidationCallback))); } } private void SetAndVerifySelectionCallback(LocalCertificateSelectionCallback? callback) { if (_userCertificateSelectionCallback == null) { _userCertificateSelectionCallback = callback; _certSelectionDelegate = _userCertificateSelectionCallback == null ? null : new LocalCertSelectionCallback(UserCertSelectionCallbackWrapper); } else if (callback != null && _userCertificateSelectionCallback != callback) { throw new InvalidOperationException(SR.Format(SR.net_conflicting_options, nameof(LocalCertificateSelectionCallback))); } } private X509Certificate UserCertSelectionCallbackWrapper(string targetHost, X509CertificateCollection localCertificates, X509Certificate? remoteCertificate, string[] acceptableIssuers) { return _userCertificateSelectionCallback!(this, targetHost, localCertificates, remoteCertificate, acceptableIssuers); } private X509Certificate ServerCertSelectionCallbackWrapper(string? targetHost) => _userServerCertificateSelectionCallback!(this, targetHost); private SslAuthenticationOptions CreateAuthenticationOptions(SslServerAuthenticationOptions sslServerAuthenticationOptions) { if (sslServerAuthenticationOptions.ServerCertificate == null && sslServerAuthenticationOptions.ServerCertificateContext == null && sslServerAuthenticationOptions.ServerCertificateSelectionCallback == null && _certSelectionDelegate == null) { throw new ArgumentNullException(nameof(sslServerAuthenticationOptions.ServerCertificate)); } if ((sslServerAuthenticationOptions.ServerCertificate != null || sslServerAuthenticationOptions.ServerCertificateContext != null || _certSelectionDelegate != null) && sslServerAuthenticationOptions.ServerCertificateSelectionCallback != null) { throw new InvalidOperationException(SR.Format(SR.net_conflicting_options, nameof(ServerCertificateSelectionCallback))); } var authOptions = new SslAuthenticationOptions(sslServerAuthenticationOptions); _userServerCertificateSelectionCallback = sslServerAuthenticationOptions.ServerCertificateSelectionCallback; authOptions.ServerCertSelectionDelegate = _userServerCertificateSelectionCallback == null ? null : new ServerCertSelectionCallback(ServerCertSelectionCallbackWrapper); authOptions.CertValidationDelegate = _userCertificateValidationCallback; authOptions.CertSelectionDelegate = _certSelectionDelegate; return authOptions; } // // Client side auth. // public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsClient(targetHost, null, SecurityProtocol.SystemDefaultSecurityProtocols, false, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection? clientCertificates, bool checkCertificateRevocation, AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsClient(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection? clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback? asyncCallback, object? asyncState) { SslClientAuthenticationOptions options = new SslClientAuthenticationOptions { TargetHost = targetHost, ClientCertificates = clientCertificates, EnabledSslProtocols = enabledSslProtocols, CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, EncryptionPolicy = _encryptionPolicy, }; return BeginAuthenticateAsClient(options, CancellationToken.None, asyncCallback, asyncState); } internal IAsyncResult BeginAuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback? asyncCallback, object? asyncState) => TaskToApm.Begin(AuthenticateAsClientApm(sslClientAuthenticationOptions, cancellationToken)!, asyncCallback, asyncState); public virtual void EndAuthenticateAsClient(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); // // Server side auth. // public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsServer(serverCertificate, false, SecurityProtocol.SystemDefaultSecurityProtocols, false, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, AsyncCallback? asyncCallback, object? asyncState) { return BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback? asyncCallback, object? asyncState) { SslServerAuthenticationOptions options = new SslServerAuthenticationOptions { ServerCertificate = serverCertificate, ClientCertificateRequired = clientCertificateRequired, EnabledSslProtocols = enabledSslProtocols, CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, EncryptionPolicy = _encryptionPolicy, }; return BeginAuthenticateAsServer(options, CancellationToken.None, asyncCallback, asyncState); } private IAsyncResult BeginAuthenticateAsServer(SslServerAuthenticationOptions sslServerAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback? asyncCallback, object? asyncState) => TaskToApm.Begin(AuthenticateAsServerApm(sslServerAuthenticationOptions, cancellationToken)!, asyncCallback, asyncState); public virtual void EndAuthenticateAsServer(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); internal IAsyncResult BeginShutdown(AsyncCallback? asyncCallback, object? asyncState) => TaskToApm.Begin(ShutdownAsync(), asyncCallback, asyncState); internal void EndShutdown(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); public TransportContext TransportContext => new SslStreamContext(this); internal ChannelBinding? GetChannelBinding(ChannelBindingKind kind) => _context?.GetChannelBinding(kind); #region Synchronous methods public virtual void AuthenticateAsClient(string targetHost) { AuthenticateAsClient(targetHost, null, SecurityProtocol.SystemDefaultSecurityProtocols, false); } public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection? clientCertificates, bool checkCertificateRevocation) { AuthenticateAsClient(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation); } public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection? clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SslClientAuthenticationOptions options = new SslClientAuthenticationOptions { TargetHost = targetHost, ClientCertificates = clientCertificates, EnabledSslProtocols = enabledSslProtocols, CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, EncryptionPolicy = _encryptionPolicy, }; AuthenticateAsClient(options); } public void AuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions!!) { SetAndVerifyValidationCallback(sslClientAuthenticationOptions.RemoteCertificateValidationCallback); SetAndVerifySelectionCallback(sslClientAuthenticationOptions.LocalCertificateSelectionCallback); ValidateCreateContext(sslClientAuthenticationOptions, _userCertificateValidationCallback, _certSelectionDelegate); ProcessAuthenticationAsync().GetAwaiter().GetResult(); } public virtual void AuthenticateAsServer(X509Certificate serverCertificate) { AuthenticateAsServer(serverCertificate, false, SecurityProtocol.SystemDefaultSecurityProtocols, false); } public virtual void AuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) { AuthenticateAsServer(serverCertificate, clientCertificateRequired, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation); } public virtual void AuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SslServerAuthenticationOptions options = new SslServerAuthenticationOptions { ServerCertificate = serverCertificate, ClientCertificateRequired = clientCertificateRequired, EnabledSslProtocols = enabledSslProtocols, CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, EncryptionPolicy = _encryptionPolicy, }; AuthenticateAsServer(options); } public void AuthenticateAsServer(SslServerAuthenticationOptions sslServerAuthenticationOptions!!) { SetAndVerifyValidationCallback(sslServerAuthenticationOptions.RemoteCertificateValidationCallback); ValidateCreateContext(CreateAuthenticationOptions(sslServerAuthenticationOptions)); ProcessAuthenticationAsync().GetAwaiter().GetResult(); } #endregion #region Task-based async public methods public virtual Task AuthenticateAsClientAsync(string targetHost) => AuthenticateAsClientAsync(targetHost, null, false); public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection? clientCertificates, bool checkCertificateRevocation) => AuthenticateAsClientAsync(targetHost, clientCertificates, SecurityProtocol.SystemDefaultSecurityProtocols, checkCertificateRevocation); public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection? clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SslClientAuthenticationOptions options = new SslClientAuthenticationOptions() { TargetHost = targetHost, ClientCertificates = clientCertificates, EnabledSslProtocols = enabledSslProtocols, CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, EncryptionPolicy = _encryptionPolicy, }; return AuthenticateAsClientAsync(options); } public Task AuthenticateAsClientAsync(SslClientAuthenticationOptions sslClientAuthenticationOptions!!, CancellationToken cancellationToken = default) { SetAndVerifyValidationCallback(sslClientAuthenticationOptions.RemoteCertificateValidationCallback); SetAndVerifySelectionCallback(sslClientAuthenticationOptions.LocalCertificateSelectionCallback); ValidateCreateContext(sslClientAuthenticationOptions, _userCertificateValidationCallback, _certSelectionDelegate); return ProcessAuthenticationAsync(isAsync: true, cancellationToken); } private Task AuthenticateAsClientApm(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken = default) { SetAndVerifyValidationCallback(sslClientAuthenticationOptions.RemoteCertificateValidationCallback); SetAndVerifySelectionCallback(sslClientAuthenticationOptions.LocalCertificateSelectionCallback); ValidateCreateContext(sslClientAuthenticationOptions, _userCertificateValidationCallback, _certSelectionDelegate); return ProcessAuthenticationAsync(isAsync: true, cancellationToken); } public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate) => AuthenticateAsServerAsync(serverCertificate, false, SecurityProtocol.SystemDefaultSecurityProtocols, false); public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation) { SslServerAuthenticationOptions options = new SslServerAuthenticationOptions { ServerCertificate = serverCertificate, ClientCertificateRequired = clientCertificateRequired, CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, EncryptionPolicy = _encryptionPolicy, }; return AuthenticateAsServerAsync(options); } public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation) { SslServerAuthenticationOptions options = new SslServerAuthenticationOptions { ServerCertificate = serverCertificate, ClientCertificateRequired = clientCertificateRequired, EnabledSslProtocols = enabledSslProtocols, CertificateRevocationCheckMode = checkCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, EncryptionPolicy = _encryptionPolicy, }; return AuthenticateAsServerAsync(options); } public Task AuthenticateAsServerAsync(SslServerAuthenticationOptions sslServerAuthenticationOptions!!, CancellationToken cancellationToken = default) { SetAndVerifyValidationCallback(sslServerAuthenticationOptions.RemoteCertificateValidationCallback); ValidateCreateContext(CreateAuthenticationOptions(sslServerAuthenticationOptions)); return ProcessAuthenticationAsync(isAsync: true, cancellationToken); } private Task AuthenticateAsServerApm(SslServerAuthenticationOptions sslServerAuthenticationOptions, CancellationToken cancellationToken = default) { SetAndVerifyValidationCallback(sslServerAuthenticationOptions.RemoteCertificateValidationCallback); ValidateCreateContext(CreateAuthenticationOptions(sslServerAuthenticationOptions)); return ProcessAuthenticationAsync(isAsync: true, cancellationToken); } public Task AuthenticateAsServerAsync(ServerOptionsSelectionCallback optionsCallback, object? state, CancellationToken cancellationToken = default) { ValidateCreateContext(new SslAuthenticationOptions(optionsCallback, state, _userCertificateValidationCallback)); return ProcessAuthenticationAsync(isAsync: true, cancellationToken); } public virtual Task ShutdownAsync() { ThrowIfExceptionalOrNotAuthenticatedOrShutdown(); ProtocolToken message = _context!.CreateShutdownToken()!; _shutdown = true; return InnerStream.WriteAsync(message.Payload, default).AsTask(); } #endregion public override bool IsAuthenticated => _context != null && _context.IsValidContext && _exception == null && _handshakeCompleted; public override bool IsMutuallyAuthenticated { get { return IsAuthenticated && (_context!.IsServer ? _context.LocalServerCertificate : _context.LocalClientCertificate) != null && _context.IsRemoteCertificateAvailable; /* does not work: Context.IsMutualAuthFlag;*/ } } public override bool IsEncrypted => IsAuthenticated; public override bool IsSigned => IsAuthenticated; public override bool IsServer => _context != null && _context.IsServer; public virtual SslProtocols SslProtocol { get { ThrowIfExceptionalOrNotHandshake(); return GetSslProtocolInternal(); } } // Skips the ThrowIfExceptionalOrNotHandshake() check private SslProtocols GetSslProtocolInternal() { SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return SslProtocols.None; } SslProtocols proto = (SslProtocols)info.Protocol; SslProtocols ret = SslProtocols.None; #pragma warning disable 0618 // Ssl2, Ssl3 are deprecated. // Restore client/server bits so the result maps exactly on published constants. if ((proto & SslProtocols.Ssl2) != 0) { ret |= SslProtocols.Ssl2; } if ((proto & SslProtocols.Ssl3) != 0) { ret |= SslProtocols.Ssl3; } #pragma warning restore #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete if ((proto & SslProtocols.Tls) != 0) { ret |= SslProtocols.Tls; } if ((proto & SslProtocols.Tls11) != 0) { ret |= SslProtocols.Tls11; } #pragma warning restore SYSLIB0039 if ((proto & SslProtocols.Tls12) != 0) { ret |= SslProtocols.Tls12; } if ((proto & SslProtocols.Tls13) != 0) { ret |= SslProtocols.Tls13; } return ret; } public virtual bool CheckCertRevocationStatus => _context != null && _context.CheckCertRevocationStatus != X509RevocationMode.NoCheck; // // This will return selected local cert for both client/server streams // public virtual X509Certificate? LocalCertificate { get { ThrowIfExceptionalOrNotAuthenticated(); return _context!.IsServer ? _context.LocalServerCertificate : _context.LocalClientCertificate; } } public virtual X509Certificate? RemoteCertificate { get { ThrowIfExceptionalOrNotAuthenticated(); return _context?.RemoteCertificate; } } [CLSCompliant(false)] public virtual TlsCipherSuite NegotiatedCipherSuite { get { ThrowIfExceptionalOrNotHandshake(); return _context!.ConnectionInfo?.TlsCipherSuite ?? default(TlsCipherSuite); } } public virtual CipherAlgorithmType CipherAlgorithm { get { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return CipherAlgorithmType.None; } return (CipherAlgorithmType)info.DataCipherAlg; } } public virtual int CipherStrength { get { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return 0; } return info.DataKeySize; } } public virtual HashAlgorithmType HashAlgorithm { get { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return (HashAlgorithmType)0; } return (HashAlgorithmType)info.DataHashAlg; } } public virtual int HashStrength { get { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return 0; } return info.DataHashKeySize; } } public virtual ExchangeAlgorithmType KeyExchangeAlgorithm { get { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return (ExchangeAlgorithmType)0; } return (ExchangeAlgorithmType)info.KeyExchangeAlg; } } public virtual int KeyExchangeStrength { get { ThrowIfExceptionalOrNotHandshake(); SslConnectionInfo? info = _context!.ConnectionInfo; if (info == null) { return 0; } return info.KeyExchKeySize; } } public string TargetHostName { get { return _sslAuthenticationOptions != null ? _sslAuthenticationOptions.TargetHost : string.Empty; } } // // Stream contract implementation. // public override bool CanSeek => false; public override bool CanRead => IsAuthenticated && InnerStream.CanRead; public override bool CanTimeout => InnerStream.CanTimeout; public override bool CanWrite => IsAuthenticated && InnerStream.CanWrite && !_shutdown; public override int ReadTimeout { get => InnerStream.ReadTimeout; set => InnerStream.ReadTimeout = value; } public override int WriteTimeout { get => InnerStream.WriteTimeout; set => InnerStream.WriteTimeout = value; } public override long Length => InnerStream.Length; public override long Position { get => InnerStream.Position; set => throw new NotSupportedException(SR.net_noseek); } public override void SetLength(long value) => InnerStream.SetLength(value); public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(SR.net_noseek); public override void Flush() => InnerStream.Flush(); public override Task FlushAsync(CancellationToken cancellationToken) => InnerStream.FlushAsync(cancellationToken); public virtual Task NegotiateClientCertificateAsync(CancellationToken cancellationToken = default) { ThrowIfExceptionalOrNotAuthenticated(); if (RemoteCertificate != null) { throw new InvalidOperationException(SR.net_ssl_certificate_exist); } return RenegotiateAsync<AsyncReadWriteAdapter>(cancellationToken); } protected override void Dispose(bool disposing) { try { CloseInternal(); } finally { base.Dispose(disposing); } } public override async ValueTask DisposeAsync() { try { CloseInternal(); } finally { await base.DisposeAsync().ConfigureAwait(false); } } public override int ReadByte() { ThrowIfExceptionalOrNotAuthenticated(); if (Interlocked.Exchange(ref _nestedRead, 1) == 1) { throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "read")); } // If there's any data in the buffer, take one byte, and we're done. try { if (_buffer.DecryptedLength > 0) { int b = _buffer.DecryptedSpan[0]; _buffer.Discard(1); ReturnReadBufferIfEmpty(); return b; } } finally { // Regardless of whether we were able to read a byte from the buffer, // reset the read tracking. If we weren't able to read a byte, the // subsequent call to Read will set the flag again. _nestedRead = 0; } // Otherwise, fall back to reading a byte via Read, the same way Stream.ReadByte does. // This allocation is unfortunate but should be relatively rare, as it'll only occur once // per buffer fill internally by Read. byte[] oneByte = new byte[1]; int bytesRead = Read(oneByte, 0, 1); Debug.Assert(bytesRead == 0 || bytesRead == 1); return bytesRead == 1 ? oneByte[0] : -1; } public override int Read(byte[] buffer, int offset, int count) { ThrowIfExceptionalOrNotAuthenticated(); ValidateBufferArguments(buffer, offset, count); ValueTask<int> vt = ReadAsyncInternal<SyncReadWriteAdapter>(new Memory<byte>(buffer, offset, count), default(CancellationToken)); Debug.Assert(vt.IsCompleted, "Sync operation must have completed synchronously"); return vt.GetAwaiter().GetResult(); } public void Write(byte[] buffer) => Write(buffer, 0, buffer.Length); public override void Write(byte[] buffer, int offset, int count) { ThrowIfExceptionalOrNotAuthenticated(); ValidateBufferArguments(buffer, offset, count); ValueTask vt = WriteAsyncInternal<SyncReadWriteAdapter>(new ReadOnlyMemory<byte>(buffer, offset, count), default(CancellationToken)); Debug.Assert(vt.IsCompleted, "Sync operation must have completed synchronously"); vt.GetAwaiter().GetResult(); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) { ThrowIfExceptionalOrNotAuthenticated(); return TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); } public override int EndRead(IAsyncResult asyncResult) { ThrowIfExceptionalOrNotAuthenticated(); return TaskToApm.End<int>(asyncResult); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) { ThrowIfExceptionalOrNotAuthenticated(); return TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); } public override void EndWrite(IAsyncResult asyncResult) { ThrowIfExceptionalOrNotAuthenticated(); TaskToApm.End(asyncResult); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { ThrowIfExceptionalOrNotAuthenticated(); ValidateBufferArguments(buffer, offset, count); return WriteAsyncInternal<AsyncReadWriteAdapter>(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken).AsTask(); } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) { ThrowIfExceptionalOrNotAuthenticated(); return WriteAsyncInternal<AsyncReadWriteAdapter>(buffer, cancellationToken); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { ThrowIfExceptionalOrNotAuthenticated(); ValidateBufferArguments(buffer, offset, count); return ReadAsyncInternal<AsyncReadWriteAdapter>(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask(); } public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) { ThrowIfExceptionalOrNotAuthenticated(); return ReadAsyncInternal<AsyncReadWriteAdapter>(buffer, cancellationToken); } private void ThrowIfExceptional() { ExceptionDispatchInfo? e = _exception; if (e != null) { ThrowExceptional(e); } // Local function to make the check method more inline friendly. static void ThrowExceptional(ExceptionDispatchInfo e) { // If the stored exception just indicates disposal, throw a new ODE rather than the stored one, // so as to not continually build onto the shared exception's stack. if (ReferenceEquals(e, s_disposedSentinel)) { throw new ObjectDisposedException(nameof(SslStream)); } // Throw the stored exception. e.Throw(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ThrowIfExceptionalOrNotAuthenticated() { ThrowIfExceptional(); if (!IsAuthenticated) { ThrowNotAuthenticated(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ThrowIfExceptionalOrNotHandshake() { ThrowIfExceptional(); if (!IsAuthenticated && _context?.ConnectionInfo == null) { ThrowNotAuthenticated(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ThrowIfExceptionalOrNotAuthenticatedOrShutdown() { ThrowIfExceptional(); if (!IsAuthenticated) { ThrowNotAuthenticated(); } if (_shutdown) { ThrowAlreadyShutdown(); } // Local function to make the check method more inline friendly. static void ThrowAlreadyShutdown() { throw new InvalidOperationException(SR.net_ssl_io_already_shutdown); } } // Static non-returning throw method to make the check methods more inline friendly. private static void ThrowNotAuthenticated() { throw new InvalidOperationException(SR.net_auth_noauth); } } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.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.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Text; using Microsoft.Win32.SafeHandles; namespace System.Net.Security { internal static class SslStreamPal { private static readonly bool UseNewCryptoApi = // On newer Windows version we use new API to get TLS1.3. // API is supported since Windows 10 1809 (17763) but there is no reason to use at the moment. Environment.OSVersion.Version.Major >= 10 && Environment.OSVersion.Version.Build >= 18836; private const string SecurityPackage = "Microsoft Unified Security Protocol Provider"; private const Interop.SspiCli.ContextFlags RequiredFlags = Interop.SspiCli.ContextFlags.ReplayDetect | Interop.SspiCli.ContextFlags.SequenceDetect | Interop.SspiCli.ContextFlags.Confidentiality | Interop.SspiCli.ContextFlags.AllocateMemory; private const Interop.SspiCli.ContextFlags ServerRequiredFlags = RequiredFlags | Interop.SspiCli.ContextFlags.AcceptStream | Interop.SspiCli.ContextFlags.AcceptExtendedError; public static Exception GetException(SecurityStatusPal status) { int win32Code = (int)SecurityStatusAdapterPal.GetInteropFromSecurityStatusPal(status); return new Win32Exception(win32Code); } internal const bool StartMutualAuthAsAnonymous = true; internal const bool CanEncryptEmptyMessage = true; public static void VerifyPackageInfo() { SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPISecureChannel, SecurityPackage, true); } public static byte[] ConvertAlpnProtocolListToByteArray(List<SslApplicationProtocol> protocols) { return Interop.Sec_Application_Protocols.ToByteArray(protocols); } public static SecurityStatusPal AcceptSecurityContext( SecureChannel secureChannel, ref SafeFreeCredentials? credentialsHandle, ref SafeDeleteSslContext? context, ReadOnlySpan<byte> inputBuffer, ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { Interop.SspiCli.ContextFlags unusedAttributes = default; InputSecurityBuffers inputBuffers = default; inputBuffers.SetNextBuffer(new InputSecurityBuffer(inputBuffer, SecurityBufferType.SECBUFFER_TOKEN)); inputBuffers.SetNextBuffer(new InputSecurityBuffer(default, SecurityBufferType.SECBUFFER_EMPTY)); if (sslAuthenticationOptions.ApplicationProtocols != null && sslAuthenticationOptions.ApplicationProtocols.Count != 0) { byte[] alpnBytes = ConvertAlpnProtocolListToByteArray(sslAuthenticationOptions.ApplicationProtocols); inputBuffers.SetNextBuffer(new InputSecurityBuffer(new ReadOnlySpan<byte>(alpnBytes), SecurityBufferType.SECBUFFER_APPLICATION_PROTOCOLS)); } var resultBuffer = new SecurityBuffer(outputBuffer, SecurityBufferType.SECBUFFER_TOKEN); int errorCode = SSPIWrapper.AcceptSecurityContext( GlobalSSPI.SSPISecureChannel, credentialsHandle, ref context, ServerRequiredFlags | (sslAuthenticationOptions.RemoteCertRequired ? Interop.SspiCli.ContextFlags.MutualAuth : Interop.SspiCli.ContextFlags.Zero), Interop.SspiCli.Endianness.SECURITY_NATIVE_DREP, inputBuffers, ref resultBuffer, ref unusedAttributes); outputBuffer = resultBuffer.token; return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } public static SecurityStatusPal InitializeSecurityContext( SecureChannel secureChannel, ref SafeFreeCredentials? credentialsHandle, ref SafeDeleteSslContext? context, string? targetName, ReadOnlySpan<byte> inputBuffer, ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { Interop.SspiCli.ContextFlags unusedAttributes = default; InputSecurityBuffers inputBuffers = default; inputBuffers.SetNextBuffer(new InputSecurityBuffer(inputBuffer, SecurityBufferType.SECBUFFER_TOKEN)); inputBuffers.SetNextBuffer(new InputSecurityBuffer(default, SecurityBufferType.SECBUFFER_EMPTY)); if (sslAuthenticationOptions.ApplicationProtocols != null && sslAuthenticationOptions.ApplicationProtocols.Count != 0) { byte[] alpnBytes = ConvertAlpnProtocolListToByteArray(sslAuthenticationOptions.ApplicationProtocols); inputBuffers.SetNextBuffer(new InputSecurityBuffer(new ReadOnlySpan<byte>(alpnBytes), SecurityBufferType.SECBUFFER_APPLICATION_PROTOCOLS)); } var resultBuffer = new SecurityBuffer(outputBuffer, SecurityBufferType.SECBUFFER_TOKEN); int errorCode = SSPIWrapper.InitializeSecurityContext( GlobalSSPI.SSPISecureChannel, ref credentialsHandle, ref context, targetName, RequiredFlags | Interop.SspiCli.ContextFlags.InitManualCredValidation, Interop.SspiCli.Endianness.SECURITY_NATIVE_DREP, inputBuffers, ref resultBuffer, ref unusedAttributes); outputBuffer = resultBuffer.token; return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } public static SecurityStatusPal Renegotiate( SecureChannel secureChannel, ref SafeFreeCredentials? credentialsHandle, ref SafeDeleteSslContext? context, SslAuthenticationOptions sslAuthenticationOptions, out byte[]? outputBuffer ) { byte[]? output = Array.Empty<byte>(); SecurityStatusPal status = AcceptSecurityContext(secureChannel, ref credentialsHandle, ref context, Span<byte>.Empty, ref output, sslAuthenticationOptions); outputBuffer = output; return status; } public static SafeFreeCredentials AcquireCredentialsHandle(SslStreamCertificateContext? certificateContext, SslProtocols protocols, EncryptionPolicy policy, bool isServer) { try { // New crypto API supports TLS1.3 but it does not allow to force NULL encryption. SafeFreeCredentials cred = !UseNewCryptoApi || policy == EncryptionPolicy.NoEncryption ? AcquireCredentialsHandleSchannelCred(certificateContext, protocols, policy, isServer) : AcquireCredentialsHandleSchCredentials(certificateContext, protocols, policy, isServer); if (certificateContext != null && certificateContext.Trust != null && certificateContext.Trust._sendTrustInHandshake) { AttachCertificateStore(cred, certificateContext.Trust._store!); } return cred; } catch (Win32Exception e) { throw new AuthenticationException(SR.net_auth_SSPI, e); } } private static unsafe void AttachCertificateStore(SafeFreeCredentials cred, X509Store store) { Interop.SspiCli.SecPkgCred_ClientCertPolicy clientCertPolicy = default; fixed (char* ptr = store.Name) { clientCertPolicy.pwszSslCtlStoreName = ptr; Interop.SECURITY_STATUS errorCode = Interop.SspiCli.SetCredentialsAttributesW( cred._handle, (long)Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CLIENT_CERT_POLICY, clientCertPolicy, sizeof(Interop.SspiCli.SecPkgCred_ClientCertPolicy)); if (errorCode != Interop.SECURITY_STATUS.OK) { throw new Win32Exception((int)errorCode); } } return; } // This is legacy crypto API used on .NET Framework and older Windows versions. // It only supports TLS up to 1.2 public static unsafe SafeFreeCredentials AcquireCredentialsHandleSchannelCred(SslStreamCertificateContext? certificateContext, SslProtocols protocols, EncryptionPolicy policy, bool isServer) { X509Certificate2? certificate = certificateContext?.Certificate; int protocolFlags = GetProtocolFlagsFromSslProtocols(protocols, isServer); Interop.SspiCli.SCHANNEL_CRED.Flags flags; Interop.SspiCli.CredentialUse direction; if (!isServer) { direction = Interop.SspiCli.CredentialUse.SECPKG_CRED_OUTBOUND; flags = Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_CRED_MANUAL_CRED_VALIDATION | Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_CRED_NO_DEFAULT_CREDS | Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_SEND_AUX_RECORD; // Always opt-in SCH_USE_STRONG_CRYPTO for TLS. if (((protocolFlags == 0) || (protocolFlags & ~(Interop.SChannel.SP_PROT_SSL2 | Interop.SChannel.SP_PROT_SSL3)) != 0) && (policy != EncryptionPolicy.AllowNoEncryption) && (policy != EncryptionPolicy.NoEncryption)) { flags |= Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_USE_STRONG_CRYPTO; } } else { direction = Interop.SspiCli.CredentialUse.SECPKG_CRED_INBOUND; flags = Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_SEND_AUX_RECORD; if (certificateContext?.Trust?._sendTrustInHandshake == true) { flags |= Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_CRED_NO_SYSTEM_MAPPER; } } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info($"flags=({flags}), ProtocolFlags=({protocolFlags}), EncryptionPolicy={policy}"); Interop.SspiCli.SCHANNEL_CRED secureCredential = CreateSecureCredential( flags, protocolFlags, policy); if (certificate != null) { secureCredential.cCreds = 1; Interop.Crypt32.CERT_CONTEXT* certificateHandle = (Interop.Crypt32.CERT_CONTEXT*)certificate.Handle; secureCredential.paCred = &certificateHandle; } return AcquireCredentialsHandle(direction, &secureCredential); } // This function uses new crypto API to support TLS 1.3 and beyond. public static unsafe SafeFreeCredentials AcquireCredentialsHandleSchCredentials(SslStreamCertificateContext? certificateContext, SslProtocols protocols, EncryptionPolicy policy, bool isServer) { X509Certificate2? certificate = certificateContext?.Certificate; int protocolFlags = GetProtocolFlagsFromSslProtocols(protocols, isServer); Interop.SspiCli.SCH_CREDENTIALS.Flags flags; Interop.SspiCli.CredentialUse direction; if (isServer) { direction = Interop.SspiCli.CredentialUse.SECPKG_CRED_INBOUND; flags = Interop.SspiCli.SCH_CREDENTIALS.Flags.SCH_SEND_AUX_RECORD; if (certificateContext?.Trust?._sendTrustInHandshake == true) { flags |= Interop.SspiCli.SCH_CREDENTIALS.Flags.SCH_CRED_NO_SYSTEM_MAPPER; } } else { direction = Interop.SspiCli.CredentialUse.SECPKG_CRED_OUTBOUND; flags = Interop.SspiCli.SCH_CREDENTIALS.Flags.SCH_CRED_MANUAL_CRED_VALIDATION | Interop.SspiCli.SCH_CREDENTIALS.Flags.SCH_CRED_NO_DEFAULT_CREDS | Interop.SspiCli.SCH_CREDENTIALS.Flags.SCH_SEND_AUX_RECORD; } if (policy == EncryptionPolicy.RequireEncryption) { // Always opt-in SCH_USE_STRONG_CRYPTO for TLS. if (!isServer && ((protocolFlags & Interop.SChannel.SP_PROT_SSL3) == 0)) { flags |= Interop.SspiCli.SCH_CREDENTIALS.Flags.SCH_USE_STRONG_CRYPTO; } } else if (policy == EncryptionPolicy.AllowNoEncryption) { // Allow null encryption cipher in addition to other ciphers. flags |= Interop.SspiCli.SCH_CREDENTIALS.Flags.SCH_ALLOW_NULL_ENCRYPTION; } else { throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), nameof(policy)); } Interop.SspiCli.SCH_CREDENTIALS credential = default; credential.dwVersion = Interop.SspiCli.SCH_CREDENTIALS.CurrentVersion; credential.dwFlags = flags; if (certificate != null) { credential.cCreds = 1; Interop.Crypt32.CERT_CONTEXT* certificateHandle = (Interop.Crypt32.CERT_CONTEXT*)certificate.Handle; credential.paCred = &certificateHandle; } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info($"flags=({flags}), ProtocolFlags=({protocolFlags}), EncryptionPolicy={policy}"); if (protocolFlags != 0) { // If we were asked to do specific protocol we need to fill TLS_PARAMETERS. Interop.SspiCli.TLS_PARAMETERS tlsParameters = default; tlsParameters.grbitDisabledProtocols = (uint)protocolFlags ^ uint.MaxValue; credential.cTlsParameters = 1; credential.pTlsParameters = &tlsParameters; } return AcquireCredentialsHandle(direction, &credential); } internal static byte[]? GetNegotiatedApplicationProtocol(SafeDeleteContext context) { Interop.SecPkgContext_ApplicationProtocol alpnContext = default; bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPISecureChannel, context, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_APPLICATION_PROTOCOL, ref alpnContext); // Check if the context returned is alpn data, with successful negotiation. if (success && alpnContext.ProtoNegoExt == Interop.ApplicationProtocolNegotiationExt.ALPN && alpnContext.ProtoNegoStatus == Interop.ApplicationProtocolNegotiationStatus.Success) { return alpnContext.Protocol; } return null; } public static unsafe SecurityStatusPal EncryptMessage(SafeDeleteSslContext securityContext, ReadOnlyMemory<byte> input, int headerSize, int trailerSize, ref byte[] output, out int resultSize) { // Ensure that there is sufficient space for the message output. int bufferSizeNeeded = checked(input.Length + headerSize + trailerSize); if (output == null || output.Length < bufferSizeNeeded) { output = new byte[bufferSizeNeeded]; } // Copy the input into the output buffer to prepare for SCHANNEL's expectations input.Span.CopyTo(new Span<byte>(output, headerSize, input.Length)); const int NumSecBuffers = 4; // header + data + trailer + empty Interop.SspiCli.SecBuffer* unmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[NumSecBuffers]; Interop.SspiCli.SecBufferDesc sdcInOut = new Interop.SspiCli.SecBufferDesc(NumSecBuffers) { pBuffers = unmanagedBuffer }; fixed (byte* outputPtr = output) { Interop.SspiCli.SecBuffer* headerSecBuffer = &unmanagedBuffer[0]; headerSecBuffer->BufferType = SecurityBufferType.SECBUFFER_STREAM_HEADER; headerSecBuffer->pvBuffer = (IntPtr)outputPtr; headerSecBuffer->cbBuffer = headerSize; Interop.SspiCli.SecBuffer* dataSecBuffer = &unmanagedBuffer[1]; dataSecBuffer->BufferType = SecurityBufferType.SECBUFFER_DATA; dataSecBuffer->pvBuffer = (IntPtr)(outputPtr + headerSize); dataSecBuffer->cbBuffer = input.Length; Interop.SspiCli.SecBuffer* trailerSecBuffer = &unmanagedBuffer[2]; trailerSecBuffer->BufferType = SecurityBufferType.SECBUFFER_STREAM_TRAILER; trailerSecBuffer->pvBuffer = (IntPtr)(outputPtr + headerSize + input.Length); trailerSecBuffer->cbBuffer = trailerSize; Interop.SspiCli.SecBuffer* emptySecBuffer = &unmanagedBuffer[3]; emptySecBuffer->BufferType = SecurityBufferType.SECBUFFER_EMPTY; emptySecBuffer->cbBuffer = 0; emptySecBuffer->pvBuffer = IntPtr.Zero; int errorCode = GlobalSSPI.SSPISecureChannel.EncryptMessage(securityContext, ref sdcInOut, 0); if (errorCode != 0) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(securityContext, $"Encrypt ERROR {errorCode:X}"); resultSize = 0; return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } Debug.Assert(headerSecBuffer->cbBuffer >= 0 && dataSecBuffer->cbBuffer >= 0 && trailerSecBuffer->cbBuffer >= 0); Debug.Assert(checked(headerSecBuffer->cbBuffer + dataSecBuffer->cbBuffer + trailerSecBuffer->cbBuffer) <= output.Length); resultSize = checked(headerSecBuffer->cbBuffer + dataSecBuffer->cbBuffer + trailerSecBuffer->cbBuffer); return new SecurityStatusPal(SecurityStatusPalErrorCode.OK); } } public static unsafe SecurityStatusPal DecryptMessage(SafeDeleteSslContext? securityContext, Span<byte> buffer, out int offset, out int count) { const int NumSecBuffers = 4; // data + empty + empty + empty fixed (byte* bufferPtr = buffer) { Interop.SspiCli.SecBuffer* unmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[NumSecBuffers]; Interop.SspiCli.SecBuffer* dataBuffer = &unmanagedBuffer[0]; dataBuffer->BufferType = SecurityBufferType.SECBUFFER_DATA; dataBuffer->pvBuffer = (IntPtr)bufferPtr; dataBuffer->cbBuffer = buffer.Length; for (int i = 1; i < NumSecBuffers; i++) { Interop.SspiCli.SecBuffer* emptyBuffer = &unmanagedBuffer[i]; emptyBuffer->BufferType = SecurityBufferType.SECBUFFER_EMPTY; emptyBuffer->pvBuffer = IntPtr.Zero; emptyBuffer->cbBuffer = 0; } Interop.SspiCli.SecBufferDesc sdcInOut = new Interop.SspiCli.SecBufferDesc(NumSecBuffers) { pBuffers = unmanagedBuffer }; Interop.SECURITY_STATUS errorCode = (Interop.SECURITY_STATUS)GlobalSSPI.SSPISecureChannel.DecryptMessage(securityContext!, ref sdcInOut, 0); // Decrypt may repopulate the sec buffers, likely with header + data + trailer + empty. // We need to find the data. count = 0; offset = 0; for (int i = 0; i < NumSecBuffers; i++) { // Successfully decoded data and placed it at the following position in the buffer, if ((errorCode == Interop.SECURITY_STATUS.OK && unmanagedBuffer[i].BufferType == SecurityBufferType.SECBUFFER_DATA) // or we failed to decode the data, here is the encoded data. || (errorCode != Interop.SECURITY_STATUS.OK && unmanagedBuffer[i].BufferType == SecurityBufferType.SECBUFFER_EXTRA)) { offset = (int)((byte*)unmanagedBuffer[i].pvBuffer - bufferPtr); count = unmanagedBuffer[i].cbBuffer; // output is ignored on Windows. We always decrypt in place and we set outputOffset to indicate where the data start. Debug.Assert(offset >= 0 && count >= 0, $"Expected offset and count greater than 0, got {offset} and {count}"); Debug.Assert(checked(offset + count) <= buffer.Length, $"Expected offset+count <= buffer.Length, got {offset}+{count}>={buffer.Length}"); break; } } return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode); } } public static SecurityStatusPal ApplyAlertToken(ref SafeFreeCredentials? credentialsHandle, SafeDeleteContext? securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage) { var alertToken = new Interop.SChannel.SCHANNEL_ALERT_TOKEN { dwTokenType = Interop.SChannel.SCHANNEL_ALERT, dwAlertType = (uint)alertType, dwAlertNumber = (uint)alertMessage }; byte[] buffer = MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref alertToken, 1)).ToArray(); var securityBuffer = new SecurityBuffer(buffer, SecurityBufferType.SECBUFFER_TOKEN); var errorCode = (Interop.SECURITY_STATUS)SSPIWrapper.ApplyControlToken( GlobalSSPI.SSPISecureChannel, ref securityContext, in securityBuffer); return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode, attachException: true); } private static readonly byte[] s_schannelShutdownBytes = BitConverter.GetBytes(Interop.SChannel.SCHANNEL_SHUTDOWN); public static SecurityStatusPal ApplyShutdownToken(ref SafeFreeCredentials? credentialsHandle, SafeDeleteContext? securityContext) { var securityBuffer = new SecurityBuffer(s_schannelShutdownBytes, SecurityBufferType.SECBUFFER_TOKEN); var errorCode = (Interop.SECURITY_STATUS)SSPIWrapper.ApplyControlToken( GlobalSSPI.SSPISecureChannel, ref securityContext, in securityBuffer); return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode, attachException: true); } public static SafeFreeContextBufferChannelBinding? QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute) { return SSPIWrapper.QueryContextChannelBinding(GlobalSSPI.SSPISecureChannel, securityContext, (Interop.SspiCli.ContextAttribute)attribute); } public static void QueryContextStreamSizes(SafeDeleteContext securityContext, out StreamSizes streamSizes) { SecPkgContext_StreamSizes interopStreamSizes = default; bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_STREAM_SIZES, ref interopStreamSizes); Debug.Assert(success); streamSizes = new StreamSizes(interopStreamSizes); } public static void QueryContextConnectionInfo(SafeDeleteContext securityContext, out SslConnectionInfo connectionInfo) { SecPkgContext_ConnectionInfo interopConnectionInfo = default; bool success = SSPIWrapper.QueryBlittableContextAttributes( GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CONNECTION_INFO, ref interopConnectionInfo); Debug.Assert(success); TlsCipherSuite cipherSuite = default; SecPkgContext_CipherInfo cipherInfo = default; success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CIPHER_INFO, ref cipherInfo); if (success) { cipherSuite = (TlsCipherSuite)cipherInfo.dwCipherSuite; } connectionInfo = new SslConnectionInfo(interopConnectionInfo, cipherSuite); } private static int GetProtocolFlagsFromSslProtocols(SslProtocols protocols, bool isServer) { int protocolFlags = (int)protocols; if (isServer) { protocolFlags &= Interop.SChannel.ServerProtocolMask; } else { protocolFlags &= Interop.SChannel.ClientProtocolMask; } return protocolFlags; } private static Interop.SspiCli.SCHANNEL_CRED CreateSecureCredential( Interop.SspiCli.SCHANNEL_CRED.Flags flags, int protocols, EncryptionPolicy policy) { var credential = new Interop.SspiCli.SCHANNEL_CRED() { hRootStore = IntPtr.Zero, aphMappers = IntPtr.Zero, palgSupportedAlgs = IntPtr.Zero, paCred = null, cCreds = 0, cMappers = 0, cSupportedAlgs = 0, dwSessionLifespan = 0, reserved = 0, dwVersion = Interop.SspiCli.SCHANNEL_CRED.CurrentVersion }; if (policy == EncryptionPolicy.RequireEncryption) { // Prohibit null encryption cipher. credential.dwMinimumCipherStrength = 0; credential.dwMaximumCipherStrength = 0; } else if (policy == EncryptionPolicy.AllowNoEncryption) { // Allow null encryption cipher in addition to other ciphers. credential.dwMinimumCipherStrength = -1; credential.dwMaximumCipherStrength = 0; } else if (policy == EncryptionPolicy.NoEncryption) { // Suppress all encryption and require null encryption cipher only credential.dwMinimumCipherStrength = -1; credential.dwMaximumCipherStrength = -1; } else { throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), nameof(policy)); } credential.dwFlags = flags; credential.grbitEnabledProtocols = protocols; return credential; } // // Security: we temporarily reset thread token to open the handle under process account. // private static unsafe SafeFreeCredentials AcquireCredentialsHandle(Interop.SspiCli.CredentialUse credUsage, Interop.SspiCli.SCHANNEL_CRED* secureCredential) { // First try without impersonation, if it fails, then try the process account. // I.E. We don't know which account the certificate context was created under. try { // // For app-compat we want to ensure the credential are accessed under >>process<< account. // return WindowsIdentity.RunImpersonated<SafeFreeCredentials>(SafeAccessTokenHandle.InvalidHandle, () => { return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential); }); } catch { return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential); } } private static unsafe SafeFreeCredentials AcquireCredentialsHandle(Interop.SspiCli.CredentialUse credUsage, Interop.SspiCli.SCH_CREDENTIALS* secureCredential) { // First try without impersonation, if it fails, then try the process account. // I.E. We don't know which account the certificate context was created under. try { // // For app-compat we want to ensure the credential are accessed under >>process<< account. // return WindowsIdentity.RunImpersonated<SafeFreeCredentials>(SafeAccessTokenHandle.InvalidHandle, () => { return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential); }); } catch { return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential); } } } }
// 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; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Text; using Microsoft.Win32.SafeHandles; namespace System.Net.Security { internal static class SslStreamPal { private static readonly bool UseNewCryptoApi = // On newer Windows version we use new API to get TLS1.3. // API is supported since Windows 10 1809 (17763) but there is no reason to use at the moment. Environment.OSVersion.Version.Major >= 10 && Environment.OSVersion.Version.Build >= 18836; private const string SecurityPackage = "Microsoft Unified Security Protocol Provider"; private const Interop.SspiCli.ContextFlags RequiredFlags = Interop.SspiCli.ContextFlags.ReplayDetect | Interop.SspiCli.ContextFlags.SequenceDetect | Interop.SspiCli.ContextFlags.Confidentiality | Interop.SspiCli.ContextFlags.AllocateMemory; private const Interop.SspiCli.ContextFlags ServerRequiredFlags = RequiredFlags | Interop.SspiCli.ContextFlags.AcceptStream | Interop.SspiCli.ContextFlags.AcceptExtendedError; public static Exception GetException(SecurityStatusPal status) { int win32Code = (int)SecurityStatusAdapterPal.GetInteropFromSecurityStatusPal(status); return new Win32Exception(win32Code); } internal const bool StartMutualAuthAsAnonymous = true; internal const bool CanEncryptEmptyMessage = true; public static void VerifyPackageInfo() { SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPISecureChannel, SecurityPackage, true); } public static byte[] ConvertAlpnProtocolListToByteArray(List<SslApplicationProtocol> protocols) { return Interop.Sec_Application_Protocols.ToByteArray(protocols); } public static SecurityStatusPal AcceptSecurityContext( SecureChannel secureChannel, ref SafeFreeCredentials? credentialsHandle, ref SafeDeleteSslContext? context, ReadOnlySpan<byte> inputBuffer, ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { Interop.SspiCli.ContextFlags unusedAttributes = default; InputSecurityBuffers inputBuffers = default; inputBuffers.SetNextBuffer(new InputSecurityBuffer(inputBuffer, SecurityBufferType.SECBUFFER_TOKEN)); inputBuffers.SetNextBuffer(new InputSecurityBuffer(default, SecurityBufferType.SECBUFFER_EMPTY)); if (sslAuthenticationOptions.ApplicationProtocols != null && sslAuthenticationOptions.ApplicationProtocols.Count != 0) { byte[] alpnBytes = ConvertAlpnProtocolListToByteArray(sslAuthenticationOptions.ApplicationProtocols); inputBuffers.SetNextBuffer(new InputSecurityBuffer(new ReadOnlySpan<byte>(alpnBytes), SecurityBufferType.SECBUFFER_APPLICATION_PROTOCOLS)); } var resultBuffer = new SecurityBuffer(outputBuffer, SecurityBufferType.SECBUFFER_TOKEN); int errorCode = SSPIWrapper.AcceptSecurityContext( GlobalSSPI.SSPISecureChannel, credentialsHandle, ref context, ServerRequiredFlags | (sslAuthenticationOptions.RemoteCertRequired ? Interop.SspiCli.ContextFlags.MutualAuth : Interop.SspiCli.ContextFlags.Zero), Interop.SspiCli.Endianness.SECURITY_NATIVE_DREP, inputBuffers, ref resultBuffer, ref unusedAttributes); outputBuffer = resultBuffer.token; return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } public static SecurityStatusPal InitializeSecurityContext( SecureChannel secureChannel, ref SafeFreeCredentials? credentialsHandle, ref SafeDeleteSslContext? context, string? targetName, ReadOnlySpan<byte> inputBuffer, ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { Interop.SspiCli.ContextFlags unusedAttributes = default; InputSecurityBuffers inputBuffers = default; inputBuffers.SetNextBuffer(new InputSecurityBuffer(inputBuffer, SecurityBufferType.SECBUFFER_TOKEN)); inputBuffers.SetNextBuffer(new InputSecurityBuffer(default, SecurityBufferType.SECBUFFER_EMPTY)); if (sslAuthenticationOptions.ApplicationProtocols != null && sslAuthenticationOptions.ApplicationProtocols.Count != 0) { byte[] alpnBytes = ConvertAlpnProtocolListToByteArray(sslAuthenticationOptions.ApplicationProtocols); inputBuffers.SetNextBuffer(new InputSecurityBuffer(new ReadOnlySpan<byte>(alpnBytes), SecurityBufferType.SECBUFFER_APPLICATION_PROTOCOLS)); } var resultBuffer = new SecurityBuffer(outputBuffer, SecurityBufferType.SECBUFFER_TOKEN); int errorCode = SSPIWrapper.InitializeSecurityContext( GlobalSSPI.SSPISecureChannel, ref credentialsHandle, ref context, targetName, RequiredFlags | Interop.SspiCli.ContextFlags.InitManualCredValidation, Interop.SspiCli.Endianness.SECURITY_NATIVE_DREP, inputBuffers, ref resultBuffer, ref unusedAttributes); outputBuffer = resultBuffer.token; return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } public static SecurityStatusPal Renegotiate( SecureChannel secureChannel, ref SafeFreeCredentials? credentialsHandle, ref SafeDeleteSslContext? context, SslAuthenticationOptions sslAuthenticationOptions, out byte[]? outputBuffer ) { byte[]? output = Array.Empty<byte>(); SecurityStatusPal status = AcceptSecurityContext(secureChannel, ref credentialsHandle, ref context, Span<byte>.Empty, ref output, sslAuthenticationOptions); outputBuffer = output; return status; } public static SafeFreeCredentials AcquireCredentialsHandle(SslStreamCertificateContext? certificateContext, SslProtocols protocols, EncryptionPolicy policy, bool isServer) { try { // New crypto API supports TLS1.3 but it does not allow to force NULL encryption. #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete SafeFreeCredentials cred = !UseNewCryptoApi || policy == EncryptionPolicy.NoEncryption ? AcquireCredentialsHandleSchannelCred(certificateContext, protocols, policy, isServer) : AcquireCredentialsHandleSchCredentials(certificateContext, protocols, policy, isServer); #pragma warning restore SYSLIB0040 if (certificateContext != null && certificateContext.Trust != null && certificateContext.Trust._sendTrustInHandshake) { AttachCertificateStore(cred, certificateContext.Trust._store!); } return cred; } catch (Win32Exception e) { throw new AuthenticationException(SR.net_auth_SSPI, e); } } private static unsafe void AttachCertificateStore(SafeFreeCredentials cred, X509Store store) { Interop.SspiCli.SecPkgCred_ClientCertPolicy clientCertPolicy = default; fixed (char* ptr = store.Name) { clientCertPolicy.pwszSslCtlStoreName = ptr; Interop.SECURITY_STATUS errorCode = Interop.SspiCli.SetCredentialsAttributesW( cred._handle, (long)Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CLIENT_CERT_POLICY, clientCertPolicy, sizeof(Interop.SspiCli.SecPkgCred_ClientCertPolicy)); if (errorCode != Interop.SECURITY_STATUS.OK) { throw new Win32Exception((int)errorCode); } } return; } // This is legacy crypto API used on .NET Framework and older Windows versions. // It only supports TLS up to 1.2 public static unsafe SafeFreeCredentials AcquireCredentialsHandleSchannelCred(SslStreamCertificateContext? certificateContext, SslProtocols protocols, EncryptionPolicy policy, bool isServer) { X509Certificate2? certificate = certificateContext?.Certificate; int protocolFlags = GetProtocolFlagsFromSslProtocols(protocols, isServer); Interop.SspiCli.SCHANNEL_CRED.Flags flags; Interop.SspiCli.CredentialUse direction; if (!isServer) { direction = Interop.SspiCli.CredentialUse.SECPKG_CRED_OUTBOUND; flags = Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_CRED_MANUAL_CRED_VALIDATION | Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_CRED_NO_DEFAULT_CREDS | Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_SEND_AUX_RECORD; #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete // Always opt-in SCH_USE_STRONG_CRYPTO for TLS. if (((protocolFlags == 0) || (protocolFlags & ~(Interop.SChannel.SP_PROT_SSL2 | Interop.SChannel.SP_PROT_SSL3)) != 0) && (policy != EncryptionPolicy.AllowNoEncryption) && (policy != EncryptionPolicy.NoEncryption)) { flags |= Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_USE_STRONG_CRYPTO; } #pragma warning restore SYSLIB0040 } else { direction = Interop.SspiCli.CredentialUse.SECPKG_CRED_INBOUND; flags = Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_SEND_AUX_RECORD; if (certificateContext?.Trust?._sendTrustInHandshake == true) { flags |= Interop.SspiCli.SCHANNEL_CRED.Flags.SCH_CRED_NO_SYSTEM_MAPPER; } } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info($"flags=({flags}), ProtocolFlags=({protocolFlags}), EncryptionPolicy={policy}"); Interop.SspiCli.SCHANNEL_CRED secureCredential = CreateSecureCredential( flags, protocolFlags, policy); if (certificate != null) { secureCredential.cCreds = 1; Interop.Crypt32.CERT_CONTEXT* certificateHandle = (Interop.Crypt32.CERT_CONTEXT*)certificate.Handle; secureCredential.paCred = &certificateHandle; } return AcquireCredentialsHandle(direction, &secureCredential); } // This function uses new crypto API to support TLS 1.3 and beyond. public static unsafe SafeFreeCredentials AcquireCredentialsHandleSchCredentials(SslStreamCertificateContext? certificateContext, SslProtocols protocols, EncryptionPolicy policy, bool isServer) { X509Certificate2? certificate = certificateContext?.Certificate; int protocolFlags = GetProtocolFlagsFromSslProtocols(protocols, isServer); Interop.SspiCli.SCH_CREDENTIALS.Flags flags; Interop.SspiCli.CredentialUse direction; if (isServer) { direction = Interop.SspiCli.CredentialUse.SECPKG_CRED_INBOUND; flags = Interop.SspiCli.SCH_CREDENTIALS.Flags.SCH_SEND_AUX_RECORD; if (certificateContext?.Trust?._sendTrustInHandshake == true) { flags |= Interop.SspiCli.SCH_CREDENTIALS.Flags.SCH_CRED_NO_SYSTEM_MAPPER; } } else { direction = Interop.SspiCli.CredentialUse.SECPKG_CRED_OUTBOUND; flags = Interop.SspiCli.SCH_CREDENTIALS.Flags.SCH_CRED_MANUAL_CRED_VALIDATION | Interop.SspiCli.SCH_CREDENTIALS.Flags.SCH_CRED_NO_DEFAULT_CREDS | Interop.SspiCli.SCH_CREDENTIALS.Flags.SCH_SEND_AUX_RECORD; } if (policy == EncryptionPolicy.RequireEncryption) { // Always opt-in SCH_USE_STRONG_CRYPTO for TLS. if (!isServer && ((protocolFlags & Interop.SChannel.SP_PROT_SSL3) == 0)) { flags |= Interop.SspiCli.SCH_CREDENTIALS.Flags.SCH_USE_STRONG_CRYPTO; } } #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete else if (policy == EncryptionPolicy.AllowNoEncryption) { // Allow null encryption cipher in addition to other ciphers. flags |= Interop.SspiCli.SCH_CREDENTIALS.Flags.SCH_ALLOW_NULL_ENCRYPTION; } #pragma warning restore SYSLIB0040 else { throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), nameof(policy)); } Interop.SspiCli.SCH_CREDENTIALS credential = default; credential.dwVersion = Interop.SspiCli.SCH_CREDENTIALS.CurrentVersion; credential.dwFlags = flags; if (certificate != null) { credential.cCreds = 1; Interop.Crypt32.CERT_CONTEXT* certificateHandle = (Interop.Crypt32.CERT_CONTEXT*)certificate.Handle; credential.paCred = &certificateHandle; } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info($"flags=({flags}), ProtocolFlags=({protocolFlags}), EncryptionPolicy={policy}"); if (protocolFlags != 0) { // If we were asked to do specific protocol we need to fill TLS_PARAMETERS. Interop.SspiCli.TLS_PARAMETERS tlsParameters = default; tlsParameters.grbitDisabledProtocols = (uint)protocolFlags ^ uint.MaxValue; credential.cTlsParameters = 1; credential.pTlsParameters = &tlsParameters; } return AcquireCredentialsHandle(direction, &credential); } internal static byte[]? GetNegotiatedApplicationProtocol(SafeDeleteContext context) { Interop.SecPkgContext_ApplicationProtocol alpnContext = default; bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPISecureChannel, context, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_APPLICATION_PROTOCOL, ref alpnContext); // Check if the context returned is alpn data, with successful negotiation. if (success && alpnContext.ProtoNegoExt == Interop.ApplicationProtocolNegotiationExt.ALPN && alpnContext.ProtoNegoStatus == Interop.ApplicationProtocolNegotiationStatus.Success) { return alpnContext.Protocol; } return null; } public static unsafe SecurityStatusPal EncryptMessage(SafeDeleteSslContext securityContext, ReadOnlyMemory<byte> input, int headerSize, int trailerSize, ref byte[] output, out int resultSize) { // Ensure that there is sufficient space for the message output. int bufferSizeNeeded = checked(input.Length + headerSize + trailerSize); if (output == null || output.Length < bufferSizeNeeded) { output = new byte[bufferSizeNeeded]; } // Copy the input into the output buffer to prepare for SCHANNEL's expectations input.Span.CopyTo(new Span<byte>(output, headerSize, input.Length)); const int NumSecBuffers = 4; // header + data + trailer + empty Interop.SspiCli.SecBuffer* unmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[NumSecBuffers]; Interop.SspiCli.SecBufferDesc sdcInOut = new Interop.SspiCli.SecBufferDesc(NumSecBuffers) { pBuffers = unmanagedBuffer }; fixed (byte* outputPtr = output) { Interop.SspiCli.SecBuffer* headerSecBuffer = &unmanagedBuffer[0]; headerSecBuffer->BufferType = SecurityBufferType.SECBUFFER_STREAM_HEADER; headerSecBuffer->pvBuffer = (IntPtr)outputPtr; headerSecBuffer->cbBuffer = headerSize; Interop.SspiCli.SecBuffer* dataSecBuffer = &unmanagedBuffer[1]; dataSecBuffer->BufferType = SecurityBufferType.SECBUFFER_DATA; dataSecBuffer->pvBuffer = (IntPtr)(outputPtr + headerSize); dataSecBuffer->cbBuffer = input.Length; Interop.SspiCli.SecBuffer* trailerSecBuffer = &unmanagedBuffer[2]; trailerSecBuffer->BufferType = SecurityBufferType.SECBUFFER_STREAM_TRAILER; trailerSecBuffer->pvBuffer = (IntPtr)(outputPtr + headerSize + input.Length); trailerSecBuffer->cbBuffer = trailerSize; Interop.SspiCli.SecBuffer* emptySecBuffer = &unmanagedBuffer[3]; emptySecBuffer->BufferType = SecurityBufferType.SECBUFFER_EMPTY; emptySecBuffer->cbBuffer = 0; emptySecBuffer->pvBuffer = IntPtr.Zero; int errorCode = GlobalSSPI.SSPISecureChannel.EncryptMessage(securityContext, ref sdcInOut, 0); if (errorCode != 0) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(securityContext, $"Encrypt ERROR {errorCode:X}"); resultSize = 0; return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode); } Debug.Assert(headerSecBuffer->cbBuffer >= 0 && dataSecBuffer->cbBuffer >= 0 && trailerSecBuffer->cbBuffer >= 0); Debug.Assert(checked(headerSecBuffer->cbBuffer + dataSecBuffer->cbBuffer + trailerSecBuffer->cbBuffer) <= output.Length); resultSize = checked(headerSecBuffer->cbBuffer + dataSecBuffer->cbBuffer + trailerSecBuffer->cbBuffer); return new SecurityStatusPal(SecurityStatusPalErrorCode.OK); } } public static unsafe SecurityStatusPal DecryptMessage(SafeDeleteSslContext? securityContext, Span<byte> buffer, out int offset, out int count) { const int NumSecBuffers = 4; // data + empty + empty + empty fixed (byte* bufferPtr = buffer) { Interop.SspiCli.SecBuffer* unmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[NumSecBuffers]; Interop.SspiCli.SecBuffer* dataBuffer = &unmanagedBuffer[0]; dataBuffer->BufferType = SecurityBufferType.SECBUFFER_DATA; dataBuffer->pvBuffer = (IntPtr)bufferPtr; dataBuffer->cbBuffer = buffer.Length; for (int i = 1; i < NumSecBuffers; i++) { Interop.SspiCli.SecBuffer* emptyBuffer = &unmanagedBuffer[i]; emptyBuffer->BufferType = SecurityBufferType.SECBUFFER_EMPTY; emptyBuffer->pvBuffer = IntPtr.Zero; emptyBuffer->cbBuffer = 0; } Interop.SspiCli.SecBufferDesc sdcInOut = new Interop.SspiCli.SecBufferDesc(NumSecBuffers) { pBuffers = unmanagedBuffer }; Interop.SECURITY_STATUS errorCode = (Interop.SECURITY_STATUS)GlobalSSPI.SSPISecureChannel.DecryptMessage(securityContext!, ref sdcInOut, 0); // Decrypt may repopulate the sec buffers, likely with header + data + trailer + empty. // We need to find the data. count = 0; offset = 0; for (int i = 0; i < NumSecBuffers; i++) { // Successfully decoded data and placed it at the following position in the buffer, if ((errorCode == Interop.SECURITY_STATUS.OK && unmanagedBuffer[i].BufferType == SecurityBufferType.SECBUFFER_DATA) // or we failed to decode the data, here is the encoded data. || (errorCode != Interop.SECURITY_STATUS.OK && unmanagedBuffer[i].BufferType == SecurityBufferType.SECBUFFER_EXTRA)) { offset = (int)((byte*)unmanagedBuffer[i].pvBuffer - bufferPtr); count = unmanagedBuffer[i].cbBuffer; // output is ignored on Windows. We always decrypt in place and we set outputOffset to indicate where the data start. Debug.Assert(offset >= 0 && count >= 0, $"Expected offset and count greater than 0, got {offset} and {count}"); Debug.Assert(checked(offset + count) <= buffer.Length, $"Expected offset+count <= buffer.Length, got {offset}+{count}>={buffer.Length}"); break; } } return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode); } } public static SecurityStatusPal ApplyAlertToken(ref SafeFreeCredentials? credentialsHandle, SafeDeleteContext? securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage) { var alertToken = new Interop.SChannel.SCHANNEL_ALERT_TOKEN { dwTokenType = Interop.SChannel.SCHANNEL_ALERT, dwAlertType = (uint)alertType, dwAlertNumber = (uint)alertMessage }; byte[] buffer = MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref alertToken, 1)).ToArray(); var securityBuffer = new SecurityBuffer(buffer, SecurityBufferType.SECBUFFER_TOKEN); var errorCode = (Interop.SECURITY_STATUS)SSPIWrapper.ApplyControlToken( GlobalSSPI.SSPISecureChannel, ref securityContext, in securityBuffer); return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode, attachException: true); } private static readonly byte[] s_schannelShutdownBytes = BitConverter.GetBytes(Interop.SChannel.SCHANNEL_SHUTDOWN); public static SecurityStatusPal ApplyShutdownToken(ref SafeFreeCredentials? credentialsHandle, SafeDeleteContext? securityContext) { var securityBuffer = new SecurityBuffer(s_schannelShutdownBytes, SecurityBufferType.SECBUFFER_TOKEN); var errorCode = (Interop.SECURITY_STATUS)SSPIWrapper.ApplyControlToken( GlobalSSPI.SSPISecureChannel, ref securityContext, in securityBuffer); return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode, attachException: true); } public static SafeFreeContextBufferChannelBinding? QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute) { return SSPIWrapper.QueryContextChannelBinding(GlobalSSPI.SSPISecureChannel, securityContext, (Interop.SspiCli.ContextAttribute)attribute); } public static void QueryContextStreamSizes(SafeDeleteContext securityContext, out StreamSizes streamSizes) { SecPkgContext_StreamSizes interopStreamSizes = default; bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_STREAM_SIZES, ref interopStreamSizes); Debug.Assert(success); streamSizes = new StreamSizes(interopStreamSizes); } public static void QueryContextConnectionInfo(SafeDeleteContext securityContext, out SslConnectionInfo connectionInfo) { SecPkgContext_ConnectionInfo interopConnectionInfo = default; bool success = SSPIWrapper.QueryBlittableContextAttributes( GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CONNECTION_INFO, ref interopConnectionInfo); Debug.Assert(success); TlsCipherSuite cipherSuite = default; SecPkgContext_CipherInfo cipherInfo = default; success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CIPHER_INFO, ref cipherInfo); if (success) { cipherSuite = (TlsCipherSuite)cipherInfo.dwCipherSuite; } connectionInfo = new SslConnectionInfo(interopConnectionInfo, cipherSuite); } private static int GetProtocolFlagsFromSslProtocols(SslProtocols protocols, bool isServer) { int protocolFlags = (int)protocols; if (isServer) { protocolFlags &= Interop.SChannel.ServerProtocolMask; } else { protocolFlags &= Interop.SChannel.ClientProtocolMask; } return protocolFlags; } private static Interop.SspiCli.SCHANNEL_CRED CreateSecureCredential( Interop.SspiCli.SCHANNEL_CRED.Flags flags, int protocols, EncryptionPolicy policy) { var credential = new Interop.SspiCli.SCHANNEL_CRED() { hRootStore = IntPtr.Zero, aphMappers = IntPtr.Zero, palgSupportedAlgs = IntPtr.Zero, paCred = null, cCreds = 0, cMappers = 0, cSupportedAlgs = 0, dwSessionLifespan = 0, reserved = 0, dwVersion = Interop.SspiCli.SCHANNEL_CRED.CurrentVersion }; if (policy == EncryptionPolicy.RequireEncryption) { // Prohibit null encryption cipher. credential.dwMinimumCipherStrength = 0; credential.dwMaximumCipherStrength = 0; } #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete else if (policy == EncryptionPolicy.AllowNoEncryption) { // Allow null encryption cipher in addition to other ciphers. credential.dwMinimumCipherStrength = -1; credential.dwMaximumCipherStrength = 0; } else if (policy == EncryptionPolicy.NoEncryption) { // Suppress all encryption and require null encryption cipher only credential.dwMinimumCipherStrength = -1; credential.dwMaximumCipherStrength = -1; } #pragma warning restore SYSLIB0040 else { throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), nameof(policy)); } credential.dwFlags = flags; credential.grbitEnabledProtocols = protocols; return credential; } // // Security: we temporarily reset thread token to open the handle under process account. // private static unsafe SafeFreeCredentials AcquireCredentialsHandle(Interop.SspiCli.CredentialUse credUsage, Interop.SspiCli.SCHANNEL_CRED* secureCredential) { // First try without impersonation, if it fails, then try the process account. // I.E. We don't know which account the certificate context was created under. try { // // For app-compat we want to ensure the credential are accessed under >>process<< account. // return WindowsIdentity.RunImpersonated<SafeFreeCredentials>(SafeAccessTokenHandle.InvalidHandle, () => { return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential); }); } catch { return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential); } } private static unsafe SafeFreeCredentials AcquireCredentialsHandle(Interop.SspiCli.CredentialUse credUsage, Interop.SspiCli.SCH_CREDENTIALS* secureCredential) { // First try without impersonation, if it fails, then try the process account. // I.E. We don't know which account the certificate context was created under. try { // // For app-compat we want to ensure the credential are accessed under >>process<< account. // return WindowsIdentity.RunImpersonated<SafeFreeCredentials>(SafeAccessTokenHandle.InvalidHandle, () => { return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential); }); } catch { return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential); } } } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/tests/FunctionalTests/ClientAsyncAuthenticateTest.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.Net.Test.Common; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Security.Tests { public class ClientAsyncAuthenticateTest { private readonly ITestOutputHelper _log; public ClientAsyncAuthenticateTest(ITestOutputHelper output) { _log = output; } [Fact] public async Task ClientAsyncAuthenticate_ServerRequireEncryption_ConnectWithEncryption() { await ClientAsyncSslHelper(EncryptionPolicy.RequireEncryption); } [Fact] public async Task ClientAsyncAuthenticate_ConnectionInfoInCallback_DoesNotThrow() { await ClientAsyncSslHelper(EncryptionPolicy.RequireEncryption, SslProtocols.Tls12, SslProtocolSupport.DefaultSslProtocols, AllowAnyServerCertificateAndVerifyConnectionInfo); } [Fact] public async Task ClientAsyncAuthenticate_ServerNoEncryption_NoConnect() { // Don't use Tls13 since we are trying to use NullEncryption await Assert.ThrowsAsync<AuthenticationException>( () => ClientAsyncSslHelper( EncryptionPolicy.NoEncryption, #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete SslProtocolSupport.DefaultSslProtocols, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)); #pragma warning restore SYSLIB0039 } [Theory] [ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))] public async Task ClientAsyncAuthenticate_EachSupportedProtocol_Success(SslProtocols protocol) { await ClientAsyncSslHelper(protocol, protocol); } [Theory] [MemberData(nameof(ProtocolMismatchData))] public async Task ClientAsyncAuthenticate_MismatchProtocols_Fails( SslProtocols clientProtocol, SslProtocols serverProtocol, Type expectedException) { Exception e = await Record.ExceptionAsync(() => ClientAsyncSslHelper(clientProtocol, serverProtocol)); Assert.NotNull(e); Assert.IsAssignableFrom(expectedException, e); } [Fact] public async Task ClientAsyncAuthenticate_AllServerAllClient_Success() { await ClientAsyncSslHelper( SslProtocolSupport.SupportedSslProtocols, SslProtocolSupport.SupportedSslProtocols); } [Theory] [ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))] public async Task ClientAsyncAuthenticate_AllServerVsIndividualClientSupportedProtocols_Success( SslProtocols clientProtocol) { await ClientAsyncSslHelper(clientProtocol, SslProtocolSupport.SupportedSslProtocols); } [Theory] [ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))] public async Task ClientAsyncAuthenticate_IndividualServerVsAllClientSupportedProtocols_Success( SslProtocols serverProtocol) { await ClientAsyncSslHelper(SslProtocolSupport.SupportedSslProtocols, serverProtocol); // Cached Tls creds fail when used against Tls servers of higher versions. // Servers are not expected to dynamically change versions. } public static IEnumerable<object[]> ProtocolMismatchData() { var supportedProtocols = new SslProtocolSupport.SupportedSslProtocolsTestData(); foreach (var serverProtocols in supportedProtocols) { foreach (var clientProtocols in supportedProtocols) { SslProtocols serverProtocol = (SslProtocols)serverProtocols[0]; SslProtocols clientProtocol = (SslProtocols)clientProtocols[0]; if (clientProtocol != serverProtocol) { yield return new object[] { clientProtocol, serverProtocol, typeof(AuthenticationException) }; } } } } #region Helpers private Task ClientAsyncSslHelper(EncryptionPolicy encryptionPolicy) { return ClientAsyncSslHelper(encryptionPolicy, SslProtocolSupport.DefaultSslProtocols, SslProtocolSupport.DefaultSslProtocols); } private Task ClientAsyncSslHelper(SslProtocols clientSslProtocols, SslProtocols serverSslProtocols) { return ClientAsyncSslHelper(EncryptionPolicy.RequireEncryption, clientSslProtocols, serverSslProtocols); } private async Task ClientAsyncSslHelper( EncryptionPolicy encryptionPolicy, SslProtocols clientSslProtocols, SslProtocols serverSslProtocols, RemoteCertificateValidationCallback certificateCallback = null) { _log.WriteLine("Server: " + serverSslProtocols + "; Client: " + clientSslProtocols); (SslStream client, SslStream server) = TestHelper.GetConnectedSslStreams(); using (client) using (server) { // Use a different SNI for each connection to prevent TLS 1.3 renegotiation issue: https://github.com/dotnet/runtime/issues/47378 string serverName = TestHelper.GetTestSNIName(nameof(ClientAsyncSslHelper), clientSslProtocols, serverSslProtocols); Task serverTask = default; try { Task clientTask = client.AuthenticateAsClientAsync(new SslClientAuthenticationOptions { EnabledSslProtocols = clientSslProtocols, RemoteCertificateValidationCallback = AllowAnyServerCertificate, TargetHost = serverName }); serverTask = server.AuthenticateAsServerAsync( new SslServerAuthenticationOptions { EncryptionPolicy = encryptionPolicy, EnabledSslProtocols = serverSslProtocols, ServerCertificate = TestConfiguration.ServerCertificate, CertificateRevocationCheckMode = X509RevocationMode.NoCheck }); await clientTask.WaitAsync(TestConfiguration.PassingTestTimeout); _log.WriteLine("Client authenticated to server with encryption cipher: {0} {1}-bit strength", client.CipherAlgorithm, client.CipherStrength); Assert.True(client.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL"); Assert.True(client.CipherStrength > 0, "Cipher strength should be greater than 0"); } finally { // make sure we signal server in case of client failures client.Close(); try { await serverTask; } catch (Exception ex) { // We generally don't care about server but can log exception to help diagnose test failures _log.WriteLine(ex.ToString()); } } } } // The following method is invoked by the RemoteCertificateValidationDelegate. private bool AllowAnyServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; // allow everything } private bool AllowAnyServerCertificateAndVerifyConnectionInfo( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { SslStream stream = (SslStream)sender; Assert.NotEqual(SslProtocols.None, stream.SslProtocol); Assert.NotEqual(CipherAlgorithmType.None, stream.CipherAlgorithm); return true; // allow everything } #endregion Helpers } }
// 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.Net.Test.Common; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Security.Tests { public class ClientAsyncAuthenticateTest { private readonly ITestOutputHelper _log; public ClientAsyncAuthenticateTest(ITestOutputHelper output) { _log = output; } [Fact] public async Task ClientAsyncAuthenticate_ServerRequireEncryption_ConnectWithEncryption() { await ClientAsyncSslHelper(EncryptionPolicy.RequireEncryption); } [Fact] public async Task ClientAsyncAuthenticate_ConnectionInfoInCallback_DoesNotThrow() { await ClientAsyncSslHelper(EncryptionPolicy.RequireEncryption, SslProtocols.Tls12, SslProtocolSupport.DefaultSslProtocols, AllowAnyServerCertificateAndVerifyConnectionInfo); } [Fact] public async Task ClientAsyncAuthenticate_ServerNoEncryption_NoConnect() { // Don't use Tls13 since we are trying to use NullEncryption await Assert.ThrowsAsync<AuthenticationException>( () => ClientAsyncSslHelper( #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete EncryptionPolicy.NoEncryption, #pragma warning restore SYSLIB0040 #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete SslProtocolSupport.DefaultSslProtocols, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)); #pragma warning restore SYSLIB0039 } [Theory] [ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))] public async Task ClientAsyncAuthenticate_EachSupportedProtocol_Success(SslProtocols protocol) { await ClientAsyncSslHelper(protocol, protocol); } [Theory] [MemberData(nameof(ProtocolMismatchData))] public async Task ClientAsyncAuthenticate_MismatchProtocols_Fails( SslProtocols clientProtocol, SslProtocols serverProtocol, Type expectedException) { Exception e = await Record.ExceptionAsync(() => ClientAsyncSslHelper(clientProtocol, serverProtocol)); Assert.NotNull(e); Assert.IsAssignableFrom(expectedException, e); } [Fact] public async Task ClientAsyncAuthenticate_AllServerAllClient_Success() { await ClientAsyncSslHelper( SslProtocolSupport.SupportedSslProtocols, SslProtocolSupport.SupportedSslProtocols); } [Theory] [ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))] public async Task ClientAsyncAuthenticate_AllServerVsIndividualClientSupportedProtocols_Success( SslProtocols clientProtocol) { await ClientAsyncSslHelper(clientProtocol, SslProtocolSupport.SupportedSslProtocols); } [Theory] [ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))] public async Task ClientAsyncAuthenticate_IndividualServerVsAllClientSupportedProtocols_Success( SslProtocols serverProtocol) { await ClientAsyncSslHelper(SslProtocolSupport.SupportedSslProtocols, serverProtocol); // Cached Tls creds fail when used against Tls servers of higher versions. // Servers are not expected to dynamically change versions. } public static IEnumerable<object[]> ProtocolMismatchData() { var supportedProtocols = new SslProtocolSupport.SupportedSslProtocolsTestData(); foreach (var serverProtocols in supportedProtocols) { foreach (var clientProtocols in supportedProtocols) { SslProtocols serverProtocol = (SslProtocols)serverProtocols[0]; SslProtocols clientProtocol = (SslProtocols)clientProtocols[0]; if (clientProtocol != serverProtocol) { yield return new object[] { clientProtocol, serverProtocol, typeof(AuthenticationException) }; } } } } #region Helpers private Task ClientAsyncSslHelper(EncryptionPolicy encryptionPolicy) { return ClientAsyncSslHelper(encryptionPolicy, SslProtocolSupport.DefaultSslProtocols, SslProtocolSupport.DefaultSslProtocols); } private Task ClientAsyncSslHelper(SslProtocols clientSslProtocols, SslProtocols serverSslProtocols) { return ClientAsyncSslHelper(EncryptionPolicy.RequireEncryption, clientSslProtocols, serverSslProtocols); } private async Task ClientAsyncSslHelper( EncryptionPolicy encryptionPolicy, SslProtocols clientSslProtocols, SslProtocols serverSslProtocols, RemoteCertificateValidationCallback certificateCallback = null) { _log.WriteLine("Server: " + serverSslProtocols + "; Client: " + clientSslProtocols); (SslStream client, SslStream server) = TestHelper.GetConnectedSslStreams(); using (client) using (server) { // Use a different SNI for each connection to prevent TLS 1.3 renegotiation issue: https://github.com/dotnet/runtime/issues/47378 string serverName = TestHelper.GetTestSNIName(nameof(ClientAsyncSslHelper), clientSslProtocols, serverSslProtocols); Task serverTask = default; try { Task clientTask = client.AuthenticateAsClientAsync(new SslClientAuthenticationOptions { EnabledSslProtocols = clientSslProtocols, RemoteCertificateValidationCallback = AllowAnyServerCertificate, TargetHost = serverName }); serverTask = server.AuthenticateAsServerAsync( new SslServerAuthenticationOptions { EncryptionPolicy = encryptionPolicy, EnabledSslProtocols = serverSslProtocols, ServerCertificate = TestConfiguration.ServerCertificate, CertificateRevocationCheckMode = X509RevocationMode.NoCheck }); await clientTask.WaitAsync(TestConfiguration.PassingTestTimeout); _log.WriteLine("Client authenticated to server with encryption cipher: {0} {1}-bit strength", client.CipherAlgorithm, client.CipherStrength); Assert.True(client.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL"); Assert.True(client.CipherStrength > 0, "Cipher strength should be greater than 0"); } finally { // make sure we signal server in case of client failures client.Close(); try { await serverTask; } catch (Exception ex) { // We generally don't care about server but can log exception to help diagnose test failures _log.WriteLine(ex.ToString()); } } } } // The following method is invoked by the RemoteCertificateValidationDelegate. private bool AllowAnyServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; // allow everything } private bool AllowAnyServerCertificateAndVerifyConnectionInfo( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { SslStream stream = (SslStream)sender; Assert.NotEqual(SslProtocols.None, stream.SslProtocol); Assert.NotEqual(CipherAlgorithmType.None, stream.CipherAlgorithm); return true; // allow everything } #endregion Helpers } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/tests/FunctionalTests/ClientDefaultEncryptionTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net.Sockets; using System.Net.Test.Common; using System.Security.Authentication; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Security.Tests { public class ClientDefaultEncryptionTest { private readonly ITestOutputHelper _log; public ClientDefaultEncryptionTest(ITestOutputHelper output) { _log = output; } [Fact] public async Task ClientDefaultEncryption_ServerRequireEncryption_ConnectWithEncryption() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null)) using (var server = new SslStream(serverStream)) { await TestConfiguration.WhenAllOrAnyFailedWithTimeout( client.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false), server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate)); _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", clientStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength) ; Assert.True(client.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL"); Assert.True(client.CipherStrength > 0, "Cipher strength should be greater than 0"); } } } [Fact] public async Task ClientDefaultEncryption_ServerAllowNoEncryption_ConnectWithEncryption() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null)) using (var server = new SslStream(serverStream)) { await TestConfiguration.WhenAllOrAnyFailedWithTimeout( client.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false), server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate)); _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", clientStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength); Assert.True(client.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL"); Assert.True(client.CipherStrength > 0, "Cipher strength should be greater than 0"); } } } [Fact] public async Task ClientDefaultEncryption_ServerNoEncryption_NoConnect() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null)) using (var server = new SslStream(serverStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption)) { Task serverTask = server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate); await Assert.ThrowsAsync<AuthenticationException>(() => client.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false)); try { await serverTask.WaitAsync(TestConfiguration.PassingTestTimeout); } catch (Exception ex) { // serverTask will fail. // We generally don't care but can log exception to help diagnose test failures _log.WriteLine(ex.ToString()); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net.Sockets; using System.Net.Test.Common; using System.Security.Authentication; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Security.Tests { public class ClientDefaultEncryptionTest { private readonly ITestOutputHelper _log; public ClientDefaultEncryptionTest(ITestOutputHelper output) { _log = output; } [Fact] public async Task ClientDefaultEncryption_ServerRequireEncryption_ConnectWithEncryption() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null)) using (var server = new SslStream(serverStream)) { await TestConfiguration.WhenAllOrAnyFailedWithTimeout( client.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false), server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate)); _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", clientStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength) ; Assert.True(client.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL"); Assert.True(client.CipherStrength > 0, "Cipher strength should be greater than 0"); } } } [Fact] public async Task ClientDefaultEncryption_ServerAllowNoEncryption_ConnectWithEncryption() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null)) using (var server = new SslStream(serverStream)) { await TestConfiguration.WhenAllOrAnyFailedWithTimeout( client.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false), server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate)); _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", clientStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength); Assert.True(client.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL"); Assert.True(client.CipherStrength > 0, "Cipher strength should be greater than 0"); } } } [Fact] public async Task ClientDefaultEncryption_ServerNoEncryption_NoConnect() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null)) #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete using (var server = new SslStream(serverStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption)) #pragma warning restore SYSLIB0040 { Task serverTask = server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate); await Assert.ThrowsAsync<AuthenticationException>(() => client.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false)); try { await serverTask.WaitAsync(TestConfiguration.PassingTestTimeout); } catch (Exception ex) { // serverTask will fail. // We generally don't care but can log exception to help diagnose test failures _log.WriteLine(ex.ToString()); } } } } } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/tests/FunctionalTests/ServerAllowNoEncryptionTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net.Sockets; using System.Security.Authentication; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Security.Tests { public class ServerAllowNoEncryptionTest { private readonly ITestOutputHelper _log; public ServerAllowNoEncryptionTest(ITestOutputHelper output) { _log = output; } [Fact] public async Task ServerAllowNoEncryption_ClientRequireEncryption_ConnectWithEncryption() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.RequireEncryption)) using (var server = new SslStream(serverStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.AllowNoEncryption)) { await TestConfiguration.WhenAllOrAnyFailedWithTimeout( client.AuthenticateAsClientAsync("localhost", null, SslProtocols.None, false), server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate)); _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", clientStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength); Assert.NotEqual(CipherAlgorithmType.Null, client.CipherAlgorithm); Assert.True(client.CipherStrength > 0); } } } [Fact] public async Task ServerAllowNoEncryption_ClientAllowNoEncryption_ConnectWithEncryption() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.AllowNoEncryption)) using (var server = new SslStream(serverStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.AllowNoEncryption)) { await TestConfiguration.WhenAllOrAnyFailedWithTimeout( client.AuthenticateAsClientAsync("localhost", null, SslProtocols.None, false), server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate)); _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", clientStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength); Assert.NotEqual(CipherAlgorithmType.Null, client.CipherAlgorithm); Assert.True(client.CipherStrength > 0, "Cipher strength should be greater than 0"); } } } [ConditionalFact(typeof(TestConfiguration), nameof(TestConfiguration.SupportsNullEncryption))] public async Task ServerAllowNoEncryption_ClientNoEncryption_ConnectWithNoEncryption() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption)) using (var server = new SslStream(serverStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.AllowNoEncryption)) { #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete await TestConfiguration.WhenAllOrAnyFailedWithTimeout( // null encryption is not permitted with Tls13 client.AuthenticateAsClientAsync("localhost", null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false), server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate)); #pragma warning restore SYSLIB0039 _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", clientStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength); CipherAlgorithmType expected = CipherAlgorithmType.Null; Assert.Equal(expected, client.CipherAlgorithm); Assert.Equal(0, client.CipherStrength); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net.Sockets; using System.Security.Authentication; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Security.Tests { public class ServerAllowNoEncryptionTest { private readonly ITestOutputHelper _log; public ServerAllowNoEncryptionTest(ITestOutputHelper output) { _log = output; } [Fact] public async Task ServerAllowNoEncryption_ClientRequireEncryption_ConnectWithEncryption() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.RequireEncryption)) #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete using (var server = new SslStream(serverStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.AllowNoEncryption)) #pragma warning restore SYSLIB0040 { await TestConfiguration.WhenAllOrAnyFailedWithTimeout( client.AuthenticateAsClientAsync("localhost", null, SslProtocols.None, false), server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate)); _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", clientStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength); Assert.NotEqual(CipherAlgorithmType.Null, client.CipherAlgorithm); Assert.True(client.CipherStrength > 0); } } } [Fact] public async Task ServerAllowNoEncryption_ClientAllowNoEncryption_ConnectWithEncryption() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.AllowNoEncryption)) using (var server = new SslStream(serverStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.AllowNoEncryption)) #pragma warning restore SYSLIB0040 { await TestConfiguration.WhenAllOrAnyFailedWithTimeout( client.AuthenticateAsClientAsync("localhost", null, SslProtocols.None, false), server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate)); _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", clientStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength); Assert.NotEqual(CipherAlgorithmType.Null, client.CipherAlgorithm); Assert.True(client.CipherStrength > 0, "Cipher strength should be greater than 0"); } } } [ConditionalFact(typeof(TestConfiguration), nameof(TestConfiguration.SupportsNullEncryption))] public async Task ServerAllowNoEncryption_ClientNoEncryption_ConnectWithNoEncryption() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption)) using (var server = new SslStream(serverStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.AllowNoEncryption)) #pragma warning restore SYSLIB0040 { #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete await TestConfiguration.WhenAllOrAnyFailedWithTimeout( // null encryption is not permitted with Tls13 client.AuthenticateAsClientAsync("localhost", null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false), server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate)); #pragma warning restore SYSLIB0039 _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", clientStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength); CipherAlgorithmType expected = CipherAlgorithmType.Null; Assert.Equal(expected, client.CipherAlgorithm); Assert.Equal(0, client.CipherStrength); } } } } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/tests/FunctionalTests/ServerNoEncryptionTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Net.Sockets; using System.Net.Test.Common; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Security.Tests { public class ServerNoEncryptionTest { private readonly ITestOutputHelper _log; public ServerNoEncryptionTest(ITestOutputHelper output) { _log = output; } [ConditionalFact(typeof(TestConfiguration), nameof(TestConfiguration.SupportsNullEncryption))] public async Task ServerNoEncryption_ClientRequireEncryption_NoConnect() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.RequireEncryption)) using (var server = new SslStream(serverStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption)) { Task serverTask = server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate); await Assert.ThrowsAsync<AuthenticationException>(() => client.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false)); try { await serverTask; } catch (Exception ex) { // serverTask will fail. Log server error in case the test fails. _log.WriteLine(ex.ToString()); } } } } [ConditionalTheory(typeof(TestConfiguration), nameof(TestConfiguration.SupportsNullEncryption))] [InlineData(EncryptionPolicy.AllowNoEncryption)] [InlineData(EncryptionPolicy.NoEncryption)] public async Task ServerNoEncryption_ClientPermitsNoEncryption_ConnectWithNoEncryption(EncryptionPolicy policy) { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, policy)) using (var server = new SslStream(serverStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption)) { #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete await TestConfiguration.WhenAllOrAnyFailedWithTimeout( // null encryption is not permitted with Tls13 client.AuthenticateAsClientAsync("localhost", null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false), server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate)); #pragma warning restore SYSLIB0039 _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", serverStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength); Assert.Equal(CipherAlgorithmType.Null, client.CipherAlgorithm); Assert.Equal(0, client.CipherStrength); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Net.Sockets; using System.Net.Test.Common; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Security.Tests { public class ServerNoEncryptionTest { private readonly ITestOutputHelper _log; public ServerNoEncryptionTest(ITestOutputHelper output) { _log = output; } [ConditionalFact(typeof(TestConfiguration), nameof(TestConfiguration.SupportsNullEncryption))] public async Task ServerNoEncryption_ClientRequireEncryption_NoConnect() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.RequireEncryption)) #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete using (var server = new SslStream(serverStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption)) #pragma warning restore SYSLIB0040 { Task serverTask = server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate); await Assert.ThrowsAsync<AuthenticationException>(() => client.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false)); try { await serverTask; } catch (Exception ex) { // serverTask will fail. Log server error in case the test fails. _log.WriteLine(ex.ToString()); } } } } [ConditionalTheory(typeof(TestConfiguration), nameof(TestConfiguration.SupportsNullEncryption))] #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete [InlineData(EncryptionPolicy.AllowNoEncryption)] [InlineData(EncryptionPolicy.NoEncryption)] #pragma warning restore SYSLIB0040 public async Task ServerNoEncryption_ClientPermitsNoEncryption_ConnectWithNoEncryption(EncryptionPolicy policy) { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, policy)) #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete using (var server = new SslStream(serverStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption)) #pragma warning restore SYSLIB0040 { #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete await TestConfiguration.WhenAllOrAnyFailedWithTimeout( // null encryption is not permitted with Tls13 client.AuthenticateAsClientAsync("localhost", null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false), server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate)); #pragma warning restore SYSLIB0039 _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", serverStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength); Assert.Equal(CipherAlgorithmType.Null, client.CipherAlgorithm); Assert.Equal(0, client.CipherStrength); } } } } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/tests/FunctionalTests/ServerRequireEncryptionTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Net.Sockets; using System.Net.Test.Common; using System.Security.Authentication; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Security.Tests { public class ServerRequireEncryptionTest { private readonly ITestOutputHelper _log; public ServerRequireEncryptionTest(ITestOutputHelper output) { _log = output; } [Fact] public async Task ServerRequireEncryption_ClientRequireEncryption_ConnectWithEncryption() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.RequireEncryption)) using (var server = new SslStream(serverStream)) { await TestConfiguration.WhenAllOrAnyFailedWithTimeout( client.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false), server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate)); _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", clientStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength); Assert.True(client.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL"); Assert.True(client.CipherStrength > 0, "Cipher strength should be greater than 0"); } } } [Fact] public async Task ServerRequireEncryption_ClientAllowNoEncryption_ConnectWithEncryption() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.AllowNoEncryption)) using (var server = new SslStream(serverStream)) { await TestConfiguration.WhenAllOrAnyFailedWithTimeout( client.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false), server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate)); _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", clientStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength); Assert.True(client.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL"); Assert.True(client.CipherStrength > 0, "Cipher strength should be greater than 0"); } } } [ConditionalFact(typeof(TestConfiguration), nameof(TestConfiguration.SupportsNullEncryption))] public async Task ServerRequireEncryption_ClientNoEncryption_NoConnect() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption)) using (var server = new SslStream(serverStream)) { Task serverTask = server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate); #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete await Assert.ThrowsAsync(TestConfiguration.SupportsHandshakeAlerts ? typeof(AuthenticationException) : typeof(IOException), () => client.AuthenticateAsClientAsync("localhost", null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false)); #pragma warning restore SYSLIB0039 try { await serverTask.WaitAsync(TestConfiguration.PassingTestTimeout); } catch (Exception ex) { // This will fail. Log server error in case test fails. _log.WriteLine(ex.ToString()); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Net.Sockets; using System.Net.Test.Common; using System.Security.Authentication; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Security.Tests { public class ServerRequireEncryptionTest { private readonly ITestOutputHelper _log; public ServerRequireEncryptionTest(ITestOutputHelper output) { _log = output; } [Fact] public async Task ServerRequireEncryption_ClientRequireEncryption_ConnectWithEncryption() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.RequireEncryption)) using (var server = new SslStream(serverStream)) { await TestConfiguration.WhenAllOrAnyFailedWithTimeout( client.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false), server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate)); _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", clientStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength); Assert.True(client.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL"); Assert.True(client.CipherStrength > 0, "Cipher strength should be greater than 0"); } } } [Fact] public async Task ServerRequireEncryption_ClientAllowNoEncryption_ConnectWithEncryption() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.AllowNoEncryption)) #pragma warning restore SYSLIB0040 using (var server = new SslStream(serverStream)) { await TestConfiguration.WhenAllOrAnyFailedWithTimeout( client.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false), server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate)); _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", clientStream.Socket.RemoteEndPoint, client.CipherAlgorithm, client.CipherStrength); Assert.True(client.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL"); Assert.True(client.CipherStrength > 0, "Cipher strength should be greater than 0"); } } } [ConditionalFact(typeof(TestConfiguration), nameof(TestConfiguration.SupportsNullEncryption))] public async Task ServerRequireEncryption_ClientNoEncryption_NoConnect() { (NetworkStream clientStream, NetworkStream serverStream) = TestHelper.GetConnectedTcpStreams(); using (clientStream) using (serverStream) { #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete using (var client = new SslStream(clientStream, false, TestHelper.AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption)) #pragma warning restore SYSLIB0040 using (var server = new SslStream(serverStream)) { Task serverTask = server.AuthenticateAsServerAsync(TestConfiguration.ServerCertificate); #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete await Assert.ThrowsAsync(TestConfiguration.SupportsHandshakeAlerts ? typeof(AuthenticationException) : typeof(IOException), () => client.AuthenticateAsClientAsync("localhost", null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false)); #pragma warning restore SYSLIB0039 try { await serverTask.WaitAsync(TestConfiguration.PassingTestTimeout); } catch (Exception ex) { // This will fail. Log server error in case test fails. _log.WriteLine(ex.ToString()); } } } } } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/tests/FunctionalTests/SslAuthenticationOptionsTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Test.Common; using System.Security.Cryptography.X509Certificates; using System.Security.Authentication; using System.Threading.Tasks; using Xunit; namespace System.Net.Security.Tests { using Configuration = System.Net.Test.Common.Configuration; public abstract class SslClientAuthenticationOptionsTestBase { protected abstract bool TestAuthenticateAsync { get; } [Fact] public async Task ClientOptions_ServerOptions_NotMutatedDuringAuthentication() { using (X509Certificate2 clientCert = Configuration.Certificates.GetClientCertificate()) using (X509Certificate2 serverCert = Configuration.Certificates.GetServerCertificate()) { // Values used to populate client options bool clientAllowRenegotiation = false; List<SslApplicationProtocol> clientAppProtocols = new List<SslApplicationProtocol> { SslApplicationProtocol.Http11 }; X509RevocationMode clientRevocation = X509RevocationMode.NoCheck; X509CertificateCollection clientCertificates = new X509CertificateCollection() { clientCert }; SslProtocols clientSslProtocols = SslProtocols.Tls12; EncryptionPolicy clientEncryption = EncryptionPolicy.RequireEncryption; LocalCertificateSelectionCallback clientLocalCallback = new LocalCertificateSelectionCallback(delegate { return null; }); RemoteCertificateValidationCallback clientRemoteCallback = new RemoteCertificateValidationCallback(delegate { return true; }); string clientHost = serverCert.GetNameInfo(X509NameType.SimpleName, false); // Values used to populate server options bool serverAllowRenegotiation = true; List<SslApplicationProtocol> serverAppProtocols = new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }; X509RevocationMode serverRevocation = X509RevocationMode.NoCheck; bool serverCertRequired = false; #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete SslProtocols serverSslProtocols = SslProtocols.Tls11 | SslProtocols.Tls12; #pragma warning restore SYSLIB0039 EncryptionPolicy serverEncryption = EncryptionPolicy.AllowNoEncryption; RemoteCertificateValidationCallback serverRemoteCallback = new RemoteCertificateValidationCallback(delegate { return true; }); SslStreamCertificateContext certificateContext = SslStreamCertificateContext.Create(serverCert, null, false); (Stream stream1, Stream stream2) = TestHelper.GetConnectedStreams(); using (var client = new SslStream(stream1)) using (var server = new SslStream(stream2)) { // Create client options var clientOptions = new SslClientAuthenticationOptions { AllowRenegotiation = clientAllowRenegotiation, ApplicationProtocols = clientAppProtocols, CertificateRevocationCheckMode = clientRevocation, ClientCertificates = clientCertificates, EnabledSslProtocols = clientSslProtocols, EncryptionPolicy = clientEncryption, LocalCertificateSelectionCallback = clientLocalCallback, RemoteCertificateValidationCallback = clientRemoteCallback, TargetHost = clientHost }; // Create server options var serverOptions = new SslServerAuthenticationOptions { AllowRenegotiation = serverAllowRenegotiation, ApplicationProtocols = serverAppProtocols, CertificateRevocationCheckMode = serverRevocation, ClientCertificateRequired = serverCertRequired, EnabledSslProtocols = serverSslProtocols, EncryptionPolicy = serverEncryption, RemoteCertificateValidationCallback = serverRemoteCallback, ServerCertificate = serverCert, ServerCertificateContext = certificateContext, }; // Authenticate Task clientTask = client.AuthenticateAsClientAsync(TestAuthenticateAsync, clientOptions); Task serverTask = server.AuthenticateAsServerAsync(TestAuthenticateAsync, serverOptions); await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(); // Validate that client options are unchanged Assert.Equal(clientAllowRenegotiation, clientOptions.AllowRenegotiation); Assert.Same(clientAppProtocols, clientOptions.ApplicationProtocols); Assert.Equal(1, clientOptions.ApplicationProtocols.Count); Assert.Equal(clientRevocation, clientOptions.CertificateRevocationCheckMode); Assert.Same(clientCertificates, clientOptions.ClientCertificates); Assert.Contains(clientCert, clientOptions.ClientCertificates.Cast<X509Certificate2>()); Assert.Equal(clientSslProtocols, clientOptions.EnabledSslProtocols); Assert.Equal(clientEncryption, clientOptions.EncryptionPolicy); Assert.Same(clientLocalCallback, clientOptions.LocalCertificateSelectionCallback); Assert.Same(clientRemoteCallback, clientOptions.RemoteCertificateValidationCallback); Assert.Same(clientHost, clientOptions.TargetHost); // Validate that server options are unchanged Assert.Equal(serverAllowRenegotiation, serverOptions.AllowRenegotiation); Assert.Same(serverAppProtocols, serverOptions.ApplicationProtocols); Assert.Equal(2, serverOptions.ApplicationProtocols.Count); Assert.Equal(clientRevocation, serverOptions.CertificateRevocationCheckMode); Assert.Equal(serverCertRequired, serverOptions.ClientCertificateRequired); Assert.Equal(serverSslProtocols, serverOptions.EnabledSslProtocols); Assert.Equal(serverEncryption, serverOptions.EncryptionPolicy); Assert.Same(serverRemoteCallback, serverOptions.RemoteCertificateValidationCallback); Assert.Same(serverCert, serverOptions.ServerCertificate); Assert.Same(certificateContext, serverOptions.ServerCertificateContext); } } } } public sealed class SslClientAuthenticationOptionsTestBase_Sync : SslClientAuthenticationOptionsTestBase { protected override bool TestAuthenticateAsync => false; } public sealed class SslClientAuthenticationOptionsTestBase_Async : SslClientAuthenticationOptionsTestBase { protected override bool TestAuthenticateAsync => true; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Test.Common; using System.Security.Cryptography.X509Certificates; using System.Security.Authentication; using System.Threading.Tasks; using Xunit; namespace System.Net.Security.Tests { using Configuration = System.Net.Test.Common.Configuration; public abstract class SslClientAuthenticationOptionsTestBase { protected abstract bool TestAuthenticateAsync { get; } [Fact] public async Task ClientOptions_ServerOptions_NotMutatedDuringAuthentication() { using (X509Certificate2 clientCert = Configuration.Certificates.GetClientCertificate()) using (X509Certificate2 serverCert = Configuration.Certificates.GetServerCertificate()) { // Values used to populate client options bool clientAllowRenegotiation = false; List<SslApplicationProtocol> clientAppProtocols = new List<SslApplicationProtocol> { SslApplicationProtocol.Http11 }; X509RevocationMode clientRevocation = X509RevocationMode.NoCheck; X509CertificateCollection clientCertificates = new X509CertificateCollection() { clientCert }; SslProtocols clientSslProtocols = SslProtocols.Tls12; EncryptionPolicy clientEncryption = EncryptionPolicy.RequireEncryption; LocalCertificateSelectionCallback clientLocalCallback = new LocalCertificateSelectionCallback(delegate { return null; }); RemoteCertificateValidationCallback clientRemoteCallback = new RemoteCertificateValidationCallback(delegate { return true; }); string clientHost = serverCert.GetNameInfo(X509NameType.SimpleName, false); // Values used to populate server options bool serverAllowRenegotiation = true; List<SslApplicationProtocol> serverAppProtocols = new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }; X509RevocationMode serverRevocation = X509RevocationMode.NoCheck; bool serverCertRequired = false; #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete SslProtocols serverSslProtocols = SslProtocols.Tls11 | SslProtocols.Tls12; #pragma warning restore SYSLIB0039 #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete EncryptionPolicy serverEncryption = EncryptionPolicy.AllowNoEncryption; #pragma warning restore SYSLIB0040 RemoteCertificateValidationCallback serverRemoteCallback = new RemoteCertificateValidationCallback(delegate { return true; }); SslStreamCertificateContext certificateContext = SslStreamCertificateContext.Create(serverCert, null, false); (Stream stream1, Stream stream2) = TestHelper.GetConnectedStreams(); using (var client = new SslStream(stream1)) using (var server = new SslStream(stream2)) { // Create client options var clientOptions = new SslClientAuthenticationOptions { AllowRenegotiation = clientAllowRenegotiation, ApplicationProtocols = clientAppProtocols, CertificateRevocationCheckMode = clientRevocation, ClientCertificates = clientCertificates, EnabledSslProtocols = clientSslProtocols, EncryptionPolicy = clientEncryption, LocalCertificateSelectionCallback = clientLocalCallback, RemoteCertificateValidationCallback = clientRemoteCallback, TargetHost = clientHost }; // Create server options var serverOptions = new SslServerAuthenticationOptions { AllowRenegotiation = serverAllowRenegotiation, ApplicationProtocols = serverAppProtocols, CertificateRevocationCheckMode = serverRevocation, ClientCertificateRequired = serverCertRequired, EnabledSslProtocols = serverSslProtocols, EncryptionPolicy = serverEncryption, RemoteCertificateValidationCallback = serverRemoteCallback, ServerCertificate = serverCert, ServerCertificateContext = certificateContext, }; // Authenticate Task clientTask = client.AuthenticateAsClientAsync(TestAuthenticateAsync, clientOptions); Task serverTask = server.AuthenticateAsServerAsync(TestAuthenticateAsync, serverOptions); await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(); // Validate that client options are unchanged Assert.Equal(clientAllowRenegotiation, clientOptions.AllowRenegotiation); Assert.Same(clientAppProtocols, clientOptions.ApplicationProtocols); Assert.Equal(1, clientOptions.ApplicationProtocols.Count); Assert.Equal(clientRevocation, clientOptions.CertificateRevocationCheckMode); Assert.Same(clientCertificates, clientOptions.ClientCertificates); Assert.Contains(clientCert, clientOptions.ClientCertificates.Cast<X509Certificate2>()); Assert.Equal(clientSslProtocols, clientOptions.EnabledSslProtocols); Assert.Equal(clientEncryption, clientOptions.EncryptionPolicy); Assert.Same(clientLocalCallback, clientOptions.LocalCertificateSelectionCallback); Assert.Same(clientRemoteCallback, clientOptions.RemoteCertificateValidationCallback); Assert.Same(clientHost, clientOptions.TargetHost); // Validate that server options are unchanged Assert.Equal(serverAllowRenegotiation, serverOptions.AllowRenegotiation); Assert.Same(serverAppProtocols, serverOptions.ApplicationProtocols); Assert.Equal(2, serverOptions.ApplicationProtocols.Count); Assert.Equal(clientRevocation, serverOptions.CertificateRevocationCheckMode); Assert.Equal(serverCertRequired, serverOptions.ClientCertificateRequired); Assert.Equal(serverSslProtocols, serverOptions.EnabledSslProtocols); Assert.Equal(serverEncryption, serverOptions.EncryptionPolicy); Assert.Same(serverRemoteCallback, serverOptions.RemoteCertificateValidationCallback); Assert.Same(serverCert, serverOptions.ServerCertificate); Assert.Same(certificateContext, serverOptions.ServerCertificateContext); } } } } public sealed class SslClientAuthenticationOptionsTestBase_Sync : SslClientAuthenticationOptionsTestBase { protected override bool TestAuthenticateAsync => false; } public sealed class SslClientAuthenticationOptionsTestBase_Async : SslClientAuthenticationOptionsTestBase { protected override bool TestAuthenticateAsync => true; } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamNegotiatedCipherSuiteTest.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; using System.IO; using System.Linq; using System.Net.Test.Common; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using Microsoft.DotNet.XUnitExtensions; using Xunit; namespace System.Net.Security.Tests { using Configuration = System.Net.Test.Common.Configuration; public class NegotiatedCipherSuiteTest { #pragma warning disable CS0618 // Ssl2 and Ssl3 are obsolete #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete public const SslProtocols AllProtocols = SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13; #pragma warning restore CS0618 #pragma warning restore SYSLIB0039 public const SslProtocols NonTls13Protocols = AllProtocols & (~SslProtocols.Tls13); private static bool IsKnownPlatformSupportingTls13 => PlatformDetection.SupportsTls13; private static bool CipherSuitesPolicySupported => s_cipherSuitePolicySupported.Value; private static bool Tls13Supported { get; set; } = IsKnownPlatformSupportingTls13 || ProtocolsSupported(SslProtocols.Tls13); private static bool CipherSuitesPolicyAndTls13Supported => Tls13Supported && CipherSuitesPolicySupported; private static IReadOnlyList<TlsCipherSuite> SupportedNonTls13CipherSuites => s_supportedNonTls13CipherSuites.Value; private static HashSet<TlsCipherSuite> s_tls13CipherSuiteLookup = new HashSet<TlsCipherSuite>(GetTls13CipherSuites()); private static HashSet<TlsCipherSuite> s_tls12CipherSuiteLookup = new HashSet<TlsCipherSuite>(GetTls12CipherSuites()); private static HashSet<TlsCipherSuite> s_tls10And11CipherSuiteLookup = new HashSet<TlsCipherSuite>(GetTls10And11CipherSuites()); private static readonly Lazy<IReadOnlyList<TlsCipherSuite>> s_supportedNonTls13CipherSuites = new Lazy<IReadOnlyList<TlsCipherSuite>>(GetSupportedNonTls13CipherSuites); private static Dictionary<SslProtocols, HashSet<TlsCipherSuite>> s_protocolCipherSuiteLookup = new Dictionary<SslProtocols, HashSet<TlsCipherSuite>>() { { SslProtocols.Tls12, s_tls12CipherSuiteLookup }, #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete { SslProtocols.Tls11, s_tls10And11CipherSuiteLookup }, { SslProtocols.Tls, s_tls10And11CipherSuiteLookup }, #pragma warning restore SYSLIB0039 }; private static Lazy<bool> s_cipherSuitePolicySupported = new Lazy<bool>(() => { try { new CipherSuitesPolicy(Array.Empty<TlsCipherSuite>()); return true; } catch (PlatformNotSupportedException) { } return false; }); [ConditionalFact(nameof(IsKnownPlatformSupportingTls13))] public void Tls13IsSupported_GetValue_ReturnsTrue() { // Validate that flag used in this file works correctly Assert.True(Tls13Supported); } [ConditionalFact(nameof(Tls13Supported))] public void NegotiatedCipherSuite_SslProtocolIsTls13_ShouldBeTls13() { var p = new ConnectionParams() { SslProtocols = SslProtocols.Tls13 }; NegotiatedParams ret = ConnectAndGetNegotiatedParams(p, p); ret.Succeeded(); Assert.True( s_tls13CipherSuiteLookup.Contains(ret.CipherSuite), $"`{ret.CipherSuite}` is not recognized as TLS 1.3 cipher suite"); } [Theory] #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete [InlineData(SslProtocols.Tls)] [InlineData(SslProtocols.Tls11)] #pragma warning restore SYSLIB0039 [InlineData(SslProtocols.Tls12)] public void NegotiatedCipherSuite_SslProtocolIsLowerThanTls13_ShouldMatchTheProtocol(SslProtocols protocol) { var p = new ConnectionParams() { SslProtocols = protocol }; NegotiatedParams ret = ConnectAndGetNegotiatedParams(p, p); if (ret.HasSucceeded) { Assert.True( s_protocolCipherSuiteLookup[protocol].Contains(ret.CipherSuite), $"`{ret.CipherSuite}` is not recognized as {protocol} cipher suite"); } else { // currently TLS 1.2 should be enabled by all known implementations Assert.NotEqual(SslProtocols.Tls12, protocol); } } [Fact] public void NegotiatedCipherSuite_BeforeNegotiationStarted_ShouldThrow() { using (var ms = new MemoryStream()) using (var server = new SslStream(ms, leaveInnerStreamOpen: false)) { Assert.Throws<InvalidOperationException>(() => server.NegotiatedCipherSuite); } } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_AllowSomeCipherSuitesWithNoEncryptionOption_Fails() { CheckPrereqsForNonTls13Tests(1); var p = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(TlsCipherSuite.TLS_AES_128_GCM_SHA256, SupportedNonTls13CipherSuites[0]), EncryptionPolicy = EncryptionPolicy.NoEncryption, }; NegotiatedParams ret = ConnectAndGetNegotiatedParams(p, p); ret.Failed(); } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_NothingAllowed_Fails() { CipherSuitesPolicy csp = BuildPolicy(); var sp = new ConnectionParams(); sp.CipherSuitesPolicy = csp; var cp = new ConnectionParams(); cp.CipherSuitesPolicy = csp; NegotiatedParams ret = ConnectAndGetNegotiatedParams(sp, cp); ret.Failed(); } [ConditionalFact(nameof(CipherSuitesPolicyAndTls13Supported))] public void CipherSuitesPolicy_AllowOneOnOneSideTls13_Success() { bool hasSucceededAtLeastOnce = false; AllowOneOnOneSide(GetTls13CipherSuites(), RequiredByTls13Spec, (cs) => hasSucceededAtLeastOnce = true); Assert.True(hasSucceededAtLeastOnce); } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_AllowTwoOnBothSidesWithSingleOverlapNonTls13_Success() { CheckPrereqsForNonTls13Tests(3); var a = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[0], SupportedNonTls13CipherSuites[1]) }; var b = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[1], SupportedNonTls13CipherSuites[2]) }; for (int i = 0; i < 2; i++) { NegotiatedParams ret = i == 0 ? ConnectAndGetNegotiatedParams(a, b) : ConnectAndGetNegotiatedParams(b, a); ret.Succeeded(); ret.CheckCipherSuite(SupportedNonTls13CipherSuites[1]); } } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_AllowTwoOnBothSidesWithNoOverlapNonTls13_Fails() { CheckPrereqsForNonTls13Tests(4); var a = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[0], SupportedNonTls13CipherSuites[1]) }; var b = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[2], SupportedNonTls13CipherSuites[3]) }; for (int i = 0; i < 2; i++) { NegotiatedParams ret = i == 0 ? ConnectAndGetNegotiatedParams(a, b) : ConnectAndGetNegotiatedParams(b, a); ret.Failed(); } } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_AllowSameTwoOnBothSidesLessPreferredIsTls13_Success() { CheckPrereqsForNonTls13Tests(1); var p = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[0], TlsCipherSuite.TLS_AES_128_GCM_SHA256) }; NegotiatedParams ret = ConnectAndGetNegotiatedParams(p, p); ret.Succeeded(); // If both sides can speak TLS 1.3 they should speak it if (Tls13Supported) { ret.CheckCipherSuite(TlsCipherSuite.TLS_AES_128_GCM_SHA256); } else { ret.CheckCipherSuite(SupportedNonTls13CipherSuites[0]); } } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_TwoCipherSuitesWithAllOverlapping_Success() { CheckPrereqsForNonTls13Tests(2); var a = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[0], SupportedNonTls13CipherSuites[1]) }; var b = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[1], SupportedNonTls13CipherSuites[0]) }; for (int i = 0; i < 2; i++) { bool isAClient = i == 0; NegotiatedParams ret = isAClient ? ConnectAndGetNegotiatedParams(b, a) : ConnectAndGetNegotiatedParams(a, b); ret.Succeeded(); Assert.True(ret.CipherSuite == SupportedNonTls13CipherSuites[0] || ret.CipherSuite == SupportedNonTls13CipherSuites[1]); } } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_ThreeCipherSuitesWithTwoOverlapping_Success() { CheckPrereqsForNonTls13Tests(4); var a = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[0], SupportedNonTls13CipherSuites[1], SupportedNonTls13CipherSuites[2]) }; var b = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[3], SupportedNonTls13CipherSuites[2], SupportedNonTls13CipherSuites[1]) }; for (int i = 0; i < 2; i++) { bool isAClient = i == 0; NegotiatedParams ret = isAClient ? ConnectAndGetNegotiatedParams(b, a) : ConnectAndGetNegotiatedParams(a, b); ret.Succeeded(); Assert.True(ret.CipherSuite == SupportedNonTls13CipherSuites[1] || ret.CipherSuite == SupportedNonTls13CipherSuites[2]); } } [ConditionalFact(nameof(CipherSuitesPolicyAndTls13Supported))] public void CipherSuitesPolicy_OnlyTls13CipherSuiteAllowedButChosenProtocolsDoesNotAllowIt_Fails() { var a = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(TlsCipherSuite.TLS_AES_128_GCM_SHA256), SslProtocols = NonTls13Protocols, }; var b = new ConnectionParams(); for (int i = 0; i < 2; i++) { NegotiatedParams ret = i == 0 ? ConnectAndGetNegotiatedParams(a, b) : ConnectAndGetNegotiatedParams(b, a); ret.Failed(); } } [ConditionalFact(nameof(CipherSuitesPolicyAndTls13Supported))] public void CipherSuitesPolicy_OnlyTls13CipherSuiteAllowedOtherSideDoesNotAllowTls13_Fails() { var a = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(TlsCipherSuite.TLS_AES_128_GCM_SHA256) }; var b = new ConnectionParams() { SslProtocols = NonTls13Protocols }; for (int i = 0; i < 2; i++) { NegotiatedParams ret = i == 0 ? ConnectAndGetNegotiatedParams(a, b) : ConnectAndGetNegotiatedParams(b, a); ret.Failed(); } } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_OnlyNonTls13CipherSuitesAllowedButChosenProtocolDoesNotAllowIt_Fails() { CheckPrereqsForNonTls13Tests(1); var a = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[0]), SslProtocols = SslProtocols.Tls13, }; var b = new ConnectionParams(); for (int i = 0; i < 2; i++) { NegotiatedParams ret = i == 0 ? ConnectAndGetNegotiatedParams(a, b) : ConnectAndGetNegotiatedParams(b, a); ret.Failed(); } } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_OnlyNonTls13CipherSuiteAllowedButOtherSideDoesNotAllowIt_Fails() { CheckPrereqsForNonTls13Tests(1); var a = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[0]) }; var b = new ConnectionParams() { SslProtocols = SslProtocols.Tls13 }; for (int i = 0; i < 2; i++) { NegotiatedParams ret = i == 0 ? ConnectAndGetNegotiatedParams(a, b) : ConnectAndGetNegotiatedParams(b, a); ret.Failed(); } } [Fact] public void CipherSuitesPolicy_CtorWithNull_Fails() { Assert.Throws<ArgumentNullException>(() => new CipherSuitesPolicy(null)); } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_AllowedCipherSuitesIncludesSubsetOfInput_Success() { TlsCipherSuite[] allCipherSuites = (TlsCipherSuite[])Enum.GetValues(typeof(TlsCipherSuite)); var r = new Random(123); int[] numOfCipherSuites = new int[] { 0, 1, 2, 5, 10, 15, 30 }; foreach (int n in numOfCipherSuites) { HashSet<TlsCipherSuite> cipherSuites = PickRandomValues(allCipherSuites, n, r); var csp = new CipherSuitesPolicy(cipherSuites); Assert.NotNull(csp.AllowedCipherSuites); Assert.InRange(csp.AllowedCipherSuites.Count(), 0, n); foreach (var cs in csp.AllowedCipherSuites) { Assert.Contains(cs, cipherSuites); } } } private HashSet<TlsCipherSuite> PickRandomValues(TlsCipherSuite[] all, int n, Random r) { var ret = new HashSet<TlsCipherSuite>(); while (ret.Count != n) { ret.Add(all[r.Next() % n]); } return ret; } private static void AllowOneOnOneSide(IEnumerable<TlsCipherSuite> cipherSuites, Predicate<TlsCipherSuite> mustSucceed, Action<TlsCipherSuite> cipherSuitePicked = null) { foreach (TlsCipherSuite cs in cipherSuites) { CipherSuitesPolicy csp = BuildPolicy(cs); var paramsA = new ConnectionParams() { CipherSuitesPolicy = csp, }; var paramsB = new ConnectionParams(); int score = 0; // 1 for success 0 for fail. Sum should be even for (int i = 0; i < 2; i++) { NegotiatedParams ret = i == 0 ? ConnectAndGetNegotiatedParams(paramsA, paramsB) : ConnectAndGetNegotiatedParams(paramsB, paramsA); score += ret.HasSucceeded ? 1 : 0; if (mustSucceed(cs) || ret.HasSucceeded) { // we do not always guarantee success but if it succeeds it // must use the picked cipher suite ret.Succeeded(); ret.CheckCipherSuite(cs); if (cipherSuitePicked != null && i == 0) { cipherSuitePicked(cs); } } } // we should either get 2 successes or 2 failures Assert.True(score % 2 == 0); } } private static void CheckPrereqsForNonTls13Tests(int minCipherSuites) { if (SupportedNonTls13CipherSuites.Count < minCipherSuites) { // We do not want to accidentally make the tests pass due to the bug in the code // This situation is rather unexpected but can happen on i.e. Alpine // Make sure at least some tests run. if (Tls13Supported) { throw new SkipTestException($"Test requires that at least {minCipherSuites} non TLS 1.3 cipher suites are supported."); } else { throw new Exception($"Less than {minCipherSuites} cipher suites are supported: {string.Join(", ", SupportedNonTls13CipherSuites)}"); } } } private static bool ProtocolsSupported(SslProtocols protocols) { var defaultParams = new ConnectionParams(); defaultParams.SslProtocols = protocols; NegotiatedParams ret = ConnectAndGetNegotiatedParams(defaultParams, defaultParams); return ret.HasSucceeded && protocols.HasFlag(ret.Protocol); } private static IEnumerable<TlsCipherSuite> GetTls13CipherSuites() { // https://tools.ietf.org/html/rfc8446#appendix-B.4 yield return TlsCipherSuite.TLS_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_AES_256_GCM_SHA384; yield return TlsCipherSuite.TLS_CHACHA20_POLY1305_SHA256; yield return TlsCipherSuite.TLS_AES_128_CCM_SHA256; yield return TlsCipherSuite.TLS_AES_128_CCM_8_SHA256; } private static IEnumerable<TlsCipherSuite> GetTls12CipherSuites() { // openssl ciphers -tls1_2 -s --stdname -v yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA; yield return TlsCipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384; yield return TlsCipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256; yield return TlsCipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256; yield return TlsCipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA; yield return TlsCipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA; } private static IEnumerable<TlsCipherSuite> GetTls10And11CipherSuites() { // openssl ciphers -tls1_1 -s --stdname -v yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA; yield return TlsCipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA; yield return TlsCipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA; // rfc5289 values (OSX) yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384; yield return TlsCipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256; yield return TlsCipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384; yield return TlsCipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256; yield return TlsCipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384; yield return TlsCipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384; yield return TlsCipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384; } private static IEnumerable<TlsCipherSuite> GetNonTls13CipherSuites() { var tls13cs = new HashSet<TlsCipherSuite>(GetTls13CipherSuites()); foreach (TlsCipherSuite cs in typeof(TlsCipherSuite).GetEnumValues()) { if (!tls13cs.Contains(cs)) { yield return cs; } } } private static IReadOnlyList<TlsCipherSuite> GetSupportedNonTls13CipherSuites() { // This function is used to initialize static property. // We do not want skipped tests to fail because of that. if (!CipherSuitesPolicySupported) return null; var ret = new List<TlsCipherSuite>(); AllowOneOnOneSide(GetNonTls13CipherSuites(), (cs) => false, (cs) => ret.Add(cs)); return ret; } private static bool RequiredByTls13Spec(TlsCipherSuite cs) { // per spec only one MUST be implemented return cs == TlsCipherSuite.TLS_AES_128_GCM_SHA256; } private static CipherSuitesPolicy BuildPolicy(params TlsCipherSuite[] cipherSuites) { return new CipherSuitesPolicy(cipherSuites); } private static async Task<Exception> WaitForSecureConnection(SslStream client, SslClientAuthenticationOptions clientOptions, SslStream server, SslServerAuthenticationOptions serverOptions) { Task serverTask = null; Task clientTask = null; // check if failed synchronously try { serverTask = server.AuthenticateAsServerAsync(serverOptions, CancellationToken.None); clientTask = client.AuthenticateAsClientAsync(clientOptions, CancellationToken.None); } catch (Exception e) { client.Close(); server.Close(); if (!(e is AuthenticationException || e is Win32Exception)) { throw; } if (serverTask != null) { // i.e. for server we used DEFAULT options but for client we chose not supported cipher suite // this will cause client to fail synchronously while server awaits connection try { // since we broke connection the server should finish await serverTask; } catch (AuthenticationException) { } catch (Win32Exception) { } catch (IOException) { } } return e; } // Since we got here it means client and server have at least 1 choice // of cipher suite // Now we expect both sides to fail or both to succeed Exception failure = null; Task task = null; try { task = await Task.WhenAny(serverTask, clientTask).WaitAsync(TestConfiguration.PassingTestTimeout); await task; } catch (Exception e) when (e is AuthenticationException || e is Win32Exception) { failure = e; // avoid client waiting for server's response if (task == serverTask) { server.Close(); } else { client.Close(); } } try { // Now wait for the other task to finish. task = (task == serverTask ? clientTask : serverTask); await task.WaitAsync(TestConfiguration.PassingTestTimeout); // Fail if server has failed but client has succeeded Assert.Null(failure); } catch (Exception e) when (e is AuthenticationException || e is Win32Exception || e is IOException) { // Fail if server has succeeded but client has failed Assert.NotNull(failure); if (e.GetType() != typeof(IOException)) { failure = new AggregateException(new Exception[] { failure, e }); } } return failure; } private static NegotiatedParams ConnectAndGetNegotiatedParams(ConnectionParams serverParams, ConnectionParams clientParams) { (Stream clientStream, Stream serverStream) = TestHelper.GetConnectedStreams(); using (clientStream) using (serverStream) using (SslStream server = new SslStream(serverStream, leaveInnerStreamOpen: false), client = new SslStream(clientStream, leaveInnerStreamOpen: false)) { var serverOptions = new SslServerAuthenticationOptions(); serverOptions.ServerCertificate = Configuration.Certificates.GetSelfSignedServerCertificate(); serverOptions.EncryptionPolicy = serverParams.EncryptionPolicy; serverOptions.EnabledSslProtocols = serverParams.SslProtocols; serverOptions.CipherSuitesPolicy = serverParams.CipherSuitesPolicy; var clientOptions = new SslClientAuthenticationOptions(); clientOptions.EncryptionPolicy = clientParams.EncryptionPolicy; clientOptions.EnabledSslProtocols = clientParams.SslProtocols; clientOptions.CipherSuitesPolicy = clientParams.CipherSuitesPolicy; clientOptions.TargetHost = "test"; clientOptions.RemoteCertificateValidationCallback = delegate { return true; }; Exception failure = WaitForSecureConnection(client, clientOptions, server, serverOptions).GetAwaiter().GetResult(); if (failure == null) { // send some bytes, make sure they can talk byte[] data = new byte[] { 1, 2, 3 }; byte[] receivedData = new byte[1]; Task serverTask = server.WriteAsync(data, 0, data.Length); for (int i = 0; i < data.Length; i++) { Assert.True(client.ReadAsync(receivedData, 0, 1).Wait(TestConfiguration.PassingTestTimeoutMilliseconds), $"Read task failed to finish in {TestConfiguration.PassingTestTimeoutMilliseconds}ms."); Assert.Equal(data[i], receivedData[0]); } Assert.True(serverTask.Wait(TestConfiguration.PassingTestTimeoutMilliseconds), $"WriteTask failed to finish in {TestConfiguration.PassingTestTimeoutMilliseconds}ms."); return new NegotiatedParams(server, client); } else { return new NegotiatedParams(failure); } } } private class ConnectionParams { public CipherSuitesPolicy CipherSuitesPolicy = null; public EncryptionPolicy EncryptionPolicy = EncryptionPolicy.RequireEncryption; public SslProtocols SslProtocols = SslProtocols.None; } private class NegotiatedParams { private Exception _failure; public bool HasSucceeded => _failure == null; public SslProtocols Protocol { get; private set; } public TlsCipherSuite CipherSuite { get; private set; } public NegotiatedParams(Exception failure) { _failure = failure; } public NegotiatedParams(SslStream serverStream, SslStream clientStream) { _failure = null; CipherSuite = serverStream.NegotiatedCipherSuite; Protocol = serverStream.SslProtocol; Assert.Equal(CipherSuite, clientStream.NegotiatedCipherSuite); Assert.Equal(Protocol, clientStream.SslProtocol); } public void Failed() { Assert.NotNull(_failure); } public void Succeeded() { if (!HasSucceeded) { // for better error message we throw throw _failure; } } public void CheckCipherSuite(TlsCipherSuite expectedCipherSuite) { Assert.Equal(expectedCipherSuite, CipherSuite); } public override string ToString() { // Only for debugging if (HasSucceeded) { return $"[{Protocol}, {CipherSuite}]"; } else { return $"[Failed: {_failure.ToString()}]"; } } } } }
// 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; using System.IO; using System.Linq; using System.Net.Test.Common; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using Microsoft.DotNet.XUnitExtensions; using Xunit; namespace System.Net.Security.Tests { using Configuration = System.Net.Test.Common.Configuration; public class NegotiatedCipherSuiteTest { #pragma warning disable CS0618 // Ssl2 and Ssl3 are obsolete #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete public const SslProtocols AllProtocols = SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13; #pragma warning restore CS0618 #pragma warning restore SYSLIB0039 public const SslProtocols NonTls13Protocols = AllProtocols & (~SslProtocols.Tls13); private static bool IsKnownPlatformSupportingTls13 => PlatformDetection.SupportsTls13; private static bool CipherSuitesPolicySupported => s_cipherSuitePolicySupported.Value; private static bool Tls13Supported { get; set; } = IsKnownPlatformSupportingTls13 || ProtocolsSupported(SslProtocols.Tls13); private static bool CipherSuitesPolicyAndTls13Supported => Tls13Supported && CipherSuitesPolicySupported; private static IReadOnlyList<TlsCipherSuite> SupportedNonTls13CipherSuites => s_supportedNonTls13CipherSuites.Value; private static HashSet<TlsCipherSuite> s_tls13CipherSuiteLookup = new HashSet<TlsCipherSuite>(GetTls13CipherSuites()); private static HashSet<TlsCipherSuite> s_tls12CipherSuiteLookup = new HashSet<TlsCipherSuite>(GetTls12CipherSuites()); private static HashSet<TlsCipherSuite> s_tls10And11CipherSuiteLookup = new HashSet<TlsCipherSuite>(GetTls10And11CipherSuites()); private static readonly Lazy<IReadOnlyList<TlsCipherSuite>> s_supportedNonTls13CipherSuites = new Lazy<IReadOnlyList<TlsCipherSuite>>(GetSupportedNonTls13CipherSuites); private static Dictionary<SslProtocols, HashSet<TlsCipherSuite>> s_protocolCipherSuiteLookup = new Dictionary<SslProtocols, HashSet<TlsCipherSuite>>() { { SslProtocols.Tls12, s_tls12CipherSuiteLookup }, #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete { SslProtocols.Tls11, s_tls10And11CipherSuiteLookup }, { SslProtocols.Tls, s_tls10And11CipherSuiteLookup }, #pragma warning restore SYSLIB0039 }; private static Lazy<bool> s_cipherSuitePolicySupported = new Lazy<bool>(() => { try { new CipherSuitesPolicy(Array.Empty<TlsCipherSuite>()); return true; } catch (PlatformNotSupportedException) { } return false; }); [ConditionalFact(nameof(IsKnownPlatformSupportingTls13))] public void Tls13IsSupported_GetValue_ReturnsTrue() { // Validate that flag used in this file works correctly Assert.True(Tls13Supported); } [ConditionalFact(nameof(Tls13Supported))] public void NegotiatedCipherSuite_SslProtocolIsTls13_ShouldBeTls13() { var p = new ConnectionParams() { SslProtocols = SslProtocols.Tls13 }; NegotiatedParams ret = ConnectAndGetNegotiatedParams(p, p); ret.Succeeded(); Assert.True( s_tls13CipherSuiteLookup.Contains(ret.CipherSuite), $"`{ret.CipherSuite}` is not recognized as TLS 1.3 cipher suite"); } [Theory] #pragma warning disable SYSLIB0039 // TLS 1.0 and 1.1 are obsolete [InlineData(SslProtocols.Tls)] [InlineData(SslProtocols.Tls11)] #pragma warning restore SYSLIB0039 [InlineData(SslProtocols.Tls12)] public void NegotiatedCipherSuite_SslProtocolIsLowerThanTls13_ShouldMatchTheProtocol(SslProtocols protocol) { var p = new ConnectionParams() { SslProtocols = protocol }; NegotiatedParams ret = ConnectAndGetNegotiatedParams(p, p); if (ret.HasSucceeded) { Assert.True( s_protocolCipherSuiteLookup[protocol].Contains(ret.CipherSuite), $"`{ret.CipherSuite}` is not recognized as {protocol} cipher suite"); } else { // currently TLS 1.2 should be enabled by all known implementations Assert.NotEqual(SslProtocols.Tls12, protocol); } } [Fact] public void NegotiatedCipherSuite_BeforeNegotiationStarted_ShouldThrow() { using (var ms = new MemoryStream()) using (var server = new SslStream(ms, leaveInnerStreamOpen: false)) { Assert.Throws<InvalidOperationException>(() => server.NegotiatedCipherSuite); } } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_AllowSomeCipherSuitesWithNoEncryptionOption_Fails() { CheckPrereqsForNonTls13Tests(1); var p = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(TlsCipherSuite.TLS_AES_128_GCM_SHA256, SupportedNonTls13CipherSuites[0]), #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete EncryptionPolicy = EncryptionPolicy.NoEncryption, #pragma warning restore SYSLIB0040 }; NegotiatedParams ret = ConnectAndGetNegotiatedParams(p, p); ret.Failed(); } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_NothingAllowed_Fails() { CipherSuitesPolicy csp = BuildPolicy(); var sp = new ConnectionParams(); sp.CipherSuitesPolicy = csp; var cp = new ConnectionParams(); cp.CipherSuitesPolicy = csp; NegotiatedParams ret = ConnectAndGetNegotiatedParams(sp, cp); ret.Failed(); } [ConditionalFact(nameof(CipherSuitesPolicyAndTls13Supported))] public void CipherSuitesPolicy_AllowOneOnOneSideTls13_Success() { bool hasSucceededAtLeastOnce = false; AllowOneOnOneSide(GetTls13CipherSuites(), RequiredByTls13Spec, (cs) => hasSucceededAtLeastOnce = true); Assert.True(hasSucceededAtLeastOnce); } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_AllowTwoOnBothSidesWithSingleOverlapNonTls13_Success() { CheckPrereqsForNonTls13Tests(3); var a = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[0], SupportedNonTls13CipherSuites[1]) }; var b = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[1], SupportedNonTls13CipherSuites[2]) }; for (int i = 0; i < 2; i++) { NegotiatedParams ret = i == 0 ? ConnectAndGetNegotiatedParams(a, b) : ConnectAndGetNegotiatedParams(b, a); ret.Succeeded(); ret.CheckCipherSuite(SupportedNonTls13CipherSuites[1]); } } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_AllowTwoOnBothSidesWithNoOverlapNonTls13_Fails() { CheckPrereqsForNonTls13Tests(4); var a = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[0], SupportedNonTls13CipherSuites[1]) }; var b = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[2], SupportedNonTls13CipherSuites[3]) }; for (int i = 0; i < 2; i++) { NegotiatedParams ret = i == 0 ? ConnectAndGetNegotiatedParams(a, b) : ConnectAndGetNegotiatedParams(b, a); ret.Failed(); } } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_AllowSameTwoOnBothSidesLessPreferredIsTls13_Success() { CheckPrereqsForNonTls13Tests(1); var p = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[0], TlsCipherSuite.TLS_AES_128_GCM_SHA256) }; NegotiatedParams ret = ConnectAndGetNegotiatedParams(p, p); ret.Succeeded(); // If both sides can speak TLS 1.3 they should speak it if (Tls13Supported) { ret.CheckCipherSuite(TlsCipherSuite.TLS_AES_128_GCM_SHA256); } else { ret.CheckCipherSuite(SupportedNonTls13CipherSuites[0]); } } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_TwoCipherSuitesWithAllOverlapping_Success() { CheckPrereqsForNonTls13Tests(2); var a = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[0], SupportedNonTls13CipherSuites[1]) }; var b = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[1], SupportedNonTls13CipherSuites[0]) }; for (int i = 0; i < 2; i++) { bool isAClient = i == 0; NegotiatedParams ret = isAClient ? ConnectAndGetNegotiatedParams(b, a) : ConnectAndGetNegotiatedParams(a, b); ret.Succeeded(); Assert.True(ret.CipherSuite == SupportedNonTls13CipherSuites[0] || ret.CipherSuite == SupportedNonTls13CipherSuites[1]); } } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_ThreeCipherSuitesWithTwoOverlapping_Success() { CheckPrereqsForNonTls13Tests(4); var a = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[0], SupportedNonTls13CipherSuites[1], SupportedNonTls13CipherSuites[2]) }; var b = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[3], SupportedNonTls13CipherSuites[2], SupportedNonTls13CipherSuites[1]) }; for (int i = 0; i < 2; i++) { bool isAClient = i == 0; NegotiatedParams ret = isAClient ? ConnectAndGetNegotiatedParams(b, a) : ConnectAndGetNegotiatedParams(a, b); ret.Succeeded(); Assert.True(ret.CipherSuite == SupportedNonTls13CipherSuites[1] || ret.CipherSuite == SupportedNonTls13CipherSuites[2]); } } [ConditionalFact(nameof(CipherSuitesPolicyAndTls13Supported))] public void CipherSuitesPolicy_OnlyTls13CipherSuiteAllowedButChosenProtocolsDoesNotAllowIt_Fails() { var a = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(TlsCipherSuite.TLS_AES_128_GCM_SHA256), SslProtocols = NonTls13Protocols, }; var b = new ConnectionParams(); for (int i = 0; i < 2; i++) { NegotiatedParams ret = i == 0 ? ConnectAndGetNegotiatedParams(a, b) : ConnectAndGetNegotiatedParams(b, a); ret.Failed(); } } [ConditionalFact(nameof(CipherSuitesPolicyAndTls13Supported))] public void CipherSuitesPolicy_OnlyTls13CipherSuiteAllowedOtherSideDoesNotAllowTls13_Fails() { var a = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(TlsCipherSuite.TLS_AES_128_GCM_SHA256) }; var b = new ConnectionParams() { SslProtocols = NonTls13Protocols }; for (int i = 0; i < 2; i++) { NegotiatedParams ret = i == 0 ? ConnectAndGetNegotiatedParams(a, b) : ConnectAndGetNegotiatedParams(b, a); ret.Failed(); } } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_OnlyNonTls13CipherSuitesAllowedButChosenProtocolDoesNotAllowIt_Fails() { CheckPrereqsForNonTls13Tests(1); var a = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[0]), SslProtocols = SslProtocols.Tls13, }; var b = new ConnectionParams(); for (int i = 0; i < 2; i++) { NegotiatedParams ret = i == 0 ? ConnectAndGetNegotiatedParams(a, b) : ConnectAndGetNegotiatedParams(b, a); ret.Failed(); } } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_OnlyNonTls13CipherSuiteAllowedButOtherSideDoesNotAllowIt_Fails() { CheckPrereqsForNonTls13Tests(1); var a = new ConnectionParams() { CipherSuitesPolicy = BuildPolicy(SupportedNonTls13CipherSuites[0]) }; var b = new ConnectionParams() { SslProtocols = SslProtocols.Tls13 }; for (int i = 0; i < 2; i++) { NegotiatedParams ret = i == 0 ? ConnectAndGetNegotiatedParams(a, b) : ConnectAndGetNegotiatedParams(b, a); ret.Failed(); } } [Fact] public void CipherSuitesPolicy_CtorWithNull_Fails() { Assert.Throws<ArgumentNullException>(() => new CipherSuitesPolicy(null)); } [ConditionalFact(nameof(CipherSuitesPolicySupported))] public void CipherSuitesPolicy_AllowedCipherSuitesIncludesSubsetOfInput_Success() { TlsCipherSuite[] allCipherSuites = (TlsCipherSuite[])Enum.GetValues(typeof(TlsCipherSuite)); var r = new Random(123); int[] numOfCipherSuites = new int[] { 0, 1, 2, 5, 10, 15, 30 }; foreach (int n in numOfCipherSuites) { HashSet<TlsCipherSuite> cipherSuites = PickRandomValues(allCipherSuites, n, r); var csp = new CipherSuitesPolicy(cipherSuites); Assert.NotNull(csp.AllowedCipherSuites); Assert.InRange(csp.AllowedCipherSuites.Count(), 0, n); foreach (var cs in csp.AllowedCipherSuites) { Assert.Contains(cs, cipherSuites); } } } private HashSet<TlsCipherSuite> PickRandomValues(TlsCipherSuite[] all, int n, Random r) { var ret = new HashSet<TlsCipherSuite>(); while (ret.Count != n) { ret.Add(all[r.Next() % n]); } return ret; } private static void AllowOneOnOneSide(IEnumerable<TlsCipherSuite> cipherSuites, Predicate<TlsCipherSuite> mustSucceed, Action<TlsCipherSuite> cipherSuitePicked = null) { foreach (TlsCipherSuite cs in cipherSuites) { CipherSuitesPolicy csp = BuildPolicy(cs); var paramsA = new ConnectionParams() { CipherSuitesPolicy = csp, }; var paramsB = new ConnectionParams(); int score = 0; // 1 for success 0 for fail. Sum should be even for (int i = 0; i < 2; i++) { NegotiatedParams ret = i == 0 ? ConnectAndGetNegotiatedParams(paramsA, paramsB) : ConnectAndGetNegotiatedParams(paramsB, paramsA); score += ret.HasSucceeded ? 1 : 0; if (mustSucceed(cs) || ret.HasSucceeded) { // we do not always guarantee success but if it succeeds it // must use the picked cipher suite ret.Succeeded(); ret.CheckCipherSuite(cs); if (cipherSuitePicked != null && i == 0) { cipherSuitePicked(cs); } } } // we should either get 2 successes or 2 failures Assert.True(score % 2 == 0); } } private static void CheckPrereqsForNonTls13Tests(int minCipherSuites) { if (SupportedNonTls13CipherSuites.Count < minCipherSuites) { // We do not want to accidentally make the tests pass due to the bug in the code // This situation is rather unexpected but can happen on i.e. Alpine // Make sure at least some tests run. if (Tls13Supported) { throw new SkipTestException($"Test requires that at least {minCipherSuites} non TLS 1.3 cipher suites are supported."); } else { throw new Exception($"Less than {minCipherSuites} cipher suites are supported: {string.Join(", ", SupportedNonTls13CipherSuites)}"); } } } private static bool ProtocolsSupported(SslProtocols protocols) { var defaultParams = new ConnectionParams(); defaultParams.SslProtocols = protocols; NegotiatedParams ret = ConnectAndGetNegotiatedParams(defaultParams, defaultParams); return ret.HasSucceeded && protocols.HasFlag(ret.Protocol); } private static IEnumerable<TlsCipherSuite> GetTls13CipherSuites() { // https://tools.ietf.org/html/rfc8446#appendix-B.4 yield return TlsCipherSuite.TLS_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_AES_256_GCM_SHA384; yield return TlsCipherSuite.TLS_CHACHA20_POLY1305_SHA256; yield return TlsCipherSuite.TLS_AES_128_CCM_SHA256; yield return TlsCipherSuite.TLS_AES_128_CCM_8_SHA256; } private static IEnumerable<TlsCipherSuite> GetTls12CipherSuites() { // openssl ciphers -tls1_2 -s --stdname -v yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA; yield return TlsCipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384; yield return TlsCipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256; yield return TlsCipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256; yield return TlsCipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA; yield return TlsCipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA; } private static IEnumerable<TlsCipherSuite> GetTls10And11CipherSuites() { // openssl ciphers -tls1_1 -s --stdname -v yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA; yield return TlsCipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA; yield return TlsCipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA; yield return TlsCipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA; // rfc5289 values (OSX) yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384; yield return TlsCipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256; yield return TlsCipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384; yield return TlsCipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256; yield return TlsCipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384; yield return TlsCipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384; yield return TlsCipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256; yield return TlsCipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384; } private static IEnumerable<TlsCipherSuite> GetNonTls13CipherSuites() { var tls13cs = new HashSet<TlsCipherSuite>(GetTls13CipherSuites()); foreach (TlsCipherSuite cs in typeof(TlsCipherSuite).GetEnumValues()) { if (!tls13cs.Contains(cs)) { yield return cs; } } } private static IReadOnlyList<TlsCipherSuite> GetSupportedNonTls13CipherSuites() { // This function is used to initialize static property. // We do not want skipped tests to fail because of that. if (!CipherSuitesPolicySupported) return null; var ret = new List<TlsCipherSuite>(); AllowOneOnOneSide(GetNonTls13CipherSuites(), (cs) => false, (cs) => ret.Add(cs)); return ret; } private static bool RequiredByTls13Spec(TlsCipherSuite cs) { // per spec only one MUST be implemented return cs == TlsCipherSuite.TLS_AES_128_GCM_SHA256; } private static CipherSuitesPolicy BuildPolicy(params TlsCipherSuite[] cipherSuites) { return new CipherSuitesPolicy(cipherSuites); } private static async Task<Exception> WaitForSecureConnection(SslStream client, SslClientAuthenticationOptions clientOptions, SslStream server, SslServerAuthenticationOptions serverOptions) { Task serverTask = null; Task clientTask = null; // check if failed synchronously try { serverTask = server.AuthenticateAsServerAsync(serverOptions, CancellationToken.None); clientTask = client.AuthenticateAsClientAsync(clientOptions, CancellationToken.None); } catch (Exception e) { client.Close(); server.Close(); if (!(e is AuthenticationException || e is Win32Exception)) { throw; } if (serverTask != null) { // i.e. for server we used DEFAULT options but for client we chose not supported cipher suite // this will cause client to fail synchronously while server awaits connection try { // since we broke connection the server should finish await serverTask; } catch (AuthenticationException) { } catch (Win32Exception) { } catch (IOException) { } } return e; } // Since we got here it means client and server have at least 1 choice // of cipher suite // Now we expect both sides to fail or both to succeed Exception failure = null; Task task = null; try { task = await Task.WhenAny(serverTask, clientTask).WaitAsync(TestConfiguration.PassingTestTimeout); await task; } catch (Exception e) when (e is AuthenticationException || e is Win32Exception) { failure = e; // avoid client waiting for server's response if (task == serverTask) { server.Close(); } else { client.Close(); } } try { // Now wait for the other task to finish. task = (task == serverTask ? clientTask : serverTask); await task.WaitAsync(TestConfiguration.PassingTestTimeout); // Fail if server has failed but client has succeeded Assert.Null(failure); } catch (Exception e) when (e is AuthenticationException || e is Win32Exception || e is IOException) { // Fail if server has succeeded but client has failed Assert.NotNull(failure); if (e.GetType() != typeof(IOException)) { failure = new AggregateException(new Exception[] { failure, e }); } } return failure; } private static NegotiatedParams ConnectAndGetNegotiatedParams(ConnectionParams serverParams, ConnectionParams clientParams) { (Stream clientStream, Stream serverStream) = TestHelper.GetConnectedStreams(); using (clientStream) using (serverStream) using (SslStream server = new SslStream(serverStream, leaveInnerStreamOpen: false), client = new SslStream(clientStream, leaveInnerStreamOpen: false)) { var serverOptions = new SslServerAuthenticationOptions(); serverOptions.ServerCertificate = Configuration.Certificates.GetSelfSignedServerCertificate(); serverOptions.EncryptionPolicy = serverParams.EncryptionPolicy; serverOptions.EnabledSslProtocols = serverParams.SslProtocols; serverOptions.CipherSuitesPolicy = serverParams.CipherSuitesPolicy; var clientOptions = new SslClientAuthenticationOptions(); clientOptions.EncryptionPolicy = clientParams.EncryptionPolicy; clientOptions.EnabledSslProtocols = clientParams.SslProtocols; clientOptions.CipherSuitesPolicy = clientParams.CipherSuitesPolicy; clientOptions.TargetHost = "test"; clientOptions.RemoteCertificateValidationCallback = delegate { return true; }; Exception failure = WaitForSecureConnection(client, clientOptions, server, serverOptions).GetAwaiter().GetResult(); if (failure == null) { // send some bytes, make sure they can talk byte[] data = new byte[] { 1, 2, 3 }; byte[] receivedData = new byte[1]; Task serverTask = server.WriteAsync(data, 0, data.Length); for (int i = 0; i < data.Length; i++) { Assert.True(client.ReadAsync(receivedData, 0, 1).Wait(TestConfiguration.PassingTestTimeoutMilliseconds), $"Read task failed to finish in {TestConfiguration.PassingTestTimeoutMilliseconds}ms."); Assert.Equal(data[i], receivedData[0]); } Assert.True(serverTask.Wait(TestConfiguration.PassingTestTimeoutMilliseconds), $"WriteTask failed to finish in {TestConfiguration.PassingTestTimeoutMilliseconds}ms."); return new NegotiatedParams(server, client); } else { return new NegotiatedParams(failure); } } } private class ConnectionParams { public CipherSuitesPolicy CipherSuitesPolicy = null; public EncryptionPolicy EncryptionPolicy = EncryptionPolicy.RequireEncryption; public SslProtocols SslProtocols = SslProtocols.None; } private class NegotiatedParams { private Exception _failure; public bool HasSucceeded => _failure == null; public SslProtocols Protocol { get; private set; } public TlsCipherSuite CipherSuite { get; private set; } public NegotiatedParams(Exception failure) { _failure = failure; } public NegotiatedParams(SslStream serverStream, SslStream clientStream) { _failure = null; CipherSuite = serverStream.NegotiatedCipherSuite; Protocol = serverStream.SslProtocol; Assert.Equal(CipherSuite, clientStream.NegotiatedCipherSuite); Assert.Equal(Protocol, clientStream.SslProtocol); } public void Failed() { Assert.NotNull(_failure); } public void Succeeded() { if (!HasSucceeded) { // for better error message we throw throw _failure; } } public void CheckCipherSuite(TlsCipherSuite expectedCipherSuite) { Assert.Equal(expectedCipherSuite, CipherSuite); } public override string ToString() { // Only for debugging if (HasSucceeded) { return $"[{Protocol}, {CipherSuite}]"; } else { return $"[Failed: {_failure.ToString()}]"; } } } } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/tests/UnitTests/SslAuthenticationOptionsTests.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.Authentication; using System.Security.Cryptography.X509Certificates; using Xunit; namespace System.Net.Security.Tests { public class SslAuthenticationOptionsTests { private readonly SslClientAuthenticationOptions _clientOptions = new SslClientAuthenticationOptions(); private readonly SslServerAuthenticationOptions _serverOptions = new SslServerAuthenticationOptions(); [Fact] public void AllowRenegotiation_Get_Set_Succeeds() { Assert.True(_clientOptions.AllowRenegotiation); Assert.False(_serverOptions.AllowRenegotiation); _clientOptions.AllowRenegotiation = true; _serverOptions.AllowRenegotiation = true; Assert.True(_clientOptions.AllowRenegotiation); Assert.True(_serverOptions.AllowRenegotiation); } [Fact] public void ClientCertificateRequired_Get_Set_Succeeds() { Assert.False(_serverOptions.ClientCertificateRequired); _serverOptions.ClientCertificateRequired = true; Assert.True(_serverOptions.ClientCertificateRequired); } [Fact] public void ApplicationProtocols_Get_Set_Succeeds() { Assert.Null(_clientOptions.ApplicationProtocols); Assert.Null(_serverOptions.ApplicationProtocols); List<SslApplicationProtocol> applnProtos = new List<SslApplicationProtocol> { SslApplicationProtocol.Http3, SslApplicationProtocol.Http2, SslApplicationProtocol.Http11 }; _clientOptions.ApplicationProtocols = applnProtos; _serverOptions.ApplicationProtocols = applnProtos; Assert.Equal(applnProtos, _clientOptions.ApplicationProtocols); Assert.Equal(applnProtos, _serverOptions.ApplicationProtocols); } [Fact] public void RemoteCertificateValidationCallback_Get_Set_Succeeds() { Assert.Null(_clientOptions.RemoteCertificateValidationCallback); Assert.Null(_serverOptions.RemoteCertificateValidationCallback); RemoteCertificateValidationCallback callback = (sender, certificate, chain, errors) => { return true; }; _clientOptions.RemoteCertificateValidationCallback = callback; _serverOptions.RemoteCertificateValidationCallback = callback; Assert.Equal(callback, _clientOptions.RemoteCertificateValidationCallback); Assert.Equal(callback, _serverOptions.RemoteCertificateValidationCallback); } [Fact] public void LocalCertificateSelectionCallback_Get_Set_Succeeds() { Assert.Null(_clientOptions.LocalCertificateSelectionCallback); LocalCertificateSelectionCallback callback = (sender, host, localCertificates, remoteCertificate, issuers) => default; _clientOptions.LocalCertificateSelectionCallback = callback; Assert.Equal(callback, _clientOptions.LocalCertificateSelectionCallback); } [Theory] [InlineData("")] [InlineData("\u0bee")] [InlineData("hello")] [InlineData(" \t")] [InlineData(null)] public void TargetHost_Get_Set_Succeeds(string expected) { Assert.Null(_clientOptions.TargetHost); _clientOptions.TargetHost = expected; Assert.Equal(expected, _clientOptions.TargetHost); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/38559")] public void ClientCertificates_Get_Set_Succeeds() { Assert.Null(_clientOptions.ClientCertificates); _clientOptions.ClientCertificates = null; Assert.Null(_clientOptions.ClientCertificates); X509CertificateCollection expected = new X509CertificateCollection(); _clientOptions.ClientCertificates = expected; Assert.Equal(expected, _clientOptions.ClientCertificates); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/38559")] public void ServerCertificate_Get_Set_Succeeds() { Assert.Null(_serverOptions.ServerCertificate); _serverOptions.ServerCertificate = null; Assert.Null(_serverOptions.ServerCertificate); X509Certificate cert = new X509Certificate2(stackalloc byte[0]); _serverOptions.ServerCertificate = cert; Assert.Equal(cert, _serverOptions.ServerCertificate); } [Fact] public void EnabledSslProtocols_Get_Set_Succeeds() { Assert.Equal(SslProtocols.None, _clientOptions.EnabledSslProtocols); Assert.Equal(SslProtocols.None, _serverOptions.EnabledSslProtocols); _clientOptions.EnabledSslProtocols = SslProtocols.Tls12; _serverOptions.EnabledSslProtocols = SslProtocols.Tls12; Assert.Equal(SslProtocols.Tls12, _clientOptions.EnabledSslProtocols); Assert.Equal(SslProtocols.Tls12, _serverOptions.EnabledSslProtocols); } [Fact] public void CheckCertificateRevocation_Get_Set_Succeeds() { Assert.Equal(X509RevocationMode.NoCheck, _clientOptions.CertificateRevocationCheckMode); Assert.Equal(X509RevocationMode.NoCheck, _serverOptions.CertificateRevocationCheckMode); _clientOptions.CertificateRevocationCheckMode = X509RevocationMode.Online; _serverOptions.CertificateRevocationCheckMode = X509RevocationMode.Offline; Assert.Equal(X509RevocationMode.Online, _clientOptions.CertificateRevocationCheckMode); Assert.Equal(X509RevocationMode.Offline, _serverOptions.CertificateRevocationCheckMode); Assert.Throws<ArgumentException>(() => _clientOptions.CertificateRevocationCheckMode = (X509RevocationMode)3); Assert.Throws<ArgumentException>(() => _serverOptions.CertificateRevocationCheckMode = (X509RevocationMode)3); } [Fact] public void EncryptionPolicy_Get_Set_Succeeds() { Assert.Equal(EncryptionPolicy.RequireEncryption, _clientOptions.EncryptionPolicy); Assert.Equal(EncryptionPolicy.RequireEncryption, _serverOptions.EncryptionPolicy); _clientOptions.EncryptionPolicy = EncryptionPolicy.AllowNoEncryption; _serverOptions.EncryptionPolicy = EncryptionPolicy.NoEncryption; Assert.Equal(EncryptionPolicy.AllowNoEncryption, _clientOptions.EncryptionPolicy); Assert.Equal(EncryptionPolicy.NoEncryption, _serverOptions.EncryptionPolicy); Assert.Throws<ArgumentException>(() => _clientOptions.EncryptionPolicy = (EncryptionPolicy)3); Assert.Throws<ArgumentException>(() => _serverOptions.EncryptionPolicy = (EncryptionPolicy)3); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using Xunit; namespace System.Net.Security.Tests { public class SslAuthenticationOptionsTests { private readonly SslClientAuthenticationOptions _clientOptions = new SslClientAuthenticationOptions(); private readonly SslServerAuthenticationOptions _serverOptions = new SslServerAuthenticationOptions(); [Fact] public void AllowRenegotiation_Get_Set_Succeeds() { Assert.True(_clientOptions.AllowRenegotiation); Assert.False(_serverOptions.AllowRenegotiation); _clientOptions.AllowRenegotiation = true; _serverOptions.AllowRenegotiation = true; Assert.True(_clientOptions.AllowRenegotiation); Assert.True(_serverOptions.AllowRenegotiation); } [Fact] public void ClientCertificateRequired_Get_Set_Succeeds() { Assert.False(_serverOptions.ClientCertificateRequired); _serverOptions.ClientCertificateRequired = true; Assert.True(_serverOptions.ClientCertificateRequired); } [Fact] public void ApplicationProtocols_Get_Set_Succeeds() { Assert.Null(_clientOptions.ApplicationProtocols); Assert.Null(_serverOptions.ApplicationProtocols); List<SslApplicationProtocol> applnProtos = new List<SslApplicationProtocol> { SslApplicationProtocol.Http3, SslApplicationProtocol.Http2, SslApplicationProtocol.Http11 }; _clientOptions.ApplicationProtocols = applnProtos; _serverOptions.ApplicationProtocols = applnProtos; Assert.Equal(applnProtos, _clientOptions.ApplicationProtocols); Assert.Equal(applnProtos, _serverOptions.ApplicationProtocols); } [Fact] public void RemoteCertificateValidationCallback_Get_Set_Succeeds() { Assert.Null(_clientOptions.RemoteCertificateValidationCallback); Assert.Null(_serverOptions.RemoteCertificateValidationCallback); RemoteCertificateValidationCallback callback = (sender, certificate, chain, errors) => { return true; }; _clientOptions.RemoteCertificateValidationCallback = callback; _serverOptions.RemoteCertificateValidationCallback = callback; Assert.Equal(callback, _clientOptions.RemoteCertificateValidationCallback); Assert.Equal(callback, _serverOptions.RemoteCertificateValidationCallback); } [Fact] public void LocalCertificateSelectionCallback_Get_Set_Succeeds() { Assert.Null(_clientOptions.LocalCertificateSelectionCallback); LocalCertificateSelectionCallback callback = (sender, host, localCertificates, remoteCertificate, issuers) => default; _clientOptions.LocalCertificateSelectionCallback = callback; Assert.Equal(callback, _clientOptions.LocalCertificateSelectionCallback); } [Theory] [InlineData("")] [InlineData("\u0bee")] [InlineData("hello")] [InlineData(" \t")] [InlineData(null)] public void TargetHost_Get_Set_Succeeds(string expected) { Assert.Null(_clientOptions.TargetHost); _clientOptions.TargetHost = expected; Assert.Equal(expected, _clientOptions.TargetHost); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/38559")] public void ClientCertificates_Get_Set_Succeeds() { Assert.Null(_clientOptions.ClientCertificates); _clientOptions.ClientCertificates = null; Assert.Null(_clientOptions.ClientCertificates); X509CertificateCollection expected = new X509CertificateCollection(); _clientOptions.ClientCertificates = expected; Assert.Equal(expected, _clientOptions.ClientCertificates); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/38559")] public void ServerCertificate_Get_Set_Succeeds() { Assert.Null(_serverOptions.ServerCertificate); _serverOptions.ServerCertificate = null; Assert.Null(_serverOptions.ServerCertificate); X509Certificate cert = new X509Certificate2(stackalloc byte[0]); _serverOptions.ServerCertificate = cert; Assert.Equal(cert, _serverOptions.ServerCertificate); } [Fact] public void EnabledSslProtocols_Get_Set_Succeeds() { Assert.Equal(SslProtocols.None, _clientOptions.EnabledSslProtocols); Assert.Equal(SslProtocols.None, _serverOptions.EnabledSslProtocols); _clientOptions.EnabledSslProtocols = SslProtocols.Tls12; _serverOptions.EnabledSslProtocols = SslProtocols.Tls12; Assert.Equal(SslProtocols.Tls12, _clientOptions.EnabledSslProtocols); Assert.Equal(SslProtocols.Tls12, _serverOptions.EnabledSslProtocols); } [Fact] public void CheckCertificateRevocation_Get_Set_Succeeds() { Assert.Equal(X509RevocationMode.NoCheck, _clientOptions.CertificateRevocationCheckMode); Assert.Equal(X509RevocationMode.NoCheck, _serverOptions.CertificateRevocationCheckMode); _clientOptions.CertificateRevocationCheckMode = X509RevocationMode.Online; _serverOptions.CertificateRevocationCheckMode = X509RevocationMode.Offline; Assert.Equal(X509RevocationMode.Online, _clientOptions.CertificateRevocationCheckMode); Assert.Equal(X509RevocationMode.Offline, _serverOptions.CertificateRevocationCheckMode); Assert.Throws<ArgumentException>(() => _clientOptions.CertificateRevocationCheckMode = (X509RevocationMode)3); Assert.Throws<ArgumentException>(() => _serverOptions.CertificateRevocationCheckMode = (X509RevocationMode)3); } [Fact] public void EncryptionPolicy_Get_Set_Succeeds() { Assert.Equal(EncryptionPolicy.RequireEncryption, _clientOptions.EncryptionPolicy); Assert.Equal(EncryptionPolicy.RequireEncryption, _serverOptions.EncryptionPolicy); #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete _clientOptions.EncryptionPolicy = EncryptionPolicy.AllowNoEncryption; _serverOptions.EncryptionPolicy = EncryptionPolicy.NoEncryption; Assert.Equal(EncryptionPolicy.AllowNoEncryption, _clientOptions.EncryptionPolicy); Assert.Equal(EncryptionPolicy.NoEncryption, _serverOptions.EncryptionPolicy); #pragma warning restore SYSLIB0040 Assert.Throws<ArgumentException>(() => _clientOptions.EncryptionPolicy = (EncryptionPolicy)3); Assert.Throws<ArgumentException>(() => _serverOptions.EncryptionPolicy = (EncryptionPolicy)3); } } }
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Security/tests/UnitTests/System.Net.Security.Unit.Tests.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <StringResourcesPath>../../src/Resources/Strings.resx</StringResourcesPath> <!-- UnitTests compile production source-code in order to test internal units such as individual methods and classes. Dependencies are broken via Fakes. Since we are referencing netstandard, the real types can conflict with the ones imported. We are disabling the "Type conflicts with the imported type CS0436 warning" for these types of projects. --> <NoWarn>436</NoWarn> <!-- Disable: CLSCompliant attribute is not needed --> <NoWarn>$(NoWarn);3021</NoWarn> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-Browser;$(NetCoreAppCurrent)-OSX;$(NetCoreAppCurrent)-iOS;$(NetCoreAppCurrent)-Android</TargetFrameworks> <Nullable>annotations</Nullable> <IgnoreForCI Condition="'$(TargetOS)' == 'Browser'">true</IgnoreForCI> </PropertyGroup> <ItemGroup> <Compile Include="AssemblyInfo.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Android'"> <Compile Include="MD4Tests.cs" /> <Compile Include="..\..\src\System\Net\Security\MD4.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' != 'Browser'"> <Compile Include="SslApplicationProtocolTests.cs" /> <Compile Include="SslAuthenticationOptionsTests.cs" /> <Compile Include="SslStreamAllowedProtocolsTest.cs" /> <Compile Include="System\Security\Authentication\AuthenticationExceptionTest.cs" /> <Compile Include="System\Security\Authentication\ExtendedProtection\ExtendedProtectionPolicyTest.cs" /> <Compile Include="System\Security\Authentication\InvalidCredentialExceptionTest.cs" /> <Compile Include="TlsAlertsMatchWindowsInterop.cs" /> <!-- Fakes --> <Compile Include="Fakes\FakeSslStream.Implementation.cs" /> <Compile Include="Fakes\FakeAuthenticatedStream.cs" /> <!-- Common test files --> <Compile Include="$(CommonTestPath)System\Net\SslProtocolSupport.cs" Link="CommonTest\System\Net\SslProtocolSupport.cs" /> <Compile Include="$(CommonPath)System\HexConverter.cs" Link="Common\System\HexConverter.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' != 'Browser'"> <!-- Production code references --> <Compile Include="..\..\src\System\Net\Security\NetEventSource.Security.cs" Link="ProductionCode\System\Net\Security\NetEventSource.Security.cs" /> <Compile Include="..\..\src\System\Net\Security\SslStream.cs" Link="ProductionCode\System\Net\Security\SslStream.cs" /> <Compile Include="..\..\src\System\Net\Security\SslClientAuthenticationOptions.cs" Link="ProductionCode\System\Net\Security\SslClientAuthenticationOptions.cs" /> <Compile Include="..\..\src\System\Net\Security\SslServerAuthenticationOptions.cs" Link="ProductionCode\System\Net\Security\SslServerAuthenticationOptions.cs" /> <Compile Include="..\..\src\System\Net\Security\SslAuthenticationOptions.cs" Link="ProductionCode\System\Net\Security\SslAuthenticationOptions.cs" /> <Compile Include="..\..\src\System\Net\Security\SslApplicationProtocol.cs" Link="ProductionCode\System\Net\Security\SslApplicationProtocol.cs" /> <Compile Include="..\..\src\System\Net\Security\SslConnectionInfo.cs" Link="ProductionCode\System\Net\Security\SslConnectionInfo.cs" /> <Compile Include="..\..\src\System\Net\Security\SslStreamCertificateContext.cs" Link="ProductionCode\System\Net\Security\SslStreamCertificateContext.cs" /> <Compile Include="..\..\src\System\Net\Security\SslStreamCertificateContext.Windows.cs" Link="ProductionCode\System\Net\Security\SslStreamCertificateContext.Windows.cs" /> <Compile Include="..\..\src\System\Net\Security\ReadWriteAdapter.cs" Link="ProductionCode\System\Net\Security\ReadWriteAdapter.cs" /> <Compile Include="..\..\src\System\Net\SslStreamContext.cs" Link="ProductionCode\System\Net\SslStreamContext.cs" /> <Compile Include="$(CommonPath)System\Net\SecurityProtocol.cs" Link="ProductionCode\Common\System\Net\SecurityProtocol.cs" /> <Compile Include="..\..\src\System\Net\Security\TlsAlertType.cs" Link="ProductionCode\Common\System\Net\TlsAlertType.cs" /> <Compile Include="..\..\src\System\Net\Security\TlsAlertMessage.cs" Link="ProductionCode\Common\System\Net\TlsAlertMessage.cs" /> <Compile Include="..\..\src\System\Net\Security\TlsFrameHelper.cs" Link="ProductionCode\Common\System\Net\TlsFrameHelper.cs" /> <Compile Include="$(CommonPath)Interop\Windows\SChannel\Interop.Alerts.cs" Link="Common\Interop\Windows\SChannel\Interop.Alerts.cs" /> <Compile Include="$(CommonPath)System\Threading\Tasks\TaskToApm.cs" Link="Common\System\Threading\Tasks\TaskToApm.cs" /> <!-- Logging --> <Compile Include="$(CommonPath)System\Net\Logging\NetEventSource.Common.cs" Link="ProductionCode\Common\System\Net\Logging\NetEventSource.Common.cs" /> <Compile Include="$(CommonPath)System\Net\InternalException.cs" Link="ProductionCode\Common\System\Net\InternalException.cs" /> <!-- System.Net common --> <Compile Include="$(CommonPath)System\Net\ArrayBuffer.cs" Link="Common\System\Net\ArrayBuffer.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <StringResourcesPath>../../src/Resources/Strings.resx</StringResourcesPath> <!-- UnitTests compile production source-code in order to test internal units such as individual methods and classes. Dependencies are broken via Fakes. Since we are referencing netstandard, the real types can conflict with the ones imported. We are disabling the "Type conflicts with the imported type CS0436 warning" for these types of projects. --> <NoWarn>436</NoWarn> <!-- Disable: CLSCompliant attribute is not needed --> <NoWarn>$(NoWarn);3021</NoWarn> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-Browser;$(NetCoreAppCurrent)-OSX;$(NetCoreAppCurrent)-iOS;$(NetCoreAppCurrent)-Android</TargetFrameworks> <Nullable>annotations</Nullable> <IgnoreForCI Condition="'$(TargetOS)' == 'Browser'">true</IgnoreForCI> </PropertyGroup> <ItemGroup> <Compile Include="AssemblyInfo.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Android'"> <Compile Include="MD4Tests.cs" /> <Compile Include="..\..\src\System\Net\Security\MD4.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' != 'Browser'"> <Compile Include="SslApplicationProtocolTests.cs" /> <Compile Include="SslAuthenticationOptionsTests.cs" /> <Compile Include="SslStreamAllowedProtocolsTest.cs" /> <Compile Include="System\Security\Authentication\AuthenticationExceptionTest.cs" /> <Compile Include="System\Security\Authentication\ExtendedProtection\ExtendedProtectionPolicyTest.cs" /> <Compile Include="System\Security\Authentication\InvalidCredentialExceptionTest.cs" /> <Compile Include="TlsAlertsMatchWindowsInterop.cs" /> <!-- Fakes --> <Compile Include="Fakes\FakeSslStream.Implementation.cs" /> <Compile Include="Fakes\FakeAuthenticatedStream.cs" /> <!-- Common test files --> <Compile Include="$(CommonTestPath)System\Net\SslProtocolSupport.cs" Link="CommonTest\System\Net\SslProtocolSupport.cs" /> <Compile Include="$(CommonPath)System\HexConverter.cs" Link="Common\System\HexConverter.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' != 'Browser'"> <!-- Production code references --> <Compile Include="..\..\src\System\Net\Security\NetEventSource.Security.cs" Link="ProductionCode\System\Net\Security\NetEventSource.Security.cs" /> <Compile Include="..\..\src\System\Net\Security\SslStream.cs" Link="ProductionCode\System\Net\Security\SslStream.cs" /> <Compile Include="..\..\src\System\Net\Security\SslClientAuthenticationOptions.cs" Link="ProductionCode\System\Net\Security\SslClientAuthenticationOptions.cs" /> <Compile Include="..\..\src\System\Net\Security\SslServerAuthenticationOptions.cs" Link="ProductionCode\System\Net\Security\SslServerAuthenticationOptions.cs" /> <Compile Include="..\..\src\System\Net\Security\SslAuthenticationOptions.cs" Link="ProductionCode\System\Net\Security\SslAuthenticationOptions.cs" /> <Compile Include="..\..\src\System\Net\Security\SslApplicationProtocol.cs" Link="ProductionCode\System\Net\Security\SslApplicationProtocol.cs" /> <Compile Include="..\..\src\System\Net\Security\SslConnectionInfo.cs" Link="ProductionCode\System\Net\Security\SslConnectionInfo.cs" /> <Compile Include="..\..\src\System\Net\Security\SslStreamCertificateContext.cs" Link="ProductionCode\System\Net\Security\SslStreamCertificateContext.cs" /> <Compile Include="..\..\src\System\Net\Security\SslStreamCertificateContext.Windows.cs" Link="ProductionCode\System\Net\Security\SslStreamCertificateContext.Windows.cs" /> <Compile Include="..\..\src\System\Net\Security\ReadWriteAdapter.cs" Link="ProductionCode\System\Net\Security\ReadWriteAdapter.cs" /> <Compile Include="..\..\src\System\Net\SslStreamContext.cs" Link="ProductionCode\System\Net\SslStreamContext.cs" /> <Compile Include="$(CommonPath)System\Net\SecurityProtocol.cs" Link="ProductionCode\Common\System\Net\SecurityProtocol.cs" /> <Compile Include="..\..\src\System\Net\Security\TlsAlertType.cs" Link="ProductionCode\Common\System\Net\TlsAlertType.cs" /> <Compile Include="..\..\src\System\Net\Security\TlsAlertMessage.cs" Link="ProductionCode\Common\System\Net\TlsAlertMessage.cs" /> <Compile Include="..\..\src\System\Net\Security\TlsFrameHelper.cs" Link="ProductionCode\Common\System\Net\TlsFrameHelper.cs" /> <Compile Include="$(CommonPath)Interop\Windows\SChannel\Interop.Alerts.cs" Link="Common\Interop\Windows\SChannel\Interop.Alerts.cs" /> <Compile Include="$(CommonPath)System\Threading\Tasks\TaskToApm.cs" Link="Common\System\Threading\Tasks\TaskToApm.cs" /> <Compile Include="$(CommonPath)System\Obsoletions.cs" Link="Common\System\Obsoletions.cs" /> <!-- Logging --> <Compile Include="$(CommonPath)System\Net\Logging\NetEventSource.Common.cs" Link="ProductionCode\Common\System\Net\Logging\NetEventSource.Common.cs" /> <Compile Include="$(CommonPath)System\Net\InternalException.cs" Link="ProductionCode\Common\System\Net\InternalException.cs" /> <!-- System.Net common --> <Compile Include="$(CommonPath)System\Net\ArrayBuffer.cs" Link="Common\System\Net\ArrayBuffer.cs" /> </ItemGroup> </Project>
1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.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.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.Serialization; // For SR using System.Text; namespace System.Xml { // This wrapper does not support seek. // Constructors consume/emit byte order mark. // Supports: UTF-8, Unicode, BigEndianUnicode // ASSUMPTION (Microsoft): This class will only be used for EITHER reading OR writing. It can be done, it would just mean more buffers. // ASSUMPTION (Microsoft): The byte buffer is large enough to hold the declaration // ASSUMPTION (Microsoft): The buffer manipulation methods (FillBuffer/Compare/etc.) will only be used to parse the declaration // during construction. internal sealed class EncodingStreamWrapper : Stream { private enum SupportedEncoding { UTF8, UTF16LE, UTF16BE, None } private static readonly UTF8Encoding s_safeUTF8 = new UTF8Encoding(false, false); private static readonly UnicodeEncoding s_safeUTF16 = new UnicodeEncoding(false, false, false); private static readonly UnicodeEncoding s_safeBEUTF16 = new UnicodeEncoding(true, false, false); private static readonly UTF8Encoding s_validatingUTF8 = new UTF8Encoding(false, true); private static readonly UnicodeEncoding s_validatingUTF16 = new UnicodeEncoding(false, false, true); private static readonly UnicodeEncoding s_validatingBEUTF16 = new UnicodeEncoding(true, false, true); private const int BufferLength = 128; // UTF-8 is fastpath, so that's how these are stored // Compare methods adapt to Unicode. private static readonly byte[] s_encodingAttr = new byte[] { (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g' }; private static readonly byte[] s_encodingUTF8 = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'8' }; private static readonly byte[] s_encodingUnicode = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6' }; private static readonly byte[] s_encodingUnicodeLE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'l', (byte)'e' }; private static readonly byte[] s_encodingUnicodeBE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'b', (byte)'e' }; private SupportedEncoding _encodingCode; private Encoding? _encoding; private readonly Encoder? _enc; private readonly Decoder? _dec; private readonly bool _isReading; private readonly Stream _stream; private char[]? _chars; private byte[]? _bytes; private int _byteOffset; private int _byteCount; private readonly byte[] _byteBuffer = new byte[1]; // Reading constructor public EncodingStreamWrapper(Stream stream, Encoding? encoding) { try { _isReading = true; _stream = stream; // Decode the expected encoding SupportedEncoding expectedEnc = GetSupportedEncoding(encoding); // Get the byte order mark so we can determine the encoding // May want to try to delay allocating everything until we know the BOM SupportedEncoding declEnc = ReadBOMEncoding(encoding == null); // Check that the expected encoding matches the decl encoding. if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc) ThrowExpectedEncodingMismatch(expectedEnc, declEnc); // Fastpath: UTF-8 BOM if (declEnc == SupportedEncoding.UTF8) { // Fastpath: UTF-8 BOM, No declaration FillBuffer(2); if (_bytes[_byteOffset + 1] != '?' || _bytes[_byteOffset] != '<') { return; } FillBuffer(BufferLength); CheckUTF8DeclarationEncoding(_bytes, _byteOffset, _byteCount, declEnc, expectedEnc); } else { // Convert to UTF-8 EnsureBuffers(); FillBuffer((BufferLength - 1) * 2); SetReadDocumentEncoding(declEnc); CleanupCharBreak(); int count = _encoding.GetChars(_bytes, _byteOffset, _byteCount, _chars, 0); _byteOffset = 0; _byteCount = s_validatingUTF8.GetBytes(_chars, 0, count, _bytes, 0); // Check for declaration if (_bytes[1] == '?' && _bytes[0] == '<') { CheckUTF8DeclarationEncoding(_bytes, 0, _byteCount, declEnc, expectedEnc); } else { // Declaration required if no out-of-band encoding if (expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); } } } catch (DecoderFallbackException ex) { throw new XmlException(SR.XmlInvalidBytes, ex); } } [MemberNotNull(nameof(_encoding))] private void SetReadDocumentEncoding(SupportedEncoding e) { EnsureBuffers(); _encodingCode = e; _encoding = GetEncoding(e); } private static Encoding GetEncoding(SupportedEncoding e) => e switch { SupportedEncoding.UTF8 => s_validatingUTF8, SupportedEncoding.UTF16LE => s_validatingUTF16, SupportedEncoding.UTF16BE => s_validatingBEUTF16, _ => throw new XmlException(SR.XmlEncodingNotSupported), }; private static Encoding GetSafeEncoding(SupportedEncoding e) => e switch { SupportedEncoding.UTF8 => s_safeUTF8, SupportedEncoding.UTF16LE => s_safeUTF16, SupportedEncoding.UTF16BE => s_safeBEUTF16, _ => throw new XmlException(SR.XmlEncodingNotSupported), }; private static string GetEncodingName(SupportedEncoding enc) => enc switch { SupportedEncoding.UTF8 => "utf-8", SupportedEncoding.UTF16LE => "utf-16LE", SupportedEncoding.UTF16BE => "utf-16BE", _ => throw new XmlException(SR.XmlEncodingNotSupported), }; private static SupportedEncoding GetSupportedEncoding(Encoding? encoding) { if (encoding == null) return SupportedEncoding.None; else if (encoding.WebName == s_validatingUTF8.WebName) return SupportedEncoding.UTF8; else if (encoding.WebName == s_validatingUTF16.WebName) return SupportedEncoding.UTF16LE; else if (encoding.WebName == s_validatingBEUTF16.WebName) return SupportedEncoding.UTF16BE; else throw new XmlException(SR.XmlEncodingNotSupported); } // Writing constructor public EncodingStreamWrapper(Stream stream, Encoding encoding, bool emitBOM) { _isReading = false; _encoding = encoding; _stream = stream; // Set the encoding code _encodingCode = GetSupportedEncoding(encoding); if (_encodingCode != SupportedEncoding.UTF8) { EnsureBuffers(); _dec = s_validatingUTF8.GetDecoder(); _enc = _encoding.GetEncoder(); // Emit BOM if (emitBOM) { ReadOnlySpan<byte> bom = _encoding.Preamble; if (bom.Length > 0) _stream.Write(bom); } } } [MemberNotNull(nameof(_bytes))] private SupportedEncoding ReadBOMEncoding(bool notOutOfBand) { int b1 = _stream.ReadByte(); int b2 = _stream.ReadByte(); int b3 = _stream.ReadByte(); int b4 = _stream.ReadByte(); // Premature end of stream if (b4 == -1) throw new XmlException(SR.UnexpectedEndOfFile); int preserve; SupportedEncoding e = ReadBOMEncoding((byte)b1, (byte)b2, (byte)b3, (byte)b4, notOutOfBand, out preserve); EnsureByteBuffer(); switch (preserve) { case 1: _bytes[0] = (byte)b4; break; case 2: _bytes[0] = (byte)b3; _bytes[1] = (byte)b4; break; case 4: _bytes[0] = (byte)b1; _bytes[1] = (byte)b2; _bytes[2] = (byte)b3; _bytes[3] = (byte)b4; break; } _byteCount = preserve; return e; } private static SupportedEncoding ReadBOMEncoding(byte b1, byte b2, byte b3, byte b4, bool notOutOfBand, out int preserve) { SupportedEncoding e = SupportedEncoding.UTF8; // Default preserve = 0; if (b1 == '<' && b2 != 0x00) // UTF-8, no BOM { e = SupportedEncoding.UTF8; preserve = 4; } else if (b1 == 0xFF && b2 == 0xFE) // UTF-16 little endian { e = SupportedEncoding.UTF16LE; preserve = 2; } else if (b1 == 0xFE && b2 == 0xFF) // UTF-16 big endian { e = SupportedEncoding.UTF16BE; preserve = 2; } else if (b1 == 0x00 && b2 == '<') // UTF-16 big endian, no BOM { e = SupportedEncoding.UTF16BE; if (notOutOfBand && (b3 != 0x00 || b4 != '?')) throw new XmlException(SR.XmlDeclMissing); preserve = 4; } else if (b1 == '<' && b2 == 0x00) // UTF-16 little endian, no BOM { e = SupportedEncoding.UTF16LE; if (notOutOfBand && (b3 != '?' || b4 != 0x00)) throw new XmlException(SR.XmlDeclMissing); preserve = 4; } else if (b1 == 0xEF && b2 == 0xBB) // UTF8 with BOM { // Encoding error if (notOutOfBand && b3 != 0xBF) throw new XmlException(SR.XmlBadBOM); preserve = 1; } else // Assume UTF8 { preserve = 4; } return e; } private void FillBuffer(int count) { count -= _byteCount; while (count > 0) { int read = _stream.Read(_bytes!, _byteOffset + _byteCount, count); if (read == 0) break; _byteCount += read; count -= read; } } [MemberNotNull(nameof(_bytes))] [MemberNotNull(nameof(_chars))] private void EnsureBuffers() { EnsureByteBuffer(); if (_chars == null) _chars = new char[BufferLength]; } [MemberNotNull(nameof(_bytes))] private void EnsureByteBuffer() { if (_bytes != null) return; _bytes = new byte[BufferLength * 4]; _byteOffset = 0; _byteCount = 0; } private static void CheckUTF8DeclarationEncoding(byte[] buffer, int offset, int count, SupportedEncoding e, SupportedEncoding expectedEnc) { byte quot = 0; int encEq = -1; int max = offset + Math.Min(count, BufferLength); // Encoding should be second "=", abort at first "?" int i; int eq = 0; for (i = offset + 2; i < max; i++) // Skip the "<?" so we don't get caught by the first "?" { if (quot != 0) { if (buffer[i] == quot) { quot = 0; } continue; } if (buffer[i] == (byte)'\'' || buffer[i] == (byte)'"') { quot = buffer[i]; } else if (buffer[i] == (byte)'=') { if (eq == 1) { encEq = i; break; } eq++; } else if (buffer[i] == (byte)'?') // Not legal character in a decl before second "=" { break; } } // No encoding found if (encEq == -1) { if (e != SupportedEncoding.UTF8 && expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); return; } if (encEq < 28) // Earliest second "=" can appear throw new XmlException(SR.XmlMalformedDecl); // Back off whitespace for (i = encEq - 1; IsWhitespace(buffer[i]); i--) ; // Check for encoding attribute if (!Compare(s_encodingAttr, buffer, i - s_encodingAttr.Length + 1)) { if (e != SupportedEncoding.UTF8 && expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); return; } // Move ahead of whitespace for (i = encEq + 1; i < max && IsWhitespace(buffer[i]); i++) ; // Find the quotes if (buffer[i] != '\'' && buffer[i] != '"') throw new XmlException(SR.XmlMalformedDecl); quot = buffer[i]; int q = i; for (i = q + 1; buffer[i] != quot && i < max; ++i) ; if (buffer[i] != quot) throw new XmlException(SR.XmlMalformedDecl); int encStart = q + 1; int encCount = i - encStart; // lookup the encoding SupportedEncoding declEnc = e; if (encCount == s_encodingUTF8.Length && CompareCaseInsensitive(s_encodingUTF8, buffer, encStart)) { declEnc = SupportedEncoding.UTF8; } else if (encCount == s_encodingUnicodeLE.Length && CompareCaseInsensitive(s_encodingUnicodeLE, buffer, encStart)) { declEnc = SupportedEncoding.UTF16LE; } else if (encCount == s_encodingUnicodeBE.Length && CompareCaseInsensitive(s_encodingUnicodeBE, buffer, encStart)) { declEnc = SupportedEncoding.UTF16BE; } else if (encCount == s_encodingUnicode.Length && CompareCaseInsensitive(s_encodingUnicode, buffer, encStart)) { if (e == SupportedEncoding.UTF8) ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), s_safeUTF8.GetString(s_encodingUTF8, 0, s_encodingUTF8.Length)); } else { ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), e); } if (e != declEnc) ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), e); } private static bool CompareCaseInsensitive(byte[] key, byte[] buffer, int offset) { for (int i = 0; i < key.Length; i++) { if (key[i] == buffer[offset + i]) continue; if (key[i] != char.ToLowerInvariant((char)buffer[offset + i])) return false; } return true; } private static bool Compare(byte[] key, byte[] buffer, int offset) { for (int i = 0; i < key.Length; i++) { if (key[i] != buffer[offset + i]) return false; } return true; } private static bool IsWhitespace(byte ch) { return ch == (byte)' ' || ch == (byte)'\n' || ch == (byte)'\t' || ch == (byte)'\r'; } internal static ArraySegment<byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding? encoding) { if (count < 4) throw new XmlException(SR.UnexpectedEndOfFile); try { int preserve; ArraySegment<byte> seg; SupportedEncoding expectedEnc = GetSupportedEncoding(encoding); SupportedEncoding declEnc = ReadBOMEncoding(buffer[offset], buffer[offset + 1], buffer[offset + 2], buffer[offset + 3], encoding == null, out preserve); if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc) ThrowExpectedEncodingMismatch(expectedEnc, declEnc); offset += 4 - preserve; count -= 4 - preserve; // Fastpath: UTF-8 char[] chars; byte[] bytes; Encoding localEnc; if (declEnc == SupportedEncoding.UTF8) { // Fastpath: No declaration if (buffer[offset + 1] != '?' || buffer[offset] != '<') { seg = new ArraySegment<byte>(buffer, offset, count); return seg; } CheckUTF8DeclarationEncoding(buffer, offset, count, declEnc, expectedEnc); seg = new ArraySegment<byte>(buffer, offset, count); return seg; } // Convert to UTF-8 localEnc = GetSafeEncoding(declEnc); int inputCount = Math.Min(count, BufferLength * 2); chars = new char[localEnc.GetMaxCharCount(inputCount)]; int ccount = localEnc.GetChars(buffer, offset, inputCount, chars, 0); bytes = new byte[s_validatingUTF8.GetMaxByteCount(ccount)]; int bcount = s_validatingUTF8.GetBytes(chars, 0, ccount, bytes, 0); // Check for declaration if (bytes[1] == '?' && bytes[0] == '<') { CheckUTF8DeclarationEncoding(bytes, 0, bcount, declEnc, expectedEnc); } else { // Declaration required if no out-of-band encoding if (expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); } seg = new ArraySegment<byte>(s_validatingUTF8.GetBytes(GetEncoding(declEnc).GetChars(buffer, offset, count))); return seg; } catch (DecoderFallbackException e) { throw new XmlException(SR.XmlInvalidBytes, e); } } private static void ThrowExpectedEncodingMismatch(SupportedEncoding expEnc, SupportedEncoding actualEnc) { throw new XmlException(SR.Format(SR.XmlExpectedEncoding, GetEncodingName(expEnc), GetEncodingName(actualEnc))); } private static void ThrowEncodingMismatch(string declEnc, SupportedEncoding enc) { ThrowEncodingMismatch(declEnc, GetEncodingName(enc)); } private static void ThrowEncodingMismatch(string declEnc, string docEnc) { throw new XmlException(SR.Format(SR.XmlEncodingMismatch, declEnc, docEnc)); } // This stream wrapper does not support duplex public override bool CanRead { get { if (!_isReading) return false; return _stream.CanRead; } } // The encoding conversion and buffering breaks seeking. public override bool CanSeek { get { return false; } } // This stream wrapper does not support duplex public override bool CanWrite { get { if (_isReading) return false; return _stream.CanWrite; } } // The encoding conversion and buffering breaks seeking. public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } protected override void Dispose(bool disposing) { if (_stream.CanWrite) { Flush(); } _stream.Dispose(); base.Dispose(disposing); } public override void Flush() { _stream.Flush(); } public override int ReadByte() { if (_byteCount == 0 && _encodingCode == SupportedEncoding.UTF8) return _stream.ReadByte(); if (Read(_byteBuffer, 0, 1) == 0) return -1; return _byteBuffer[0]; } public override int Read(byte[] buffer, int offset, int count) { try { if (_byteCount == 0) { if (_encodingCode == SupportedEncoding.UTF8) return _stream.Read(buffer, offset, count); Debug.Assert(_bytes != null); Debug.Assert(_chars != null); // No more bytes than can be turned into characters _byteOffset = 0; _byteCount = _stream.Read(_bytes, _byteCount, (_chars.Length - 1) * 2); // Check for end of stream if (_byteCount == 0) return 0; // Fix up incomplete chars CleanupCharBreak(); // Change encoding int charCount = _encoding!.GetChars(_bytes, 0, _byteCount, _chars, 0); _byteCount = Encoding.UTF8.GetBytes(_chars, 0, charCount, _bytes, 0); } // Give them bytes if (_byteCount < count) count = _byteCount; Buffer.BlockCopy(_bytes!, _byteOffset, buffer, offset, count); _byteOffset += count; _byteCount -= count; return count; } catch (DecoderFallbackException ex) { throw new XmlException(SR.XmlInvalidBytes, ex); } } private void CleanupCharBreak() { Debug.Assert(_bytes != null); int max = _byteOffset + _byteCount; // Read on 2 byte boundaries if ((_byteCount % 2) != 0) { int b = _stream.ReadByte(); if (b < 0) throw new XmlException(SR.UnexpectedEndOfFile); _bytes[max++] = (byte)b; _byteCount++; } // Don't cut off a surrogate character int w; if (_encodingCode == SupportedEncoding.UTF16LE) { w = _bytes[max - 2] + (_bytes[max - 1] << 8); } else { w = _bytes[max - 1] + (_bytes[max - 2] << 8); } if ((w & 0xDC00) != 0xDC00 && w >= 0xD800 && w <= 0xDBFF) // First 16-bit number of surrogate pair { int b1 = _stream.ReadByte(); int b2 = _stream.ReadByte(); if (b2 < 0) throw new XmlException(SR.UnexpectedEndOfFile); _bytes[max++] = (byte)b1; _bytes[max++] = (byte)b2; _byteCount += 2; } } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void WriteByte(byte b) { if (_encodingCode == SupportedEncoding.UTF8) { _stream.WriteByte(b); return; } _byteBuffer[0] = b; Write(_byteBuffer, 0, 1); } public override void Write(byte[] buffer, int offset, int count) { // Optimize UTF-8 case if (_encodingCode == SupportedEncoding.UTF8) { _stream.Write(buffer, offset, count); return; } Debug.Assert(_bytes != null); Debug.Assert(_chars != null); while (count > 0) { int size = _chars.Length < count ? _chars.Length : count; int charCount = _dec!.GetChars(buffer, offset, size, _chars, 0, false); _byteCount = _enc!.GetBytes(_chars, 0, charCount, _bytes, 0, false); _stream.Write(_bytes, 0, _byteCount); offset += size; count -= size; } } // Delegate properties public override bool CanTimeout { get { return _stream.CanTimeout; } } public override long Length { get { return _stream.Length; } } public override int ReadTimeout { get { return _stream.ReadTimeout; } set { _stream.ReadTimeout = value; } } public override int WriteTimeout { get { return _stream.WriteTimeout; } set { _stream.WriteTimeout = value; } } // Delegate methods public override void SetLength(long value) { throw new NotSupportedException(); } } // Add format exceptions // Do we need to modify the stream position/Seek to account for the buffer? // ASSUMPTION (Microsoft): This class will only be used for EITHER reading OR writing. }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.Serialization; // For SR using System.Text; namespace System.Xml { // This wrapper does not support seek. // Constructors consume/emit byte order mark. // Supports: UTF-8, Unicode, BigEndianUnicode // ASSUMPTION (Microsoft): This class will only be used for EITHER reading OR writing. It can be done, it would just mean more buffers. // ASSUMPTION (Microsoft): The byte buffer is large enough to hold the declaration // ASSUMPTION (Microsoft): The buffer manipulation methods (FillBuffer/Compare/etc.) will only be used to parse the declaration // during construction. internal sealed class EncodingStreamWrapper : Stream { private enum SupportedEncoding { UTF8, UTF16LE, UTF16BE, None } private static readonly UTF8Encoding s_safeUTF8 = new UTF8Encoding(false, false); private static readonly UnicodeEncoding s_safeUTF16 = new UnicodeEncoding(false, false, false); private static readonly UnicodeEncoding s_safeBEUTF16 = new UnicodeEncoding(true, false, false); private static readonly UTF8Encoding s_validatingUTF8 = new UTF8Encoding(false, true); private static readonly UnicodeEncoding s_validatingUTF16 = new UnicodeEncoding(false, false, true); private static readonly UnicodeEncoding s_validatingBEUTF16 = new UnicodeEncoding(true, false, true); private const int BufferLength = 128; // UTF-8 is fastpath, so that's how these are stored // Compare methods adapt to Unicode. private static readonly byte[] s_encodingAttr = new byte[] { (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g' }; private static readonly byte[] s_encodingUTF8 = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'8' }; private static readonly byte[] s_encodingUnicode = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6' }; private static readonly byte[] s_encodingUnicodeLE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'l', (byte)'e' }; private static readonly byte[] s_encodingUnicodeBE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'b', (byte)'e' }; private SupportedEncoding _encodingCode; private Encoding? _encoding; private readonly Encoder? _enc; private readonly Decoder? _dec; private readonly bool _isReading; private readonly Stream _stream; private char[]? _chars; private byte[]? _bytes; private int _byteOffset; private int _byteCount; private readonly byte[] _byteBuffer = new byte[1]; // Reading constructor public EncodingStreamWrapper(Stream stream, Encoding? encoding) { try { _isReading = true; _stream = stream; // Decode the expected encoding SupportedEncoding expectedEnc = GetSupportedEncoding(encoding); // Get the byte order mark so we can determine the encoding // May want to try to delay allocating everything until we know the BOM SupportedEncoding declEnc = ReadBOMEncoding(encoding == null); // Check that the expected encoding matches the decl encoding. if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc) ThrowExpectedEncodingMismatch(expectedEnc, declEnc); // Fastpath: UTF-8 BOM if (declEnc == SupportedEncoding.UTF8) { // Fastpath: UTF-8 BOM, No declaration FillBuffer(2); if (_bytes[_byteOffset + 1] != '?' || _bytes[_byteOffset] != '<') { return; } FillBuffer(BufferLength); CheckUTF8DeclarationEncoding(_bytes, _byteOffset, _byteCount, declEnc, expectedEnc); } else { // Convert to UTF-8 EnsureBuffers(); FillBuffer((BufferLength - 1) * 2); SetReadDocumentEncoding(declEnc); CleanupCharBreak(); int count = _encoding.GetChars(_bytes, _byteOffset, _byteCount, _chars, 0); _byteOffset = 0; _byteCount = s_validatingUTF8.GetBytes(_chars, 0, count, _bytes, 0); // Check for declaration if (_bytes[1] == '?' && _bytes[0] == '<') { CheckUTF8DeclarationEncoding(_bytes, 0, _byteCount, declEnc, expectedEnc); } else { // Declaration required if no out-of-band encoding if (expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); } } } catch (DecoderFallbackException ex) { throw new XmlException(SR.XmlInvalidBytes, ex); } } [MemberNotNull(nameof(_encoding))] private void SetReadDocumentEncoding(SupportedEncoding e) { EnsureBuffers(); _encodingCode = e; _encoding = GetEncoding(e); } private static Encoding GetEncoding(SupportedEncoding e) => e switch { SupportedEncoding.UTF8 => s_validatingUTF8, SupportedEncoding.UTF16LE => s_validatingUTF16, SupportedEncoding.UTF16BE => s_validatingBEUTF16, _ => throw new XmlException(SR.XmlEncodingNotSupported), }; private static Encoding GetSafeEncoding(SupportedEncoding e) => e switch { SupportedEncoding.UTF8 => s_safeUTF8, SupportedEncoding.UTF16LE => s_safeUTF16, SupportedEncoding.UTF16BE => s_safeBEUTF16, _ => throw new XmlException(SR.XmlEncodingNotSupported), }; private static string GetEncodingName(SupportedEncoding enc) => enc switch { SupportedEncoding.UTF8 => "utf-8", SupportedEncoding.UTF16LE => "utf-16LE", SupportedEncoding.UTF16BE => "utf-16BE", _ => throw new XmlException(SR.XmlEncodingNotSupported), }; private static SupportedEncoding GetSupportedEncoding(Encoding? encoding) { if (encoding == null) return SupportedEncoding.None; else if (encoding.WebName == s_validatingUTF8.WebName) return SupportedEncoding.UTF8; else if (encoding.WebName == s_validatingUTF16.WebName) return SupportedEncoding.UTF16LE; else if (encoding.WebName == s_validatingBEUTF16.WebName) return SupportedEncoding.UTF16BE; else throw new XmlException(SR.XmlEncodingNotSupported); } // Writing constructor public EncodingStreamWrapper(Stream stream, Encoding encoding, bool emitBOM) { _isReading = false; _encoding = encoding; _stream = stream; // Set the encoding code _encodingCode = GetSupportedEncoding(encoding); if (_encodingCode != SupportedEncoding.UTF8) { EnsureBuffers(); _dec = s_validatingUTF8.GetDecoder(); _enc = _encoding.GetEncoder(); // Emit BOM if (emitBOM) { ReadOnlySpan<byte> bom = _encoding.Preamble; if (bom.Length > 0) _stream.Write(bom); } } } [MemberNotNull(nameof(_bytes))] private SupportedEncoding ReadBOMEncoding(bool notOutOfBand) { int b1 = _stream.ReadByte(); int b2 = _stream.ReadByte(); int b3 = _stream.ReadByte(); int b4 = _stream.ReadByte(); // Premature end of stream if (b4 == -1) throw new XmlException(SR.UnexpectedEndOfFile); int preserve; SupportedEncoding e = ReadBOMEncoding((byte)b1, (byte)b2, (byte)b3, (byte)b4, notOutOfBand, out preserve); EnsureByteBuffer(); switch (preserve) { case 1: _bytes[0] = (byte)b4; break; case 2: _bytes[0] = (byte)b3; _bytes[1] = (byte)b4; break; case 4: _bytes[0] = (byte)b1; _bytes[1] = (byte)b2; _bytes[2] = (byte)b3; _bytes[3] = (byte)b4; break; } _byteCount = preserve; return e; } private static SupportedEncoding ReadBOMEncoding(byte b1, byte b2, byte b3, byte b4, bool notOutOfBand, out int preserve) { SupportedEncoding e = SupportedEncoding.UTF8; // Default preserve = 0; if (b1 == '<' && b2 != 0x00) // UTF-8, no BOM { e = SupportedEncoding.UTF8; preserve = 4; } else if (b1 == 0xFF && b2 == 0xFE) // UTF-16 little endian { e = SupportedEncoding.UTF16LE; preserve = 2; } else if (b1 == 0xFE && b2 == 0xFF) // UTF-16 big endian { e = SupportedEncoding.UTF16BE; preserve = 2; } else if (b1 == 0x00 && b2 == '<') // UTF-16 big endian, no BOM { e = SupportedEncoding.UTF16BE; if (notOutOfBand && (b3 != 0x00 || b4 != '?')) throw new XmlException(SR.XmlDeclMissing); preserve = 4; } else if (b1 == '<' && b2 == 0x00) // UTF-16 little endian, no BOM { e = SupportedEncoding.UTF16LE; if (notOutOfBand && (b3 != '?' || b4 != 0x00)) throw new XmlException(SR.XmlDeclMissing); preserve = 4; } else if (b1 == 0xEF && b2 == 0xBB) // UTF8 with BOM { // Encoding error if (notOutOfBand && b3 != 0xBF) throw new XmlException(SR.XmlBadBOM); preserve = 1; } else // Assume UTF8 { preserve = 4; } return e; } private void FillBuffer(int count) { count -= _byteCount; while (count > 0) { int read = _stream.Read(_bytes!, _byteOffset + _byteCount, count); if (read == 0) break; _byteCount += read; count -= read; } } [MemberNotNull(nameof(_bytes))] [MemberNotNull(nameof(_chars))] private void EnsureBuffers() { EnsureByteBuffer(); if (_chars == null) _chars = new char[BufferLength]; } [MemberNotNull(nameof(_bytes))] private void EnsureByteBuffer() { if (_bytes != null) return; _bytes = new byte[BufferLength * 4]; _byteOffset = 0; _byteCount = 0; } private static void CheckUTF8DeclarationEncoding(byte[] buffer, int offset, int count, SupportedEncoding e, SupportedEncoding expectedEnc) { byte quot = 0; int encEq = -1; int max = offset + Math.Min(count, BufferLength); // Encoding should be second "=", abort at first "?" int i; int eq = 0; for (i = offset + 2; i < max; i++) // Skip the "<?" so we don't get caught by the first "?" { if (quot != 0) { if (buffer[i] == quot) { quot = 0; } continue; } if (buffer[i] == (byte)'\'' || buffer[i] == (byte)'"') { quot = buffer[i]; } else if (buffer[i] == (byte)'=') { if (eq == 1) { encEq = i; break; } eq++; } else if (buffer[i] == (byte)'?') // Not legal character in a decl before second "=" { break; } } // No encoding found if (encEq == -1) { if (e != SupportedEncoding.UTF8 && expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); return; } if (encEq < 28) // Earliest second "=" can appear throw new XmlException(SR.XmlMalformedDecl); // Back off whitespace for (i = encEq - 1; IsWhitespace(buffer[i]); i--) ; // Check for encoding attribute if (!Compare(s_encodingAttr, buffer, i - s_encodingAttr.Length + 1)) { if (e != SupportedEncoding.UTF8 && expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); return; } // Move ahead of whitespace for (i = encEq + 1; i < max && IsWhitespace(buffer[i]); i++) ; // Find the quotes if (buffer[i] != '\'' && buffer[i] != '"') throw new XmlException(SR.XmlMalformedDecl); quot = buffer[i]; int q = i; for (i = q + 1; buffer[i] != quot && i < max; ++i) ; if (buffer[i] != quot) throw new XmlException(SR.XmlMalformedDecl); int encStart = q + 1; int encCount = i - encStart; // lookup the encoding SupportedEncoding declEnc = e; if (encCount == s_encodingUTF8.Length && CompareCaseInsensitive(s_encodingUTF8, buffer, encStart)) { declEnc = SupportedEncoding.UTF8; } else if (encCount == s_encodingUnicodeLE.Length && CompareCaseInsensitive(s_encodingUnicodeLE, buffer, encStart)) { declEnc = SupportedEncoding.UTF16LE; } else if (encCount == s_encodingUnicodeBE.Length && CompareCaseInsensitive(s_encodingUnicodeBE, buffer, encStart)) { declEnc = SupportedEncoding.UTF16BE; } else if (encCount == s_encodingUnicode.Length && CompareCaseInsensitive(s_encodingUnicode, buffer, encStart)) { if (e == SupportedEncoding.UTF8) ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), s_safeUTF8.GetString(s_encodingUTF8, 0, s_encodingUTF8.Length)); } else { ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), e); } if (e != declEnc) ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), e); } private static bool CompareCaseInsensitive(byte[] key, byte[] buffer, int offset) { for (int i = 0; i < key.Length; i++) { if (key[i] == buffer[offset + i]) continue; if (key[i] != char.ToLowerInvariant((char)buffer[offset + i])) return false; } return true; } private static bool Compare(byte[] key, byte[] buffer, int offset) { for (int i = 0; i < key.Length; i++) { if (key[i] != buffer[offset + i]) return false; } return true; } private static bool IsWhitespace(byte ch) { return ch == (byte)' ' || ch == (byte)'\n' || ch == (byte)'\t' || ch == (byte)'\r'; } internal static ArraySegment<byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding? encoding) { if (count < 4) throw new XmlException(SR.UnexpectedEndOfFile); try { int preserve; ArraySegment<byte> seg; SupportedEncoding expectedEnc = GetSupportedEncoding(encoding); SupportedEncoding declEnc = ReadBOMEncoding(buffer[offset], buffer[offset + 1], buffer[offset + 2], buffer[offset + 3], encoding == null, out preserve); if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc) ThrowExpectedEncodingMismatch(expectedEnc, declEnc); offset += 4 - preserve; count -= 4 - preserve; // Fastpath: UTF-8 char[] chars; byte[] bytes; Encoding localEnc; if (declEnc == SupportedEncoding.UTF8) { // Fastpath: No declaration if (buffer[offset + 1] != '?' || buffer[offset] != '<') { seg = new ArraySegment<byte>(buffer, offset, count); return seg; } CheckUTF8DeclarationEncoding(buffer, offset, count, declEnc, expectedEnc); seg = new ArraySegment<byte>(buffer, offset, count); return seg; } // Convert to UTF-8 localEnc = GetSafeEncoding(declEnc); int inputCount = Math.Min(count, BufferLength * 2); chars = new char[localEnc.GetMaxCharCount(inputCount)]; int ccount = localEnc.GetChars(buffer, offset, inputCount, chars, 0); bytes = new byte[s_validatingUTF8.GetMaxByteCount(ccount)]; int bcount = s_validatingUTF8.GetBytes(chars, 0, ccount, bytes, 0); // Check for declaration if (bytes[1] == '?' && bytes[0] == '<') { CheckUTF8DeclarationEncoding(bytes, 0, bcount, declEnc, expectedEnc); } else { // Declaration required if no out-of-band encoding if (expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); } seg = new ArraySegment<byte>(s_validatingUTF8.GetBytes(GetEncoding(declEnc).GetChars(buffer, offset, count))); return seg; } catch (DecoderFallbackException e) { throw new XmlException(SR.XmlInvalidBytes, e); } } private static void ThrowExpectedEncodingMismatch(SupportedEncoding expEnc, SupportedEncoding actualEnc) { throw new XmlException(SR.Format(SR.XmlExpectedEncoding, GetEncodingName(expEnc), GetEncodingName(actualEnc))); } private static void ThrowEncodingMismatch(string declEnc, SupportedEncoding enc) { ThrowEncodingMismatch(declEnc, GetEncodingName(enc)); } private static void ThrowEncodingMismatch(string declEnc, string docEnc) { throw new XmlException(SR.Format(SR.XmlEncodingMismatch, declEnc, docEnc)); } // This stream wrapper does not support duplex public override bool CanRead { get { if (!_isReading) return false; return _stream.CanRead; } } // The encoding conversion and buffering breaks seeking. public override bool CanSeek { get { return false; } } // This stream wrapper does not support duplex public override bool CanWrite { get { if (_isReading) return false; return _stream.CanWrite; } } // The encoding conversion and buffering breaks seeking. public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } protected override void Dispose(bool disposing) { if (_stream.CanWrite) { Flush(); } _stream.Dispose(); base.Dispose(disposing); } public override void Flush() { _stream.Flush(); } public override int ReadByte() { if (_byteCount == 0 && _encodingCode == SupportedEncoding.UTF8) return _stream.ReadByte(); if (Read(_byteBuffer, 0, 1) == 0) return -1; return _byteBuffer[0]; } public override int Read(byte[] buffer, int offset, int count) { try { if (_byteCount == 0) { if (_encodingCode == SupportedEncoding.UTF8) return _stream.Read(buffer, offset, count); Debug.Assert(_bytes != null); Debug.Assert(_chars != null); // No more bytes than can be turned into characters _byteOffset = 0; _byteCount = _stream.Read(_bytes, _byteCount, (_chars.Length - 1) * 2); // Check for end of stream if (_byteCount == 0) return 0; // Fix up incomplete chars CleanupCharBreak(); // Change encoding int charCount = _encoding!.GetChars(_bytes, 0, _byteCount, _chars, 0); _byteCount = Encoding.UTF8.GetBytes(_chars, 0, charCount, _bytes, 0); } // Give them bytes if (_byteCount < count) count = _byteCount; Buffer.BlockCopy(_bytes!, _byteOffset, buffer, offset, count); _byteOffset += count; _byteCount -= count; return count; } catch (DecoderFallbackException ex) { throw new XmlException(SR.XmlInvalidBytes, ex); } } private void CleanupCharBreak() { Debug.Assert(_bytes != null); int max = _byteOffset + _byteCount; // Read on 2 byte boundaries if ((_byteCount % 2) != 0) { int b = _stream.ReadByte(); if (b < 0) throw new XmlException(SR.UnexpectedEndOfFile); _bytes[max++] = (byte)b; _byteCount++; } // Don't cut off a surrogate character int w; if (_encodingCode == SupportedEncoding.UTF16LE) { w = _bytes[max - 2] + (_bytes[max - 1] << 8); } else { w = _bytes[max - 1] + (_bytes[max - 2] << 8); } if ((w & 0xDC00) != 0xDC00 && w >= 0xD800 && w <= 0xDBFF) // First 16-bit number of surrogate pair { int b1 = _stream.ReadByte(); int b2 = _stream.ReadByte(); if (b2 < 0) throw new XmlException(SR.UnexpectedEndOfFile); _bytes[max++] = (byte)b1; _bytes[max++] = (byte)b2; _byteCount += 2; } } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void WriteByte(byte b) { if (_encodingCode == SupportedEncoding.UTF8) { _stream.WriteByte(b); return; } _byteBuffer[0] = b; Write(_byteBuffer, 0, 1); } public override void Write(byte[] buffer, int offset, int count) { // Optimize UTF-8 case if (_encodingCode == SupportedEncoding.UTF8) { _stream.Write(buffer, offset, count); return; } Debug.Assert(_bytes != null); Debug.Assert(_chars != null); while (count > 0) { int size = _chars.Length < count ? _chars.Length : count; int charCount = _dec!.GetChars(buffer, offset, size, _chars, 0, false); _byteCount = _enc!.GetBytes(_chars, 0, charCount, _bytes, 0, false); _stream.Write(_bytes, 0, _byteCount); offset += size; count -= size; } } // Delegate properties public override bool CanTimeout { get { return _stream.CanTimeout; } } public override long Length { get { return _stream.Length; } } public override int ReadTimeout { get { return _stream.ReadTimeout; } set { _stream.ReadTimeout = value; } } public override int WriteTimeout { get { return _stream.WriteTimeout; } set { _stream.WriteTimeout = value; } } // Delegate methods public override void SetLength(long value) { throw new NotSupportedException(); } } // Add format exceptions // Do we need to modify the stream position/Seek to account for the buffer? // ASSUMPTION (Microsoft): This class will only be used for EITHER reading OR writing. }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.ComponentModel/tests/CancelEventArgsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.ComponentModel.Tests { public class CancelEventArgsTests { [Fact] public void Ctor_Default() { var eventArgs = new CancelEventArgs(); Assert.False(eventArgs.Cancel); } [Theory] [InlineData(true)] [InlineData(false)] public void Ctor_Cancel(bool cancel) { var eventArgs = new CancelEventArgs(cancel); Assert.Equal(cancel, eventArgs.Cancel); } [Fact] public void Cancel_Set_GetReturnsExpected() { var eventArgs = new CancelEventArgs(); for (int i = 0; i < 2; i++) { eventArgs.Cancel = false; Assert.False(eventArgs.Cancel); eventArgs.Cancel = true; Assert.True(eventArgs.Cancel); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.ComponentModel.Tests { public class CancelEventArgsTests { [Fact] public void Ctor_Default() { var eventArgs = new CancelEventArgs(); Assert.False(eventArgs.Cancel); } [Theory] [InlineData(true)] [InlineData(false)] public void Ctor_Cancel(bool cancel) { var eventArgs = new CancelEventArgs(cancel); Assert.Equal(cancel, eventArgs.Cancel); } [Fact] public void Cancel_Set_GetReturnsExpected() { var eventArgs = new CancelEventArgs(); for (int i = 0; i < 2; i++) { eventArgs.Cancel = false; Assert.False(eventArgs.Cancel); eventArgs.Cancel = true; Assert.True(eventArgs.Cancel); } } } }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/Common/src/Interop/Windows/Kernel32/Interop.SetProcessPriorityBoost.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Kernel32 { [GeneratedDllImport(Libraries.Kernel32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool SetProcessPriorityBoost(SafeProcessHandle handle, [MarshalAs(UnmanagedType.Bool)] bool disabled); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Kernel32 { [GeneratedDllImport(Libraries.Kernel32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool SetProcessPriorityBoost(SafeProcessHandle handle, [MarshalAs(UnmanagedType.Bool)] bool disabled); } }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/tests/JIT/Regression/JitBlue/Runtime_33972/Runtime_33972.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.CompilerServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; class Program { // CompareEqual [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<byte> AdvSimd_CompareEqual_Vector64_Byte_Zero(Vector64<byte> left) { return AdvSimd.CompareEqual(left, Vector64<byte>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<sbyte> AdvSimd_CompareEqual_Vector64_SByte_Zero(Vector64<sbyte> left) { return AdvSimd.CompareEqual(left, Vector64<sbyte>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<ushort> AdvSimd_CompareEqual_Vector64_UInt16_Zero(Vector64<ushort> left) { return AdvSimd.CompareEqual(left, Vector64<ushort>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<short> AdvSimd_CompareEqual_Vector64_Int16_Zero(Vector64<short> left) { return AdvSimd.CompareEqual(left, Vector64<short>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<uint> AdvSimd_CompareEqual_Vector64_UInt32_Zero(Vector64<uint> left) { return AdvSimd.CompareEqual(left, Vector64<uint>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<int> AdvSimd_CompareEqual_Vector64_Int32_Zero(Vector64<int> left) { return AdvSimd.CompareEqual(left, Vector64<int>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<float> AdvSimd_CompareEqual_Vector64_Single_Zero(Vector64<float> left) { return AdvSimd.CompareEqual(left, Vector64<float>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<int> AdvSimd_CompareEqual_Vector64_Int32_CreateZero(Vector64<int> left) { return AdvSimd.CompareEqual(left, Vector64.Create(0)); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<int> AdvSimd_CompareEqual_Vector64_Int32_CreateZeroZero(Vector64<int> left) { return AdvSimd.CompareEqual(left, Vector64.Create(0, 0)); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<float> AdvSimd_CompareEqual_Vector64_Single_CreateZero(Vector64<float> left) { return AdvSimd.CompareEqual(left, Vector64.Create(0f)); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<float> AdvSimd_CompareEqual_Vector64_Single_CreateZeroZero(Vector64<float> left) { return AdvSimd.CompareEqual(left, Vector64.Create(0f, 0f)); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<byte> AdvSimd_CompareEqual_Vector128_Byte_Zero(Vector128<byte> left) { return AdvSimd.CompareEqual(left, Vector128<byte>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<sbyte> AdvSimd_CompareEqual_Vector128_SByte_Zero(Vector128<sbyte> left) { return AdvSimd.CompareEqual(left, Vector128<sbyte>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<ushort> AdvSimd_CompareEqual_Vector128_UInt16_Zero(Vector128<ushort> left) { return AdvSimd.CompareEqual(left, Vector128<ushort>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<short> AdvSimd_CompareEqual_Vector128_Int16_Zero(Vector128<short> left) { return AdvSimd.CompareEqual(left, Vector128<short>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<uint> AdvSimd_CompareEqual_Vector128_UInt32_Zero(Vector128<uint> left) { return AdvSimd.CompareEqual(left, Vector128<uint>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<int> AdvSimd_CompareEqual_Vector128_Int32_Zero(Vector128<int> left) { return AdvSimd.CompareEqual(left, Vector128<int>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<float> AdvSimd_CompareEqual_Vector128_Single_Zero(Vector128<float> left) { return AdvSimd.CompareEqual(left, Vector128<float>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<int> AdvSimd_CompareEqual_Vector128_Int32_CreateZero(Vector128<int> left) { return AdvSimd.CompareEqual(left, Vector128.Create(0)); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<int> AdvSimd_CompareEqual_Vector128_Int32_CreateZeroZeroZeroZero(Vector128<int> left) { return AdvSimd.CompareEqual(left, Vector128.Create(0, 0, 0, 0)); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<float> AdvSimd_CompareEqual_Vector128_Single_CreateZero(Vector128<float> left) { return AdvSimd.CompareEqual(left, Vector128.Create(0f)); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<float> AdvSimd_CompareEqual_Vector128_Single_CreateZeroZeroZeroZero(Vector128<float> left) { return AdvSimd.CompareEqual(left, Vector128.Create(0f, 0f, 0f, 0f)); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<float> AdvSimd_CompareEqual_Vector128_Single_CreateZeroZeroZeroZero_AsVariable(Vector128<float> left) { var asVar = Vector128.Create(0f, 0f, 0f, 0f); return AdvSimd.CompareEqual(left, asVar); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<float> AdvSimd_CompareEqual_Vector128_Single_CreateZeroZeroZeroZero_AsVariableLoop(Vector128<float> left) { Vector128<float> result = default; var asVar = Vector128.Create(0f, 0f, 0f, 0f); for (var i = 0; i < 4; i++) { result = AdvSimd.CompareEqual(left, asVar); result = AdvSimd.CompareEqual(left, asVar); result = AdvSimd.CompareEqual(left, asVar); result = AdvSimd.CompareEqual(left, asVar); for (var j = 0; j < 4; j++) { result = AdvSimd.CompareEqual(left, asVar); result = AdvSimd.CompareEqual(left, asVar); result = AdvSimd.CompareEqual(left, asVar); result = AdvSimd.CompareEqual(left, asVar); } } return result; } [MethodImpl(MethodImplOptions.NoInlining)] static unsafe Vector128<long> AdvSimd_Arm64_CompareEqual_Vector128_Long_AsVariableLoop(Vector128<long> left) { Vector128<long> result = default; Vector128<long> asVar = Vector128.Create((long)0); Vector128<nint> asVar2 = Vector128.Create((nint)0); Vector128<long> asVar3 = asVar2.AsInt64(); for (var i = 0; i < 4; i++) { result = AdvSimd.Arm64.CompareEqual(left, asVar); for (var j = 0; j < 4; j++) { result = AdvSimd.Arm64.CompareEqual(left, asVar3); } } return result; } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<double> AdvSimd_Arm64_CompareEqual_Vector128_Double_Zero(Vector128<double> left) { return AdvSimd.Arm64.CompareEqual(left, Vector128<double>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<ulong> AdvSimd_Arm64_CompareEqual_Vector128_UInt64_Zero(Vector128<ulong> left) { return AdvSimd.Arm64.CompareEqual(left, Vector128<ulong>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<long> AdvSimd_Arm64_CompareEqual_Vector128_Int64_Zero(Vector128<long> left) { return AdvSimd.Arm64.CompareEqual(left, Vector128<long>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<float> AdvSimd_Arm64_CompareEqualScalar_Vector64_Single_Zero(Vector64<float> left) { return AdvSimd.Arm64.CompareEqualScalar(left, Vector64<float>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<double> AdvSimd_Arm64_CompareEqualScalar_Vector64_Double_Zero(Vector64<double> left) { return AdvSimd.Arm64.CompareEqualScalar(left, Vector64<double>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<ulong> AdvSimd_Arm64_CompareEqualScalar_Vector64_UInt64_Zero(Vector64<ulong> left) { return AdvSimd.Arm64.CompareEqualScalar(left, Vector64<ulong>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<long> AdvSimd_Arm64_CompareEqualScalar_Vector64_Int64_Zero(Vector64<long> left) { return AdvSimd.Arm64.CompareEqualScalar(left, Vector64<long>.Zero); } // CompareEqual Swapped [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<byte> AdvSimd_CompareEqual_Vector64_Byte_Zero_Swapped(Vector64<byte> right) { return AdvSimd.CompareEqual(Vector64<byte>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<sbyte> AdvSimd_CompareEqual_Vector64_SByte_Zero_Swapped(Vector64<sbyte> right) { return AdvSimd.CompareEqual(Vector64<sbyte>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<ushort> AdvSimd_CompareEqual_Vector64_UInt16_Zero_Swapped(Vector64<ushort> right) { return AdvSimd.CompareEqual(Vector64<ushort>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<short> AdvSimd_CompareEqual_Vector64_Int16_Zero_Swapped(Vector64<short> right) { return AdvSimd.CompareEqual(Vector64<short>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<uint> AdvSimd_CompareEqual_Vector64_UInt32_Zero_Swapped(Vector64<uint> right) { return AdvSimd.CompareEqual(Vector64<uint>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<int> AdvSimd_CompareEqual_Vector64_Int32_Zero_Swapped(Vector64<int> right) { return AdvSimd.CompareEqual(Vector64<int>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<float> AdvSimd_CompareEqual_Vector64_Single_Zero_Swapped(Vector64<float> right) { return AdvSimd.CompareEqual(Vector64<float>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<byte> AdvSimd_CompareEqual_Vector128_Byte_Zero_Swapped(Vector128<byte> right) { return AdvSimd.CompareEqual(Vector128<byte>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<sbyte> AdvSimd_CompareEqual_Vector128_SByte_Zero_Swapped(Vector128<sbyte> right) { return AdvSimd.CompareEqual(Vector128<sbyte>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<ushort> AdvSimd_CompareEqual_Vector128_UInt16_Zero_Swapped(Vector128<ushort> right) { return AdvSimd.CompareEqual(Vector128<ushort>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<short> AdvSimd_CompareEqual_Vector128_Int16_Zero_Swapped(Vector128<short> right) { return AdvSimd.CompareEqual(Vector128<short>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<uint> AdvSimd_CompareEqual_Vector128_UInt32_Zero_Swapped(Vector128<uint> right) { return AdvSimd.CompareEqual(Vector128<uint>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<int> AdvSimd_CompareEqual_Vector128_Int32_Zero_Swapped(Vector128<int> right) { return AdvSimd.CompareEqual(Vector128<int>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<float> AdvSimd_CompareEqual_Vector128_Single_Zero_Swapped(Vector128<float> right) { return AdvSimd.CompareEqual(Vector128<float>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<double> AdvSimd_Arm64_CompareEqual_Vector128_Double_Zero_Swapped(Vector128<double> right) { return AdvSimd.Arm64.CompareEqual(Vector128<double>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<ulong> AdvSimd_Arm64_CompareEqual_Vector128_UInt64_Zero_Swapped(Vector128<ulong> right) { return AdvSimd.Arm64.CompareEqual(Vector128<ulong>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<long> AdvSimd_Arm64_CompareEqual_Vector128_Int64_Zero_Swapped(Vector128<long> right) { return AdvSimd.Arm64.CompareEqual(Vector128<long>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<float> AdvSimd_Arm64_CompareEqualScalar_Vector64_Single_Zero_Swapped(Vector64<float> right) { return AdvSimd.Arm64.CompareEqualScalar(Vector64<float>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<double> AdvSimd_Arm64_CompareEqualScalar_Vector64_Double_Zero_Swapped(Vector64<double> right) { return AdvSimd.Arm64.CompareEqualScalar(Vector64<double>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<ulong> AdvSimd_Arm64_CompareEqualScalar_Vector64_UInt64_Zero_Swapped(Vector64<ulong> right) { return AdvSimd.Arm64.CompareEqualScalar(Vector64<ulong>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<long> AdvSimd_Arm64_CompareEqualScalar_Vector64_Int64_Zero_Swapped(Vector64<long> right) { return AdvSimd.Arm64.CompareEqualScalar(Vector64<long>.Zero, right); } // CompareGreaterThan [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<byte> AdvSimd_CompareGreaterThan_Vector64_Byte_Zero(Vector64<byte> left) { return AdvSimd.CompareGreaterThan(left, Vector64<byte>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<float> AdvSimd_CompareGreaterThan_Vector64_Single_Zero(Vector64<float> left) { return AdvSimd.CompareGreaterThan(left, Vector64<float>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<byte> AdvSimd_CompareGreaterThan_Vector128_Byte_Zero(Vector128<byte> left) { return AdvSimd.CompareGreaterThan(left, Vector128<byte>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<float> AdvSimd_CompareGreaterThan_Vector128_Single_Zero(Vector128<float> left) { return AdvSimd.CompareGreaterThan(left, Vector128<float>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<double> AdvSimd_Arm64_CompareGreaterThan_Vector128_Double_Zero(Vector128<double> left) { return AdvSimd.Arm64.CompareGreaterThan(left, Vector128<double>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<long> AdvSimd_Arm64_CompareGreaterThan_Vector128_Int64_Zero(Vector128<long> left) { return AdvSimd.Arm64.CompareGreaterThan(left, Vector128<long>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<double> AdvSimd_Arm64_CompareGreaterThanScalar_Vector64_Double_Zero(Vector64<double> left) { return AdvSimd.Arm64.CompareGreaterThanScalar(left, Vector64<double>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<long> AdvSimd_Arm64_CompareGreaterThanScalar_Vector64_Int64_Zero(Vector64<long> left) { return AdvSimd.Arm64.CompareGreaterThanScalar(left, Vector64<long>.Zero); } // CompareGreaterThanOrEqual [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<byte> AdvSimd_CompareGreaterThanOrEqual_Vector64_Byte_Zero(Vector64<byte> left) { return AdvSimd.CompareGreaterThanOrEqual(left, Vector64<byte>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<float> AdvSimd_CompareGreaterThanOrEqual_Vector64_Single_Zero(Vector64<float> left) { return AdvSimd.CompareGreaterThanOrEqual(left, Vector64<float>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<byte> AdvSimd_CompareGreaterThanOrEqual_Vector128_Byte_Zero(Vector128<byte> left) { return AdvSimd.CompareGreaterThanOrEqual(left, Vector128<byte>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<float> AdvSimd_CompareGreaterThanOrEqual_Vector128_Single_Zero(Vector128<float> left) { return AdvSimd.CompareGreaterThanOrEqual(left, Vector128<float>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<double> AdvSimd_Arm64_CompareGreaterThanOrEqual_Vector128_Double_Zero(Vector128<double> left) { return AdvSimd.Arm64.CompareGreaterThanOrEqual(left, Vector128<double>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<long> AdvSimd_Arm64_CompareGreaterThanOrEqual_Vector128_Int64_Zero(Vector128<long> left) { return AdvSimd.Arm64.CompareGreaterThanOrEqual(left, Vector128<long>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<double> AdvSimd_Arm64_CompareGreaterThanOrEqualScalar_Vector64_Double_Zero(Vector64<double> left) { return AdvSimd.Arm64.CompareGreaterThanOrEqualScalar(left, Vector64<double>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<long> AdvSimd_Arm64_CompareGreaterThanOrEqualScalar_Vector64_Int64_Zero(Vector64<long> left) { return AdvSimd.Arm64.CompareGreaterThanOrEqualScalar(left, Vector64<long>.Zero); } // Validation unsafe static bool ValidateResult_Vector64<T>(Vector64<T> result, T expectedElementValue) where T : unmanaged { var succeeded = true; for (var i = 0; i < (8 / sizeof(T)); i++) { if (!result.GetElement(i).Equals(expectedElementValue)) { succeeded = false; } } return succeeded; } unsafe static bool ValidateResult_Vector64<T>(Vector64<T> result, Vector64<T> expectedElementValue) where T : unmanaged { var succeeded = true; for (var i = 0; i < (8 / sizeof(T)); i++) { if (!result.GetElement(i).Equals(expectedElementValue.GetElement(i))) { succeeded = false; } } return succeeded; } unsafe static bool ValidateResult_Vector128<T>(Vector128<T> result, T expectedElementValue) where T : unmanaged { var succeeded = true; for (var i = 0; i < (16 / sizeof(T)); i++) { if (!result.GetElement(i).Equals(expectedElementValue)) { succeeded = false; } } return succeeded; } unsafe static bool ValidateResult_Vector128<T>(Vector128<T> result, Vector128<T> expectedElementValue) where T : unmanaged { var succeeded = true; for (var i = 0; i < (16 / sizeof(T)); i++) { if (!result.GetElement(i).Equals(expectedElementValue.GetElement(i))) { succeeded = false; } } return succeeded; } static int Tests_AdvSimd() { var result = 100; // Begin CompareEqual Tests // Vector64 if (!ValidateResult_Vector64<byte>(AdvSimd_CompareEqual_Vector64_Byte_Zero(Vector64<byte>.Zero), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector64<sbyte>(AdvSimd_CompareEqual_Vector64_SByte_Zero(Vector64<sbyte>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<ushort>(AdvSimd_CompareEqual_Vector64_UInt16_Zero(Vector64<ushort>.Zero), UInt16.MaxValue)) result = -1; if (!ValidateResult_Vector64<short>(AdvSimd_CompareEqual_Vector64_Int16_Zero(Vector64<short>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<uint>(AdvSimd_CompareEqual_Vector64_UInt32_Zero(Vector64<uint>.Zero), UInt32.MaxValue)) result = -1; if (!ValidateResult_Vector64<int>(AdvSimd_CompareEqual_Vector64_Int32_Zero(Vector64<int>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<float>(AdvSimd_CompareEqual_Vector64_Single_Zero(Vector64<float>.Zero), Single.NaN)) result = -1; // Vector64.Create if (!ValidateResult_Vector64<int>(AdvSimd_CompareEqual_Vector64_Int32_CreateZero(Vector64<int>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<float>(AdvSimd_CompareEqual_Vector64_Single_CreateZero(Vector64<float>.Zero), Single.NaN)) result = -1; if (!ValidateResult_Vector64<int>(AdvSimd_CompareEqual_Vector64_Int32_CreateZeroZero(Vector64<int>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<float>(AdvSimd_CompareEqual_Vector64_Single_CreateZeroZero(Vector64<float>.Zero), Single.NaN)) result = -1; // Vector128 if (!ValidateResult_Vector128<byte>(AdvSimd_CompareEqual_Vector128_Byte_Zero(Vector128<byte>.Zero), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector128<sbyte>(AdvSimd_CompareEqual_Vector128_SByte_Zero(Vector128<sbyte>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<ushort>(AdvSimd_CompareEqual_Vector128_UInt16_Zero(Vector128<ushort>.Zero), UInt16.MaxValue)) result = -1; if (!ValidateResult_Vector128<short>(AdvSimd_CompareEqual_Vector128_Int16_Zero(Vector128<short>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<uint>(AdvSimd_CompareEqual_Vector128_UInt32_Zero(Vector128<uint>.Zero), UInt32.MaxValue)) result = -1; if (!ValidateResult_Vector128<int>(AdvSimd_CompareEqual_Vector128_Int32_Zero(Vector128<int>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareEqual_Vector128_Single_Zero(Vector128<float>.Zero), Single.NaN)) result = -1; // Vector128.Create if (!ValidateResult_Vector128<int>(AdvSimd_CompareEqual_Vector128_Int32_CreateZero(Vector128<int>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareEqual_Vector128_Single_CreateZero(Vector128<float>.Zero), Single.NaN)) result = -1; if (!ValidateResult_Vector128<int>(AdvSimd_CompareEqual_Vector128_Int32_CreateZeroZeroZeroZero(Vector128<int>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareEqual_Vector128_Single_CreateZeroZeroZeroZero(Vector128<float>.Zero), Single.NaN)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareEqual_Vector128_Single_CreateZeroZeroZeroZero_AsVariable(Vector128<float>.Zero), Single.NaN)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareEqual_Vector128_Single_CreateZeroZeroZeroZero_AsVariableLoop(Vector128<float>.Zero), Single.NaN)) result = -1; // End CompareEqual Tests // Begin CompareGreaterThan Tests if (!ValidateResult_Vector64<byte>(AdvSimd_CompareGreaterThan_Vector64_Byte_Zero(Vector64.Create((byte)1)), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector64<float>(AdvSimd_CompareGreaterThan_Vector64_Single_Zero(Vector64.Create(1.0f)), Single.NaN)) result = -1; if (!ValidateResult_Vector128<byte>(AdvSimd_CompareGreaterThan_Vector128_Byte_Zero(Vector128.Create((byte)1)), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareGreaterThan_Vector128_Single_Zero(Vector128.Create(1.0f)), Single.NaN)) result = -1; if (!ValidateResult_Vector128<double>(AdvSimd_Arm64_CompareGreaterThan_Vector128_Double_Zero(Vector128.Create(1.0)), Double.NaN)) result = -1; if (!ValidateResult_Vector128<long>(AdvSimd_Arm64_CompareGreaterThan_Vector128_Int64_Zero(Vector128.Create(1L)), -1)) result = -1; if (!ValidateResult_Vector64<double>(AdvSimd_Arm64_CompareGreaterThanScalar_Vector64_Double_Zero(Vector64.Create(1.0)), Double.NaN)) result = -1; if (!ValidateResult_Vector64<long>(AdvSimd_Arm64_CompareGreaterThanScalar_Vector64_Int64_Zero(Vector64.Create(1L)), -1)) result = -1; if (ValidateResult_Vector64<byte>(AdvSimd_CompareGreaterThan_Vector64_Byte_Zero(Vector64<byte>.Zero), Byte.MaxValue)) result = -1; if (ValidateResult_Vector64<float>(AdvSimd_CompareGreaterThan_Vector64_Single_Zero(Vector64<float>.Zero), Single.NaN)) result = -1; if (ValidateResult_Vector128<byte>(AdvSimd_CompareGreaterThan_Vector128_Byte_Zero(Vector128<byte>.Zero), Byte.MaxValue)) result = -1; if (ValidateResult_Vector128<float>(AdvSimd_CompareGreaterThan_Vector128_Single_Zero(Vector128<float>.Zero), Single.NaN)) result = -1; if (ValidateResult_Vector128<double>(AdvSimd_Arm64_CompareGreaterThan_Vector128_Double_Zero(Vector128<double>.Zero), Double.NaN)) result = -1; if (ValidateResult_Vector128<long>(AdvSimd_Arm64_CompareGreaterThan_Vector128_Int64_Zero(Vector128<long>.Zero), -1)) result = -1; if (ValidateResult_Vector64<double>(AdvSimd_Arm64_CompareGreaterThanScalar_Vector64_Double_Zero(Vector64<double>.Zero), Double.NaN)) result = -1; if (ValidateResult_Vector64<long>(AdvSimd_Arm64_CompareGreaterThanScalar_Vector64_Int64_Zero(Vector64<long>.Zero), -1)) result = -1; // End CompareGreaterThan Tests // Begin CompareGreaterThanOrEqual Tests if (!ValidateResult_Vector64<byte>(AdvSimd_CompareGreaterThanOrEqual_Vector64_Byte_Zero(Vector64.Create((byte)1)), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector64<float>(AdvSimd_CompareGreaterThanOrEqual_Vector64_Single_Zero(Vector64.Create(1.0f)), Single.NaN)) result = -1; if (!ValidateResult_Vector128<byte>(AdvSimd_CompareGreaterThanOrEqual_Vector128_Byte_Zero(Vector128.Create((byte)1)), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareGreaterThanOrEqual_Vector128_Single_Zero(Vector128.Create(1.0f)), Single.NaN)) result = -1; if (!ValidateResult_Vector128<double>(AdvSimd_Arm64_CompareGreaterThanOrEqual_Vector128_Double_Zero(Vector128.Create(1.0)), Double.NaN)) result = -1; if (!ValidateResult_Vector128<long>(AdvSimd_Arm64_CompareGreaterThanOrEqual_Vector128_Int64_Zero(Vector128.Create(1L)), -1)) result = -1; if (!ValidateResult_Vector64<double>(AdvSimd_Arm64_CompareGreaterThanOrEqualScalar_Vector64_Double_Zero(Vector64.Create(1.0)), Double.NaN)) result = -1; if (!ValidateResult_Vector64<long>(AdvSimd_Arm64_CompareGreaterThanOrEqualScalar_Vector64_Int64_Zero(Vector64.Create(1L)), -1)) result = -1; if (!ValidateResult_Vector64<byte>(AdvSimd_CompareGreaterThanOrEqual_Vector64_Byte_Zero(Vector64<byte>.Zero), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector64<float>(AdvSimd_CompareGreaterThanOrEqual_Vector64_Single_Zero(Vector64<float>.Zero), Single.NaN)) result = -1; if (!ValidateResult_Vector128<byte>(AdvSimd_CompareGreaterThanOrEqual_Vector128_Byte_Zero(Vector128<byte>.Zero), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareGreaterThanOrEqual_Vector128_Single_Zero(Vector128<float>.Zero), Single.NaN)) result = -1; if (!ValidateResult_Vector128<double>(AdvSimd_Arm64_CompareGreaterThanOrEqual_Vector128_Double_Zero(Vector128<double>.Zero), Double.NaN)) result = -1; if (!ValidateResult_Vector128<long>(AdvSimd_Arm64_CompareGreaterThanOrEqual_Vector128_Int64_Zero(Vector128<long>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<double>(AdvSimd_Arm64_CompareGreaterThanOrEqualScalar_Vector64_Double_Zero(Vector64<double>.Zero), Double.NaN)) result = -1; if (!ValidateResult_Vector64<long>(AdvSimd_Arm64_CompareGreaterThanOrEqualScalar_Vector64_Int64_Zero(Vector64<long>.Zero), -1)) result = -1; // End CompareGreaterThanOrEqual Tests return result; } static int Tests_AdvSimd_Swapped() { var result = 100; // Begin CompareEqual Tests // Vector64 if (!ValidateResult_Vector64<byte>(AdvSimd_CompareEqual_Vector64_Byte_Zero_Swapped(Vector64<byte>.Zero), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector64<sbyte>(AdvSimd_CompareEqual_Vector64_SByte_Zero_Swapped(Vector64<sbyte>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<ushort>(AdvSimd_CompareEqual_Vector64_UInt16_Zero_Swapped(Vector64<ushort>.Zero), UInt16.MaxValue)) result = -1; if (!ValidateResult_Vector64<short>(AdvSimd_CompareEqual_Vector64_Int16_Zero_Swapped(Vector64<short>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<uint>(AdvSimd_CompareEqual_Vector64_UInt32_Zero_Swapped(Vector64<uint>.Zero), UInt32.MaxValue)) result = -1; if (!ValidateResult_Vector64<int>(AdvSimd_CompareEqual_Vector64_Int32_Zero_Swapped(Vector64<int>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<float>(AdvSimd_CompareEqual_Vector64_Single_Zero_Swapped(Vector64<float>.Zero), Single.NaN)) result = -1; // Vector128 if (!ValidateResult_Vector128<byte>(AdvSimd_CompareEqual_Vector128_Byte_Zero_Swapped(Vector128<byte>.Zero), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector128<sbyte>(AdvSimd_CompareEqual_Vector128_SByte_Zero_Swapped(Vector128<sbyte>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<ushort>(AdvSimd_CompareEqual_Vector128_UInt16_Zero_Swapped(Vector128<ushort>.Zero), UInt16.MaxValue)) result = -1; if (!ValidateResult_Vector128<short>(AdvSimd_CompareEqual_Vector128_Int16_Zero_Swapped(Vector128<short>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<uint>(AdvSimd_CompareEqual_Vector128_UInt32_Zero_Swapped(Vector128<uint>.Zero), UInt32.MaxValue)) result = -1; if (!ValidateResult_Vector128<int>(AdvSimd_CompareEqual_Vector128_Int32_Zero_Swapped(Vector128<int>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareEqual_Vector128_Single_Zero_Swapped(Vector128<float>.Zero), Single.NaN)) result = -1; // End CompareEqual Tests return result; } static int Tests_AdvSimd_Arm64() { var result = 100; // Begin CompareEqual Tests // Vector128 if (!ValidateResult_Vector128<double>(AdvSimd_Arm64_CompareEqual_Vector128_Double_Zero(Vector128<double>.Zero), Double.NaN)) result = -1; if (!ValidateResult_Vector128<ulong>(AdvSimd_Arm64_CompareEqual_Vector128_UInt64_Zero(Vector128<ulong>.Zero), UInt64.MaxValue)) result = -1; if (!ValidateResult_Vector128<long>(AdvSimd_Arm64_CompareEqual_Vector128_Int64_Zero(Vector128<long>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<long>(AdvSimd_Arm64_CompareEqual_Vector128_Long_AsVariableLoop(Vector128<long>.Zero), -1)) result = -1; // Vector64 if (!ValidateResult_Vector64<float>(AdvSimd_Arm64_CompareEqualScalar_Vector64_Single_Zero(Vector64<float>.Zero), Vector64.CreateScalar(Single.NaN))) result = -1; if (!ValidateResult_Vector64<double>(AdvSimd_Arm64_CompareEqualScalar_Vector64_Double_Zero(Vector64<double>.Zero), Vector64.CreateScalar(Double.NaN))) result = -1; if (!ValidateResult_Vector64<ulong>(AdvSimd_Arm64_CompareEqualScalar_Vector64_UInt64_Zero(Vector64<ulong>.Zero), Vector64.CreateScalar(UInt64.MaxValue))) result = -1; if (!ValidateResult_Vector64<long>(AdvSimd_Arm64_CompareEqualScalar_Vector64_Int64_Zero(Vector64<long>.Zero), Vector64.CreateScalar(-1L))) result = -1; // End CompareEqual Tests return result; } static int Tests_AdvSimd_Arm64_Swapped() { var result = 100; // Begin CompareEqual Tests // Vector128 if (!ValidateResult_Vector128<double>(AdvSimd_Arm64_CompareEqual_Vector128_Double_Zero_Swapped(Vector128<double>.Zero), Double.NaN)) result = -1; if (!ValidateResult_Vector128<ulong>(AdvSimd_Arm64_CompareEqual_Vector128_UInt64_Zero_Swapped(Vector128<ulong>.Zero), UInt64.MaxValue)) result = -1; if (!ValidateResult_Vector128<long>(AdvSimd_Arm64_CompareEqual_Vector128_Int64_Zero_Swapped(Vector128<long>.Zero), -1)) result = -1; // Vector64 if (!ValidateResult_Vector64<float>(AdvSimd_Arm64_CompareEqualScalar_Vector64_Single_Zero_Swapped(Vector64<float>.Zero), Vector64.CreateScalar(Single.NaN))) result = -1; if (!ValidateResult_Vector64<double>(AdvSimd_Arm64_CompareEqualScalar_Vector64_Double_Zero_Swapped(Vector64<double>.Zero), Vector64.CreateScalar(Double.NaN))) result = -1; if (!ValidateResult_Vector64<ulong>(AdvSimd_Arm64_CompareEqualScalar_Vector64_UInt64_Zero_Swapped(Vector64<ulong>.Zero), Vector64.CreateScalar(UInt64.MaxValue))) result = -1; if (!ValidateResult_Vector64<long>(AdvSimd_Arm64_CompareEqualScalar_Vector64_Int64_Zero_Swapped(Vector64<long>.Zero), Vector64.CreateScalar(-1L))) result = -1; // End CompareEqual Tests return result; } static int Main(string[] args) { var result = 100; if (AdvSimd.IsSupported) { Console.WriteLine("Testing AdvSimd"); if (result != -1) { result = Tests_AdvSimd(); } if (result != -1) { result = Tests_AdvSimd_Swapped(); } if (result == -1) { Console.WriteLine("AdvSimd Tests Failed"); } else { Console.WriteLine("AdvSimd Tests Passed"); } } else { Console.WriteLine("Skipped AdvSimd Tests"); } if (AdvSimd.Arm64.IsSupported) { Console.WriteLine("Testing AdvSimd_Arm64"); if (result != -1) { result = Tests_AdvSimd_Arm64(); } if (result != -1) { result = Tests_AdvSimd_Arm64_Swapped(); } if (result == -1) { Console.WriteLine("AdvSimd_Arm64 Tests Failed"); } else { Console.WriteLine("AdvSimd_Arm64 Tests Passed"); } } else { Console.WriteLine("Skipped AdvSimd_Arm64 Tests"); } return result; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.CompilerServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; class Program { // CompareEqual [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<byte> AdvSimd_CompareEqual_Vector64_Byte_Zero(Vector64<byte> left) { return AdvSimd.CompareEqual(left, Vector64<byte>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<sbyte> AdvSimd_CompareEqual_Vector64_SByte_Zero(Vector64<sbyte> left) { return AdvSimd.CompareEqual(left, Vector64<sbyte>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<ushort> AdvSimd_CompareEqual_Vector64_UInt16_Zero(Vector64<ushort> left) { return AdvSimd.CompareEqual(left, Vector64<ushort>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<short> AdvSimd_CompareEqual_Vector64_Int16_Zero(Vector64<short> left) { return AdvSimd.CompareEqual(left, Vector64<short>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<uint> AdvSimd_CompareEqual_Vector64_UInt32_Zero(Vector64<uint> left) { return AdvSimd.CompareEqual(left, Vector64<uint>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<int> AdvSimd_CompareEqual_Vector64_Int32_Zero(Vector64<int> left) { return AdvSimd.CompareEqual(left, Vector64<int>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<float> AdvSimd_CompareEqual_Vector64_Single_Zero(Vector64<float> left) { return AdvSimd.CompareEqual(left, Vector64<float>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<int> AdvSimd_CompareEqual_Vector64_Int32_CreateZero(Vector64<int> left) { return AdvSimd.CompareEqual(left, Vector64.Create(0)); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<int> AdvSimd_CompareEqual_Vector64_Int32_CreateZeroZero(Vector64<int> left) { return AdvSimd.CompareEqual(left, Vector64.Create(0, 0)); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<float> AdvSimd_CompareEqual_Vector64_Single_CreateZero(Vector64<float> left) { return AdvSimd.CompareEqual(left, Vector64.Create(0f)); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<float> AdvSimd_CompareEqual_Vector64_Single_CreateZeroZero(Vector64<float> left) { return AdvSimd.CompareEqual(left, Vector64.Create(0f, 0f)); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<byte> AdvSimd_CompareEqual_Vector128_Byte_Zero(Vector128<byte> left) { return AdvSimd.CompareEqual(left, Vector128<byte>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<sbyte> AdvSimd_CompareEqual_Vector128_SByte_Zero(Vector128<sbyte> left) { return AdvSimd.CompareEqual(left, Vector128<sbyte>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<ushort> AdvSimd_CompareEqual_Vector128_UInt16_Zero(Vector128<ushort> left) { return AdvSimd.CompareEqual(left, Vector128<ushort>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<short> AdvSimd_CompareEqual_Vector128_Int16_Zero(Vector128<short> left) { return AdvSimd.CompareEqual(left, Vector128<short>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<uint> AdvSimd_CompareEqual_Vector128_UInt32_Zero(Vector128<uint> left) { return AdvSimd.CompareEqual(left, Vector128<uint>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<int> AdvSimd_CompareEqual_Vector128_Int32_Zero(Vector128<int> left) { return AdvSimd.CompareEqual(left, Vector128<int>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<float> AdvSimd_CompareEqual_Vector128_Single_Zero(Vector128<float> left) { return AdvSimd.CompareEqual(left, Vector128<float>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<int> AdvSimd_CompareEqual_Vector128_Int32_CreateZero(Vector128<int> left) { return AdvSimd.CompareEqual(left, Vector128.Create(0)); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<int> AdvSimd_CompareEqual_Vector128_Int32_CreateZeroZeroZeroZero(Vector128<int> left) { return AdvSimd.CompareEqual(left, Vector128.Create(0, 0, 0, 0)); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<float> AdvSimd_CompareEqual_Vector128_Single_CreateZero(Vector128<float> left) { return AdvSimd.CompareEqual(left, Vector128.Create(0f)); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<float> AdvSimd_CompareEqual_Vector128_Single_CreateZeroZeroZeroZero(Vector128<float> left) { return AdvSimd.CompareEqual(left, Vector128.Create(0f, 0f, 0f, 0f)); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<float> AdvSimd_CompareEqual_Vector128_Single_CreateZeroZeroZeroZero_AsVariable(Vector128<float> left) { var asVar = Vector128.Create(0f, 0f, 0f, 0f); return AdvSimd.CompareEqual(left, asVar); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<float> AdvSimd_CompareEqual_Vector128_Single_CreateZeroZeroZeroZero_AsVariableLoop(Vector128<float> left) { Vector128<float> result = default; var asVar = Vector128.Create(0f, 0f, 0f, 0f); for (var i = 0; i < 4; i++) { result = AdvSimd.CompareEqual(left, asVar); result = AdvSimd.CompareEqual(left, asVar); result = AdvSimd.CompareEqual(left, asVar); result = AdvSimd.CompareEqual(left, asVar); for (var j = 0; j < 4; j++) { result = AdvSimd.CompareEqual(left, asVar); result = AdvSimd.CompareEqual(left, asVar); result = AdvSimd.CompareEqual(left, asVar); result = AdvSimd.CompareEqual(left, asVar); } } return result; } [MethodImpl(MethodImplOptions.NoInlining)] static unsafe Vector128<long> AdvSimd_Arm64_CompareEqual_Vector128_Long_AsVariableLoop(Vector128<long> left) { Vector128<long> result = default; Vector128<long> asVar = Vector128.Create((long)0); Vector128<nint> asVar2 = Vector128.Create((nint)0); Vector128<long> asVar3 = asVar2.AsInt64(); for (var i = 0; i < 4; i++) { result = AdvSimd.Arm64.CompareEqual(left, asVar); for (var j = 0; j < 4; j++) { result = AdvSimd.Arm64.CompareEqual(left, asVar3); } } return result; } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<double> AdvSimd_Arm64_CompareEqual_Vector128_Double_Zero(Vector128<double> left) { return AdvSimd.Arm64.CompareEqual(left, Vector128<double>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<ulong> AdvSimd_Arm64_CompareEqual_Vector128_UInt64_Zero(Vector128<ulong> left) { return AdvSimd.Arm64.CompareEqual(left, Vector128<ulong>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<long> AdvSimd_Arm64_CompareEqual_Vector128_Int64_Zero(Vector128<long> left) { return AdvSimd.Arm64.CompareEqual(left, Vector128<long>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<float> AdvSimd_Arm64_CompareEqualScalar_Vector64_Single_Zero(Vector64<float> left) { return AdvSimd.Arm64.CompareEqualScalar(left, Vector64<float>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<double> AdvSimd_Arm64_CompareEqualScalar_Vector64_Double_Zero(Vector64<double> left) { return AdvSimd.Arm64.CompareEqualScalar(left, Vector64<double>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<ulong> AdvSimd_Arm64_CompareEqualScalar_Vector64_UInt64_Zero(Vector64<ulong> left) { return AdvSimd.Arm64.CompareEqualScalar(left, Vector64<ulong>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<long> AdvSimd_Arm64_CompareEqualScalar_Vector64_Int64_Zero(Vector64<long> left) { return AdvSimd.Arm64.CompareEqualScalar(left, Vector64<long>.Zero); } // CompareEqual Swapped [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<byte> AdvSimd_CompareEqual_Vector64_Byte_Zero_Swapped(Vector64<byte> right) { return AdvSimd.CompareEqual(Vector64<byte>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<sbyte> AdvSimd_CompareEqual_Vector64_SByte_Zero_Swapped(Vector64<sbyte> right) { return AdvSimd.CompareEqual(Vector64<sbyte>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<ushort> AdvSimd_CompareEqual_Vector64_UInt16_Zero_Swapped(Vector64<ushort> right) { return AdvSimd.CompareEqual(Vector64<ushort>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<short> AdvSimd_CompareEqual_Vector64_Int16_Zero_Swapped(Vector64<short> right) { return AdvSimd.CompareEqual(Vector64<short>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<uint> AdvSimd_CompareEqual_Vector64_UInt32_Zero_Swapped(Vector64<uint> right) { return AdvSimd.CompareEqual(Vector64<uint>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<int> AdvSimd_CompareEqual_Vector64_Int32_Zero_Swapped(Vector64<int> right) { return AdvSimd.CompareEqual(Vector64<int>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<float> AdvSimd_CompareEqual_Vector64_Single_Zero_Swapped(Vector64<float> right) { return AdvSimd.CompareEqual(Vector64<float>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<byte> AdvSimd_CompareEqual_Vector128_Byte_Zero_Swapped(Vector128<byte> right) { return AdvSimd.CompareEqual(Vector128<byte>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<sbyte> AdvSimd_CompareEqual_Vector128_SByte_Zero_Swapped(Vector128<sbyte> right) { return AdvSimd.CompareEqual(Vector128<sbyte>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<ushort> AdvSimd_CompareEqual_Vector128_UInt16_Zero_Swapped(Vector128<ushort> right) { return AdvSimd.CompareEqual(Vector128<ushort>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<short> AdvSimd_CompareEqual_Vector128_Int16_Zero_Swapped(Vector128<short> right) { return AdvSimd.CompareEqual(Vector128<short>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<uint> AdvSimd_CompareEqual_Vector128_UInt32_Zero_Swapped(Vector128<uint> right) { return AdvSimd.CompareEqual(Vector128<uint>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<int> AdvSimd_CompareEqual_Vector128_Int32_Zero_Swapped(Vector128<int> right) { return AdvSimd.CompareEqual(Vector128<int>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<float> AdvSimd_CompareEqual_Vector128_Single_Zero_Swapped(Vector128<float> right) { return AdvSimd.CompareEqual(Vector128<float>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<double> AdvSimd_Arm64_CompareEqual_Vector128_Double_Zero_Swapped(Vector128<double> right) { return AdvSimd.Arm64.CompareEqual(Vector128<double>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<ulong> AdvSimd_Arm64_CompareEqual_Vector128_UInt64_Zero_Swapped(Vector128<ulong> right) { return AdvSimd.Arm64.CompareEqual(Vector128<ulong>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<long> AdvSimd_Arm64_CompareEqual_Vector128_Int64_Zero_Swapped(Vector128<long> right) { return AdvSimd.Arm64.CompareEqual(Vector128<long>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<float> AdvSimd_Arm64_CompareEqualScalar_Vector64_Single_Zero_Swapped(Vector64<float> right) { return AdvSimd.Arm64.CompareEqualScalar(Vector64<float>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<double> AdvSimd_Arm64_CompareEqualScalar_Vector64_Double_Zero_Swapped(Vector64<double> right) { return AdvSimd.Arm64.CompareEqualScalar(Vector64<double>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<ulong> AdvSimd_Arm64_CompareEqualScalar_Vector64_UInt64_Zero_Swapped(Vector64<ulong> right) { return AdvSimd.Arm64.CompareEqualScalar(Vector64<ulong>.Zero, right); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<long> AdvSimd_Arm64_CompareEqualScalar_Vector64_Int64_Zero_Swapped(Vector64<long> right) { return AdvSimd.Arm64.CompareEqualScalar(Vector64<long>.Zero, right); } // CompareGreaterThan [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<byte> AdvSimd_CompareGreaterThan_Vector64_Byte_Zero(Vector64<byte> left) { return AdvSimd.CompareGreaterThan(left, Vector64<byte>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<float> AdvSimd_CompareGreaterThan_Vector64_Single_Zero(Vector64<float> left) { return AdvSimd.CompareGreaterThan(left, Vector64<float>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<byte> AdvSimd_CompareGreaterThan_Vector128_Byte_Zero(Vector128<byte> left) { return AdvSimd.CompareGreaterThan(left, Vector128<byte>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<float> AdvSimd_CompareGreaterThan_Vector128_Single_Zero(Vector128<float> left) { return AdvSimd.CompareGreaterThan(left, Vector128<float>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<double> AdvSimd_Arm64_CompareGreaterThan_Vector128_Double_Zero(Vector128<double> left) { return AdvSimd.Arm64.CompareGreaterThan(left, Vector128<double>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<long> AdvSimd_Arm64_CompareGreaterThan_Vector128_Int64_Zero(Vector128<long> left) { return AdvSimd.Arm64.CompareGreaterThan(left, Vector128<long>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<double> AdvSimd_Arm64_CompareGreaterThanScalar_Vector64_Double_Zero(Vector64<double> left) { return AdvSimd.Arm64.CompareGreaterThanScalar(left, Vector64<double>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<long> AdvSimd_Arm64_CompareGreaterThanScalar_Vector64_Int64_Zero(Vector64<long> left) { return AdvSimd.Arm64.CompareGreaterThanScalar(left, Vector64<long>.Zero); } // CompareGreaterThanOrEqual [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<byte> AdvSimd_CompareGreaterThanOrEqual_Vector64_Byte_Zero(Vector64<byte> left) { return AdvSimd.CompareGreaterThanOrEqual(left, Vector64<byte>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<float> AdvSimd_CompareGreaterThanOrEqual_Vector64_Single_Zero(Vector64<float> left) { return AdvSimd.CompareGreaterThanOrEqual(left, Vector64<float>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<byte> AdvSimd_CompareGreaterThanOrEqual_Vector128_Byte_Zero(Vector128<byte> left) { return AdvSimd.CompareGreaterThanOrEqual(left, Vector128<byte>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<float> AdvSimd_CompareGreaterThanOrEqual_Vector128_Single_Zero(Vector128<float> left) { return AdvSimd.CompareGreaterThanOrEqual(left, Vector128<float>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<double> AdvSimd_Arm64_CompareGreaterThanOrEqual_Vector128_Double_Zero(Vector128<double> left) { return AdvSimd.Arm64.CompareGreaterThanOrEqual(left, Vector128<double>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector128<long> AdvSimd_Arm64_CompareGreaterThanOrEqual_Vector128_Int64_Zero(Vector128<long> left) { return AdvSimd.Arm64.CompareGreaterThanOrEqual(left, Vector128<long>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<double> AdvSimd_Arm64_CompareGreaterThanOrEqualScalar_Vector64_Double_Zero(Vector64<double> left) { return AdvSimd.Arm64.CompareGreaterThanOrEqualScalar(left, Vector64<double>.Zero); } [MethodImpl(MethodImplOptions.NoInlining)] static Vector64<long> AdvSimd_Arm64_CompareGreaterThanOrEqualScalar_Vector64_Int64_Zero(Vector64<long> left) { return AdvSimd.Arm64.CompareGreaterThanOrEqualScalar(left, Vector64<long>.Zero); } // Validation unsafe static bool ValidateResult_Vector64<T>(Vector64<T> result, T expectedElementValue) where T : unmanaged { var succeeded = true; for (var i = 0; i < (8 / sizeof(T)); i++) { if (!result.GetElement(i).Equals(expectedElementValue)) { succeeded = false; } } return succeeded; } unsafe static bool ValidateResult_Vector64<T>(Vector64<T> result, Vector64<T> expectedElementValue) where T : unmanaged { var succeeded = true; for (var i = 0; i < (8 / sizeof(T)); i++) { if (!result.GetElement(i).Equals(expectedElementValue.GetElement(i))) { succeeded = false; } } return succeeded; } unsafe static bool ValidateResult_Vector128<T>(Vector128<T> result, T expectedElementValue) where T : unmanaged { var succeeded = true; for (var i = 0; i < (16 / sizeof(T)); i++) { if (!result.GetElement(i).Equals(expectedElementValue)) { succeeded = false; } } return succeeded; } unsafe static bool ValidateResult_Vector128<T>(Vector128<T> result, Vector128<T> expectedElementValue) where T : unmanaged { var succeeded = true; for (var i = 0; i < (16 / sizeof(T)); i++) { if (!result.GetElement(i).Equals(expectedElementValue.GetElement(i))) { succeeded = false; } } return succeeded; } static int Tests_AdvSimd() { var result = 100; // Begin CompareEqual Tests // Vector64 if (!ValidateResult_Vector64<byte>(AdvSimd_CompareEqual_Vector64_Byte_Zero(Vector64<byte>.Zero), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector64<sbyte>(AdvSimd_CompareEqual_Vector64_SByte_Zero(Vector64<sbyte>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<ushort>(AdvSimd_CompareEqual_Vector64_UInt16_Zero(Vector64<ushort>.Zero), UInt16.MaxValue)) result = -1; if (!ValidateResult_Vector64<short>(AdvSimd_CompareEqual_Vector64_Int16_Zero(Vector64<short>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<uint>(AdvSimd_CompareEqual_Vector64_UInt32_Zero(Vector64<uint>.Zero), UInt32.MaxValue)) result = -1; if (!ValidateResult_Vector64<int>(AdvSimd_CompareEqual_Vector64_Int32_Zero(Vector64<int>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<float>(AdvSimd_CompareEqual_Vector64_Single_Zero(Vector64<float>.Zero), Single.NaN)) result = -1; // Vector64.Create if (!ValidateResult_Vector64<int>(AdvSimd_CompareEqual_Vector64_Int32_CreateZero(Vector64<int>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<float>(AdvSimd_CompareEqual_Vector64_Single_CreateZero(Vector64<float>.Zero), Single.NaN)) result = -1; if (!ValidateResult_Vector64<int>(AdvSimd_CompareEqual_Vector64_Int32_CreateZeroZero(Vector64<int>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<float>(AdvSimd_CompareEqual_Vector64_Single_CreateZeroZero(Vector64<float>.Zero), Single.NaN)) result = -1; // Vector128 if (!ValidateResult_Vector128<byte>(AdvSimd_CompareEqual_Vector128_Byte_Zero(Vector128<byte>.Zero), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector128<sbyte>(AdvSimd_CompareEqual_Vector128_SByte_Zero(Vector128<sbyte>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<ushort>(AdvSimd_CompareEqual_Vector128_UInt16_Zero(Vector128<ushort>.Zero), UInt16.MaxValue)) result = -1; if (!ValidateResult_Vector128<short>(AdvSimd_CompareEqual_Vector128_Int16_Zero(Vector128<short>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<uint>(AdvSimd_CompareEqual_Vector128_UInt32_Zero(Vector128<uint>.Zero), UInt32.MaxValue)) result = -1; if (!ValidateResult_Vector128<int>(AdvSimd_CompareEqual_Vector128_Int32_Zero(Vector128<int>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareEqual_Vector128_Single_Zero(Vector128<float>.Zero), Single.NaN)) result = -1; // Vector128.Create if (!ValidateResult_Vector128<int>(AdvSimd_CompareEqual_Vector128_Int32_CreateZero(Vector128<int>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareEqual_Vector128_Single_CreateZero(Vector128<float>.Zero), Single.NaN)) result = -1; if (!ValidateResult_Vector128<int>(AdvSimd_CompareEqual_Vector128_Int32_CreateZeroZeroZeroZero(Vector128<int>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareEqual_Vector128_Single_CreateZeroZeroZeroZero(Vector128<float>.Zero), Single.NaN)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareEqual_Vector128_Single_CreateZeroZeroZeroZero_AsVariable(Vector128<float>.Zero), Single.NaN)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareEqual_Vector128_Single_CreateZeroZeroZeroZero_AsVariableLoop(Vector128<float>.Zero), Single.NaN)) result = -1; // End CompareEqual Tests // Begin CompareGreaterThan Tests if (!ValidateResult_Vector64<byte>(AdvSimd_CompareGreaterThan_Vector64_Byte_Zero(Vector64.Create((byte)1)), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector64<float>(AdvSimd_CompareGreaterThan_Vector64_Single_Zero(Vector64.Create(1.0f)), Single.NaN)) result = -1; if (!ValidateResult_Vector128<byte>(AdvSimd_CompareGreaterThan_Vector128_Byte_Zero(Vector128.Create((byte)1)), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareGreaterThan_Vector128_Single_Zero(Vector128.Create(1.0f)), Single.NaN)) result = -1; if (!ValidateResult_Vector128<double>(AdvSimd_Arm64_CompareGreaterThan_Vector128_Double_Zero(Vector128.Create(1.0)), Double.NaN)) result = -1; if (!ValidateResult_Vector128<long>(AdvSimd_Arm64_CompareGreaterThan_Vector128_Int64_Zero(Vector128.Create(1L)), -1)) result = -1; if (!ValidateResult_Vector64<double>(AdvSimd_Arm64_CompareGreaterThanScalar_Vector64_Double_Zero(Vector64.Create(1.0)), Double.NaN)) result = -1; if (!ValidateResult_Vector64<long>(AdvSimd_Arm64_CompareGreaterThanScalar_Vector64_Int64_Zero(Vector64.Create(1L)), -1)) result = -1; if (ValidateResult_Vector64<byte>(AdvSimd_CompareGreaterThan_Vector64_Byte_Zero(Vector64<byte>.Zero), Byte.MaxValue)) result = -1; if (ValidateResult_Vector64<float>(AdvSimd_CompareGreaterThan_Vector64_Single_Zero(Vector64<float>.Zero), Single.NaN)) result = -1; if (ValidateResult_Vector128<byte>(AdvSimd_CompareGreaterThan_Vector128_Byte_Zero(Vector128<byte>.Zero), Byte.MaxValue)) result = -1; if (ValidateResult_Vector128<float>(AdvSimd_CompareGreaterThan_Vector128_Single_Zero(Vector128<float>.Zero), Single.NaN)) result = -1; if (ValidateResult_Vector128<double>(AdvSimd_Arm64_CompareGreaterThan_Vector128_Double_Zero(Vector128<double>.Zero), Double.NaN)) result = -1; if (ValidateResult_Vector128<long>(AdvSimd_Arm64_CompareGreaterThan_Vector128_Int64_Zero(Vector128<long>.Zero), -1)) result = -1; if (ValidateResult_Vector64<double>(AdvSimd_Arm64_CompareGreaterThanScalar_Vector64_Double_Zero(Vector64<double>.Zero), Double.NaN)) result = -1; if (ValidateResult_Vector64<long>(AdvSimd_Arm64_CompareGreaterThanScalar_Vector64_Int64_Zero(Vector64<long>.Zero), -1)) result = -1; // End CompareGreaterThan Tests // Begin CompareGreaterThanOrEqual Tests if (!ValidateResult_Vector64<byte>(AdvSimd_CompareGreaterThanOrEqual_Vector64_Byte_Zero(Vector64.Create((byte)1)), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector64<float>(AdvSimd_CompareGreaterThanOrEqual_Vector64_Single_Zero(Vector64.Create(1.0f)), Single.NaN)) result = -1; if (!ValidateResult_Vector128<byte>(AdvSimd_CompareGreaterThanOrEqual_Vector128_Byte_Zero(Vector128.Create((byte)1)), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareGreaterThanOrEqual_Vector128_Single_Zero(Vector128.Create(1.0f)), Single.NaN)) result = -1; if (!ValidateResult_Vector128<double>(AdvSimd_Arm64_CompareGreaterThanOrEqual_Vector128_Double_Zero(Vector128.Create(1.0)), Double.NaN)) result = -1; if (!ValidateResult_Vector128<long>(AdvSimd_Arm64_CompareGreaterThanOrEqual_Vector128_Int64_Zero(Vector128.Create(1L)), -1)) result = -1; if (!ValidateResult_Vector64<double>(AdvSimd_Arm64_CompareGreaterThanOrEqualScalar_Vector64_Double_Zero(Vector64.Create(1.0)), Double.NaN)) result = -1; if (!ValidateResult_Vector64<long>(AdvSimd_Arm64_CompareGreaterThanOrEqualScalar_Vector64_Int64_Zero(Vector64.Create(1L)), -1)) result = -1; if (!ValidateResult_Vector64<byte>(AdvSimd_CompareGreaterThanOrEqual_Vector64_Byte_Zero(Vector64<byte>.Zero), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector64<float>(AdvSimd_CompareGreaterThanOrEqual_Vector64_Single_Zero(Vector64<float>.Zero), Single.NaN)) result = -1; if (!ValidateResult_Vector128<byte>(AdvSimd_CompareGreaterThanOrEqual_Vector128_Byte_Zero(Vector128<byte>.Zero), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareGreaterThanOrEqual_Vector128_Single_Zero(Vector128<float>.Zero), Single.NaN)) result = -1; if (!ValidateResult_Vector128<double>(AdvSimd_Arm64_CompareGreaterThanOrEqual_Vector128_Double_Zero(Vector128<double>.Zero), Double.NaN)) result = -1; if (!ValidateResult_Vector128<long>(AdvSimd_Arm64_CompareGreaterThanOrEqual_Vector128_Int64_Zero(Vector128<long>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<double>(AdvSimd_Arm64_CompareGreaterThanOrEqualScalar_Vector64_Double_Zero(Vector64<double>.Zero), Double.NaN)) result = -1; if (!ValidateResult_Vector64<long>(AdvSimd_Arm64_CompareGreaterThanOrEqualScalar_Vector64_Int64_Zero(Vector64<long>.Zero), -1)) result = -1; // End CompareGreaterThanOrEqual Tests return result; } static int Tests_AdvSimd_Swapped() { var result = 100; // Begin CompareEqual Tests // Vector64 if (!ValidateResult_Vector64<byte>(AdvSimd_CompareEqual_Vector64_Byte_Zero_Swapped(Vector64<byte>.Zero), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector64<sbyte>(AdvSimd_CompareEqual_Vector64_SByte_Zero_Swapped(Vector64<sbyte>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<ushort>(AdvSimd_CompareEqual_Vector64_UInt16_Zero_Swapped(Vector64<ushort>.Zero), UInt16.MaxValue)) result = -1; if (!ValidateResult_Vector64<short>(AdvSimd_CompareEqual_Vector64_Int16_Zero_Swapped(Vector64<short>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<uint>(AdvSimd_CompareEqual_Vector64_UInt32_Zero_Swapped(Vector64<uint>.Zero), UInt32.MaxValue)) result = -1; if (!ValidateResult_Vector64<int>(AdvSimd_CompareEqual_Vector64_Int32_Zero_Swapped(Vector64<int>.Zero), -1)) result = -1; if (!ValidateResult_Vector64<float>(AdvSimd_CompareEqual_Vector64_Single_Zero_Swapped(Vector64<float>.Zero), Single.NaN)) result = -1; // Vector128 if (!ValidateResult_Vector128<byte>(AdvSimd_CompareEqual_Vector128_Byte_Zero_Swapped(Vector128<byte>.Zero), Byte.MaxValue)) result = -1; if (!ValidateResult_Vector128<sbyte>(AdvSimd_CompareEqual_Vector128_SByte_Zero_Swapped(Vector128<sbyte>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<ushort>(AdvSimd_CompareEqual_Vector128_UInt16_Zero_Swapped(Vector128<ushort>.Zero), UInt16.MaxValue)) result = -1; if (!ValidateResult_Vector128<short>(AdvSimd_CompareEqual_Vector128_Int16_Zero_Swapped(Vector128<short>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<uint>(AdvSimd_CompareEqual_Vector128_UInt32_Zero_Swapped(Vector128<uint>.Zero), UInt32.MaxValue)) result = -1; if (!ValidateResult_Vector128<int>(AdvSimd_CompareEqual_Vector128_Int32_Zero_Swapped(Vector128<int>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<float>(AdvSimd_CompareEqual_Vector128_Single_Zero_Swapped(Vector128<float>.Zero), Single.NaN)) result = -1; // End CompareEqual Tests return result; } static int Tests_AdvSimd_Arm64() { var result = 100; // Begin CompareEqual Tests // Vector128 if (!ValidateResult_Vector128<double>(AdvSimd_Arm64_CompareEqual_Vector128_Double_Zero(Vector128<double>.Zero), Double.NaN)) result = -1; if (!ValidateResult_Vector128<ulong>(AdvSimd_Arm64_CompareEqual_Vector128_UInt64_Zero(Vector128<ulong>.Zero), UInt64.MaxValue)) result = -1; if (!ValidateResult_Vector128<long>(AdvSimd_Arm64_CompareEqual_Vector128_Int64_Zero(Vector128<long>.Zero), -1)) result = -1; if (!ValidateResult_Vector128<long>(AdvSimd_Arm64_CompareEqual_Vector128_Long_AsVariableLoop(Vector128<long>.Zero), -1)) result = -1; // Vector64 if (!ValidateResult_Vector64<float>(AdvSimd_Arm64_CompareEqualScalar_Vector64_Single_Zero(Vector64<float>.Zero), Vector64.CreateScalar(Single.NaN))) result = -1; if (!ValidateResult_Vector64<double>(AdvSimd_Arm64_CompareEqualScalar_Vector64_Double_Zero(Vector64<double>.Zero), Vector64.CreateScalar(Double.NaN))) result = -1; if (!ValidateResult_Vector64<ulong>(AdvSimd_Arm64_CompareEqualScalar_Vector64_UInt64_Zero(Vector64<ulong>.Zero), Vector64.CreateScalar(UInt64.MaxValue))) result = -1; if (!ValidateResult_Vector64<long>(AdvSimd_Arm64_CompareEqualScalar_Vector64_Int64_Zero(Vector64<long>.Zero), Vector64.CreateScalar(-1L))) result = -1; // End CompareEqual Tests return result; } static int Tests_AdvSimd_Arm64_Swapped() { var result = 100; // Begin CompareEqual Tests // Vector128 if (!ValidateResult_Vector128<double>(AdvSimd_Arm64_CompareEqual_Vector128_Double_Zero_Swapped(Vector128<double>.Zero), Double.NaN)) result = -1; if (!ValidateResult_Vector128<ulong>(AdvSimd_Arm64_CompareEqual_Vector128_UInt64_Zero_Swapped(Vector128<ulong>.Zero), UInt64.MaxValue)) result = -1; if (!ValidateResult_Vector128<long>(AdvSimd_Arm64_CompareEqual_Vector128_Int64_Zero_Swapped(Vector128<long>.Zero), -1)) result = -1; // Vector64 if (!ValidateResult_Vector64<float>(AdvSimd_Arm64_CompareEqualScalar_Vector64_Single_Zero_Swapped(Vector64<float>.Zero), Vector64.CreateScalar(Single.NaN))) result = -1; if (!ValidateResult_Vector64<double>(AdvSimd_Arm64_CompareEqualScalar_Vector64_Double_Zero_Swapped(Vector64<double>.Zero), Vector64.CreateScalar(Double.NaN))) result = -1; if (!ValidateResult_Vector64<ulong>(AdvSimd_Arm64_CompareEqualScalar_Vector64_UInt64_Zero_Swapped(Vector64<ulong>.Zero), Vector64.CreateScalar(UInt64.MaxValue))) result = -1; if (!ValidateResult_Vector64<long>(AdvSimd_Arm64_CompareEqualScalar_Vector64_Int64_Zero_Swapped(Vector64<long>.Zero), Vector64.CreateScalar(-1L))) result = -1; // End CompareEqual Tests return result; } static int Main(string[] args) { var result = 100; if (AdvSimd.IsSupported) { Console.WriteLine("Testing AdvSimd"); if (result != -1) { result = Tests_AdvSimd(); } if (result != -1) { result = Tests_AdvSimd_Swapped(); } if (result == -1) { Console.WriteLine("AdvSimd Tests Failed"); } else { Console.WriteLine("AdvSimd Tests Passed"); } } else { Console.WriteLine("Skipped AdvSimd Tests"); } if (AdvSimd.Arm64.IsSupported) { Console.WriteLine("Testing AdvSimd_Arm64"); if (result != -1) { result = Tests_AdvSimd_Arm64(); } if (result != -1) { result = Tests_AdvSimd_Arm64_Swapped(); } if (result == -1) { Console.WriteLine("AdvSimd_Arm64 Tests Failed"); } else { Console.WriteLine("AdvSimd_Arm64 Tests Passed"); } } else { Console.WriteLine("Skipped AdvSimd_Arm64 Tests"); } return result; } }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/tests/JIT/Methodical/VT/etc/nested_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="nested.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="nested.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M09/b15307/b15307.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>PdbOnly</DebugType> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>PdbOnly</DebugType> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormat.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Text; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System { /* Customized format patterns: P.S. Format in the table below is the internal number format used to display the pattern. Patterns Format Description Example ========= ========== ===================================== ======== "h" "0" hour (12-hour clock)w/o leading zero 3 "hh" "00" hour (12-hour clock)with leading zero 03 "hh*" "00" hour (12-hour clock)with leading zero 03 "H" "0" hour (24-hour clock)w/o leading zero 8 "HH" "00" hour (24-hour clock)with leading zero 08 "HH*" "00" hour (24-hour clock) 08 "m" "0" minute w/o leading zero "mm" "00" minute with leading zero "mm*" "00" minute with leading zero "s" "0" second w/o leading zero "ss" "00" second with leading zero "ss*" "00" second with leading zero "f" "0" second fraction (1 digit) "ff" "00" second fraction (2 digit) "fff" "000" second fraction (3 digit) "ffff" "0000" second fraction (4 digit) "fffff" "00000" second fraction (5 digit) "ffffff" "000000" second fraction (6 digit) "fffffff" "0000000" second fraction (7 digit) "F" "0" second fraction (up to 1 digit) "FF" "00" second fraction (up to 2 digit) "FFF" "000" second fraction (up to 3 digit) "FFFF" "0000" second fraction (up to 4 digit) "FFFFF" "00000" second fraction (up to 5 digit) "FFFFFF" "000000" second fraction (up to 6 digit) "FFFFFFF" "0000000" second fraction (up to 7 digit) "t" first character of AM/PM designator A "tt" AM/PM designator AM "tt*" AM/PM designator PM "d" "0" day w/o leading zero 1 "dd" "00" day with leading zero 01 "ddd" short weekday name (abbreviation) Mon "dddd" full weekday name Monday "dddd*" full weekday name Monday "M" "0" month w/o leading zero 2 "MM" "00" month with leading zero 02 "MMM" short month name (abbreviation) Feb "MMMM" full month name February "MMMM*" full month name February "y" "0" two digit year (year % 100) w/o leading zero 0 "yy" "00" two digit year (year % 100) with leading zero 00 "yyy" "D3" year 2000 "yyyy" "D4" year 2000 "yyyyy" "D5" year 2000 ... "z" "+0;-0" timezone offset w/o leading zero -8 "zz" "+00;-00" timezone offset with leading zero -08 "zzz" "+00;-00" for hour offset, "00" for minute offset full timezone offset -07:30 "zzz*" "+00;-00" for hour offset, "00" for minute offset full timezone offset -08:00 "K" -Local "zzz", e.g. -08:00 -Utc "'Z'", representing UTC -Unspecified "" -DateTimeOffset "zzzzz" e.g -07:30:15 "g*" the current era name A.D. ":" time separator : -- DEPRECATED - Insert separator directly into pattern (eg: "H.mm.ss") "/" date separator /-- DEPRECATED - Insert separator directly into pattern (eg: "M-dd-yyyy") "'" quoted string 'ABC' will insert ABC into the formatted string. '"' quoted string "ABC" will insert ABC into the formatted string. "%" used to quote a single pattern characters E.g.The format character "%y" is to print two digit year. "\" escaped character E.g. '\d' insert the character 'd' into the format string. other characters insert the character into the format string. Pre-defined format characters: (U) to indicate Universal time is used. (G) to indicate Gregorian calendar is used. Format Description Real format Example ========= ================================= ====================== ======================= "d" short date culture-specific 10/31/1999 "D" long data culture-specific Sunday, October 31, 1999 "f" full date (long date + short time) culture-specific Sunday, October 31, 1999 2:00 AM "F" full date (long date + long time) culture-specific Sunday, October 31, 1999 2:00:00 AM "g" general date (short date + short time) culture-specific 10/31/1999 2:00 AM "G" general date (short date + long time) culture-specific 10/31/1999 2:00:00 AM "m"/"M" Month/Day date culture-specific October 31 (G) "o"/"O" Round Trip XML "yyyy-MM-ddTHH:mm:ss.fffffffK" 1999-10-31 02:00:00.0000000Z (G) "r"/"R" RFC 1123 date, "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'" Sun, 31 Oct 1999 10:00:00 GMT (G) "s" Sortable format, based on ISO 8601. "yyyy-MM-dd'T'HH:mm:ss" 1999-10-31T02:00:00 ('T' for local time) "t" short time culture-specific 2:00 AM "T" long time culture-specific 2:00:00 AM (G) "u" Universal time with sortable format, "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" 1999-10-31 10:00:00Z based on ISO 8601. (U) "U" Universal time with full culture-specific Sunday, October 31, 1999 10:00:00 AM (long date + long time) format "y"/"Y" Year/Month day culture-specific October, 1999 */ // This class contains only static members and does not require the serializable attribute. internal static class DateTimeFormat { internal const int MaxSecondsFractionDigits = 7; internal const long NullOffset = long.MinValue; internal static char[] allStandardFormats = { 'd', 'D', 'f', 'F', 'g', 'G', 'm', 'M', 'o', 'O', 'r', 'R', 's', 't', 'T', 'u', 'U', 'y', 'Y', }; internal const string RoundtripFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"; internal const string RoundtripDateTimeUnfixed = "yyyy'-'MM'-'ddTHH':'mm':'ss zzz"; private const int DEFAULT_ALL_DATETIMES_SIZE = 132; internal static readonly DateTimeFormatInfo InvariantFormatInfo = CultureInfo.InvariantCulture.DateTimeFormat; internal static readonly string[] InvariantAbbreviatedMonthNames = InvariantFormatInfo.AbbreviatedMonthNames; internal static readonly string[] InvariantAbbreviatedDayNames = InvariantFormatInfo.AbbreviatedDayNames; internal const string Gmt = "GMT"; internal static string[] fixedNumberFormats = new string[] { "0", "00", "000", "0000", "00000", "000000", "0000000", }; //////////////////////////////////////////////////////////////////////////// // // Format the positive integer value to a string and prefix with assigned // length of leading zero. // // Parameters: // value: The value to format // len: The maximum length for leading zero. // If the digits of the value is greater than len, no leading zero is added. // // Notes: // The function can format to int.MaxValue. // //////////////////////////////////////////////////////////////////////////// internal static void FormatDigits(StringBuilder outputBuffer, int value, int len) { Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0"); FormatDigits(outputBuffer, value, len, false); } internal static unsafe void FormatDigits(StringBuilder outputBuffer, int value, int len, bool overrideLengthLimit) { Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0"); // Limit the use of this function to be two-digits, so that we have the same behavior // as RTM bits. if (!overrideLengthLimit && len > 2) { len = 2; } char* buffer = stackalloc char[16]; char* p = buffer + 16; int n = value; do { *--p = (char)(n % 10 + '0'); n /= 10; } while ((n != 0) && (p > buffer)); int digits = (int)(buffer + 16 - p); // If the repeat count is greater than 0, we're trying // to emulate the "00" format, so we have to prepend // a zero if the string only has one character. while ((digits < len) && (p > buffer)) { *--p = '0'; digits++; } outputBuffer.Append(p, digits); } private static void HebrewFormatDigits(StringBuilder outputBuffer, int digits) { HebrewNumber.Append(outputBuffer, digits); } internal static int ParseRepeatPattern(ReadOnlySpan<char> format, int pos, char patternChar) { int len = format.Length; int index = pos + 1; while ((index < len) && (format[index] == patternChar)) { index++; } return index - pos; } private static string FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi) { Debug.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6"); if (repeat == 3) { return dtfi.GetAbbreviatedDayName((DayOfWeek)dayOfWeek); } // Call dtfi.GetDayName() here, instead of accessing DayNames property, because we don't // want a clone of DayNames, which will hurt perf. return dtfi.GetDayName((DayOfWeek)dayOfWeek); } private static string FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi) { Debug.Assert(month >= 1 && month <= 12, "month >=1 && month <= 12"); if (repeatCount == 3) { return dtfi.GetAbbreviatedMonthName(month); } // Call GetMonthName() here, instead of accessing MonthNames property, because we don't // want a clone of MonthNames, which will hurt perf. return dtfi.GetMonthName(month); } // // FormatHebrewMonthName // // Action: Return the Hebrew month name for the specified DateTime. // Returns: The month name string for the specified DateTime. // Arguments: // time the time to format // month The month is the value of HebrewCalendar.GetMonth(time). // repeat Return abbreviated month name if repeat=3, or full month name if repeat=4 // dtfi The DateTimeFormatInfo which uses the Hebrew calendars as its calendar. // Exceptions: None. // /* Note: If DTFI is using Hebrew calendar, GetMonthName()/GetAbbreviatedMonthName() will return month names like this: 1 Hebrew 1st Month 2 Hebrew 2nd Month .. ... 6 Hebrew 6th Month 7 Hebrew 6th Month II (used only in a leap year) 8 Hebrew 7th Month 9 Hebrew 8th Month 10 Hebrew 9th Month 11 Hebrew 10th Month 12 Hebrew 11th Month 13 Hebrew 12th Month Therefore, if we are in a regular year, we have to increment the month name if month is greater or equal to 7. */ private static string FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi) { Debug.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4"); if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time))) { // This month is in a leap year return dtfi.InternalGetMonthName(month, MonthNameStyles.LeapYear, repeatCount == 3); } // This is in a regular year. if (month >= 7) { month++; } if (repeatCount == 3) { return dtfi.GetAbbreviatedMonthName(month); } return dtfi.GetMonthName(month); } // // The pos should point to a quote character. This method will // append to the result StringBuilder the string enclosed by the quote character. // internal static int ParseQuoteString(ReadOnlySpan<char> format, int pos, StringBuilder result) { // // NOTE : pos will be the index of the quote character in the 'format' string. // int formatLen = format.Length; int beginPos = pos; char quoteChar = format[pos++]; // Get the character used to quote the following string. bool foundQuote = false; while (pos < formatLen) { char ch = format[pos++]; if (ch == quoteChar) { foundQuote = true; break; } else if (ch == '\\') { // The following are used to support escaped character. // Escaped character is also supported in the quoted string. // Therefore, someone can use a format like "'minute:' mm\"" to display: // minute: 45" // because the second double quote is escaped. if (pos < formatLen) { result.Append(format[pos++]); } else { // // This means that '\' is at the end of the formatting string. // throw new FormatException(SR.Format_InvalidString); } } else { result.Append(ch); } } if (!foundQuote) { // Here we can't find the matching quote. throw new FormatException(SR.Format(SR.Format_BadQuote, quoteChar)); } // // Return the character count including the begin/end quote characters and enclosed string. // return pos - beginPos; } // // Get the next character at the index of 'pos' in the 'format' string. // Return value of -1 means 'pos' is already at the end of the 'format' string. // Otherwise, return value is the int value of the next character. // internal static int ParseNextChar(ReadOnlySpan<char> format, int pos) { if (pos >= format.Length - 1) { return -1; } return (int)format[pos + 1]; } // // IsUseGenitiveForm // // Actions: Check the format to see if we should use genitive month in the formatting. // Starting at the position (index) in the (format) string, look back and look ahead to // see if there is "d" or "dd". In the case like "d MMMM" or "MMMM dd", we can use // genitive form. Genitive form is not used if there is more than two "d". // Arguments: // format The format string to be scanned. // index Where we should start the scanning. This is generally where "M" starts. // tokenLen The len of the current pattern character. This indicates how many "M" that we have. // patternToMatch The pattern that we want to search. This generally uses "d" // private static bool IsUseGenitiveForm(ReadOnlySpan<char> format, int index, int tokenLen, char patternToMatch) { int i; int repeat = 0; // // Look back to see if we can find "d" or "ddd" // // Find first "d". for (i = index - 1; i >= 0 && format[i] != patternToMatch; i--) { /*Do nothing here */ } if (i >= 0) { // Find a "d", so look back to see how many "d" that we can find. while (--i >= 0 && format[i] == patternToMatch) { repeat++; } // // repeat == 0 means that we have one (patternToMatch) // repeat == 1 means that we have two (patternToMatch) // if (repeat <= 1) { return true; } // Note that we can't just stop here. We may find "ddd" while looking back, and we have to look // ahead to see if there is "d" or "dd". } // // If we can't find "d" or "dd" by looking back, try look ahead. // // Find first "d" for (i = index + tokenLen; i < format.Length && format[i] != patternToMatch; i++) { /* Do nothing here */ } if (i < format.Length) { repeat = 0; // Find a "d", so contine the walk to see how may "d" that we can find. while (++i < format.Length && format[i] == patternToMatch) { repeat++; } // // repeat == 0 means that we have one (patternToMatch) // repeat == 1 means that we have two (patternToMatch) // if (repeat <= 1) { return true; } } return false; } // // FormatCustomized // // Actions: Format the DateTime instance using the specified format. // private static StringBuilder FormatCustomized( DateTime dateTime, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi, TimeSpan offset, StringBuilder? result) { Calendar cal = dtfi.Calendar; bool resultBuilderIsPooled = false; if (result == null) { resultBuilderIsPooled = true; result = StringBuilderCache.Acquire(); } // This is a flag to indicate if we are formatting the dates using Hebrew calendar. bool isHebrewCalendar = (cal.ID == CalendarId.HEBREW); bool isJapaneseCalendar = (cal.ID == CalendarId.JAPAN); // This is a flag to indicate if we are formatting hour/minute/second only. bool bTimeOnly = true; int i = 0; int tokenLen, hour12; while (i < format.Length) { char ch = format[i]; int nextChar; switch (ch) { case 'g': tokenLen = ParseRepeatPattern(format, i, ch); result.Append(dtfi.GetEraName(cal.GetEra(dateTime))); break; case 'h': tokenLen = ParseRepeatPattern(format, i, ch); hour12 = dateTime.Hour % 12; if (hour12 == 0) { hour12 = 12; } FormatDigits(result, hour12, tokenLen); break; case 'H': tokenLen = ParseRepeatPattern(format, i, ch); FormatDigits(result, dateTime.Hour, tokenLen); break; case 'm': tokenLen = ParseRepeatPattern(format, i, ch); FormatDigits(result, dateTime.Minute, tokenLen); break; case 's': tokenLen = ParseRepeatPattern(format, i, ch); FormatDigits(result, dateTime.Second, tokenLen); break; case 'f': case 'F': tokenLen = ParseRepeatPattern(format, i, ch); if (tokenLen <= MaxSecondsFractionDigits) { long fraction = (dateTime.Ticks % Calendar.TicksPerSecond); fraction /= (long)Math.Pow(10, 7 - tokenLen); if (ch == 'f') { result.AppendSpanFormattable((int)fraction, fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture); } else { int effectiveDigits = tokenLen; while (effectiveDigits > 0) { if (fraction % 10 == 0) { fraction /= 10; effectiveDigits--; } else { break; } } if (effectiveDigits > 0) { result.AppendSpanFormattable((int)fraction, fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture); } else { // No fraction to emit, so see if we should remove decimal also. if (result.Length > 0 && result[result.Length - 1] == '.') { result.Remove(result.Length - 1, 1); } } } } else { if (resultBuilderIsPooled) { StringBuilderCache.Release(result); } throw new FormatException(SR.Format_InvalidString); } break; case 't': tokenLen = ParseRepeatPattern(format, i, ch); if (tokenLen == 1) { if (dateTime.Hour < 12) { if (dtfi.AMDesignator.Length >= 1) { result.Append(dtfi.AMDesignator[0]); } } else { if (dtfi.PMDesignator.Length >= 1) { result.Append(dtfi.PMDesignator[0]); } } } else { result.Append(dateTime.Hour < 12 ? dtfi.AMDesignator : dtfi.PMDesignator); } break; case 'd': // // tokenLen == 1 : Day of month as digits with no leading zero. // tokenLen == 2 : Day of month as digits with leading zero for single-digit months. // tokenLen == 3 : Day of week as a three-letter abbreviation. // tokenLen >= 4 : Day of week as its full name. // tokenLen = ParseRepeatPattern(format, i, ch); if (tokenLen <= 2) { int day = cal.GetDayOfMonth(dateTime); if (isHebrewCalendar) { // For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values. HebrewFormatDigits(result, day); } else { FormatDigits(result, day, tokenLen); } } else { int dayOfWeek = (int)cal.GetDayOfWeek(dateTime); result.Append(FormatDayOfWeek(dayOfWeek, tokenLen, dtfi)); } bTimeOnly = false; break; case 'M': // // tokenLen == 1 : Month as digits with no leading zero. // tokenLen == 2 : Month as digits with leading zero for single-digit months. // tokenLen == 3 : Month as a three-letter abbreviation. // tokenLen >= 4 : Month as its full name. // tokenLen = ParseRepeatPattern(format, i, ch); int month = cal.GetMonth(dateTime); if (tokenLen <= 2) { if (isHebrewCalendar) { // For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values. HebrewFormatDigits(result, month); } else { FormatDigits(result, month, tokenLen); } } else { if (isHebrewCalendar) { result.Append(FormatHebrewMonthName(dateTime, month, tokenLen, dtfi)); } else { if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0) { result.Append( dtfi.InternalGetMonthName( month, IsUseGenitiveForm(format, i, tokenLen, 'd') ? MonthNameStyles.Genitive : MonthNameStyles.Regular, tokenLen == 3)); } else { result.Append(FormatMonth(month, tokenLen, dtfi)); } } } bTimeOnly = false; break; case 'y': // Notes about OS behavior: // y: Always print (year % 100). No leading zero. // yy: Always print (year % 100) with leading zero. // yyy/yyyy/yyyyy/... : Print year value. No leading zero. int year = cal.GetYear(dateTime); tokenLen = ParseRepeatPattern(format, i, ch); if (isJapaneseCalendar && !LocalAppContextSwitches.FormatJapaneseFirstYearAsANumber && year == 1 && ((i + tokenLen < format.Length && format[i + tokenLen] == DateTimeFormatInfoScanner.CJKYearSuff) || (i + tokenLen < format.Length - 1 && format[i + tokenLen] == '\'' && format[i + tokenLen + 1] == DateTimeFormatInfoScanner.CJKYearSuff))) { // We are formatting a Japanese date with year equals 1 and the year number is followed by the year sign \u5e74 // In Japanese dates, the first year in the era is not formatted as a number 1 instead it is formatted as \u5143 which means // first or beginning of the era. result.Append(DateTimeFormatInfo.JapaneseEraStart[0]); } else if (dtfi.HasForceTwoDigitYears) { FormatDigits(result, year, tokenLen <= 2 ? tokenLen : 2); } else if (cal.ID == CalendarId.HEBREW) { HebrewFormatDigits(result, year); } else { if (tokenLen <= 2) { FormatDigits(result, year % 100, tokenLen); } else if (tokenLen <= 16) // FormatDigits has an implicit 16-digit limit { FormatDigits(result, year, tokenLen, overrideLengthLimit: true); } else { result.Append(year.ToString("D" + tokenLen.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture)); } } bTimeOnly = false; break; case 'z': tokenLen = ParseRepeatPattern(format, i, ch); FormatCustomizedTimeZone(dateTime, offset, tokenLen, bTimeOnly, result); break; case 'K': tokenLen = 1; FormatCustomizedRoundripTimeZone(dateTime, offset, result); break; case ':': result.Append(dtfi.TimeSeparator); tokenLen = 1; break; case '/': result.Append(dtfi.DateSeparator); tokenLen = 1; break; case '\'': case '\"': tokenLen = ParseQuoteString(format, i, result); break; case '%': // Optional format character. // For example, format string "%d" will print day of month // without leading zero. Most of the cases, "%" can be ignored. nextChar = ParseNextChar(format, i); // nextChar will be -1 if we have already reached the end of the format string. // Besides, we will not allow "%%" to appear in the pattern. if (nextChar >= 0 && nextChar != '%') { char nextCharChar = (char)nextChar; StringBuilder origStringBuilder = FormatCustomized(dateTime, MemoryMarshal.CreateReadOnlySpan<char>(ref nextCharChar, 1), dtfi, offset, result); Debug.Assert(ReferenceEquals(origStringBuilder, result)); tokenLen = 2; } else { // // This means that '%' is at the end of the format string or // "%%" appears in the format string. // if (resultBuilderIsPooled) { StringBuilderCache.Release(result); } throw new FormatException(SR.Format_InvalidString); } break; case '\\': // Escaped character. Can be used to insert a character into the format string. // For example, "\d" will insert the character 'd' into the string. // // NOTENOTE : we can remove this format character if we enforce the enforced quote // character rule. // That is, we ask everyone to use single quote or double quote to insert characters, // then we can remove this character. // nextChar = ParseNextChar(format, i); if (nextChar >= 0) { result.Append((char)nextChar); tokenLen = 2; } else { // // This means that '\' is at the end of the formatting string. // if (resultBuilderIsPooled) { StringBuilderCache.Release(result); } throw new FormatException(SR.Format_InvalidString); } break; default: // NOTENOTE : we can remove this rule if we enforce the enforced quote // character rule. // That is, if we ask everyone to use single quote or double quote to insert characters, // then we can remove this default block. result.Append(ch); tokenLen = 1; break; } i += tokenLen; } return result; } // output the 'z' family of formats, which output a the offset from UTC, e.g. "-07:30" private static void FormatCustomizedTimeZone(DateTime dateTime, TimeSpan offset, int tokenLen, bool timeOnly, StringBuilder result) { // See if the instance already has an offset bool dateTimeFormat = (offset.Ticks == NullOffset); if (dateTimeFormat) { // No offset. The instance is a DateTime and the output should be the local time zone if (timeOnly && dateTime.Ticks < Calendar.TicksPerDay) { // For time only format and a time only input, the time offset on 0001/01/01 is less // accurate than the system's current offset because of daylight saving time. offset = TimeZoneInfo.GetLocalUtcOffset(DateTime.Now, TimeZoneInfoOptions.NoThrowOnInvalidTime); } else if (dateTime.Kind == DateTimeKind.Utc) { offset = default; // TimeSpan.Zero } else { offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); } } if (offset.Ticks >= 0) { result.Append('+'); } else { result.Append('-'); // get a positive offset, so that you don't need a separate code path for the negative numbers. offset = offset.Negate(); } if (tokenLen <= 1) { // 'z' format e.g "-7" result.Append(CultureInfo.InvariantCulture, $"{offset.Hours:0}"); } else { // 'zz' or longer format e.g "-07" result.Append(CultureInfo.InvariantCulture, $"{offset.Hours:00}"); if (tokenLen >= 3) { // 'zzz*' or longer format e.g "-07:30" result.Append(CultureInfo.InvariantCulture, $":{offset.Minutes:00}"); } } } // output the 'K' format, which is for round-tripping the data private static void FormatCustomizedRoundripTimeZone(DateTime dateTime, TimeSpan offset, StringBuilder result) { // The objective of this format is to round trip the data in the type // For DateTime it should round-trip the Kind value and preserve the time zone. // DateTimeOffset instance, it should do so by using the internal time zone. if (offset.Ticks == NullOffset) { // source is a date time, so behavior depends on the kind. switch (dateTime.Kind) { case DateTimeKind.Local: // This should output the local offset, e.g. "-07:30" offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); // fall through to shared time zone output code break; case DateTimeKind.Utc: // The 'Z' constant is a marker for a UTC date result.Append('Z'); return; default: // If the kind is unspecified, we output nothing here return; } } if (offset.Ticks >= 0) { result.Append('+'); } else { result.Append('-'); // get a positive offset, so that you don't need a separate code path for the negative numbers. offset = offset.Negate(); } Append2DigitNumber(result, offset.Hours); result.Append(':'); Append2DigitNumber(result, offset.Minutes); } private static void Append2DigitNumber(StringBuilder result, int val) { result.Append((char)('0' + (val / 10))); result.Append((char)('0' + (val % 10))); } internal static string GetRealFormat(ReadOnlySpan<char> format, DateTimeFormatInfo dtfi) { string realFormat; switch (format[0]) { case 'd': // Short Date realFormat = dtfi.ShortDatePattern; break; case 'D': // Long Date realFormat = dtfi.LongDatePattern; break; case 'f': // Full (long date + short time) realFormat = dtfi.LongDatePattern + " " + dtfi.ShortTimePattern; break; case 'F': // Full (long date + long time) realFormat = dtfi.FullDateTimePattern; break; case 'g': // General (short date + short time) realFormat = dtfi.GeneralShortTimePattern; break; case 'G': // General (short date + long time) realFormat = dtfi.GeneralLongTimePattern; break; case 'm': case 'M': // Month/Day Date realFormat = dtfi.MonthDayPattern; break; case 'o': case 'O': realFormat = RoundtripFormat; break; case 'r': case 'R': // RFC 1123 Standard realFormat = dtfi.RFC1123Pattern; break; case 's': // Sortable without Time Zone Info realFormat = dtfi.SortableDateTimePattern; break; case 't': // Short Time realFormat = dtfi.ShortTimePattern; break; case 'T': // Long Time realFormat = dtfi.LongTimePattern; break; case 'u': // Universal with Sortable format realFormat = dtfi.UniversalSortableDateTimePattern; break; case 'U': // Universal with Full (long date + long time) format realFormat = dtfi.FullDateTimePattern; break; case 'y': case 'Y': // Year/Month Date realFormat = dtfi.YearMonthPattern; break; default: throw new FormatException(SR.Format_InvalidString); } return realFormat; } // Expand a pre-defined format string (like "D" for long date) to the real format that // we are going to use in the date time parsing. // This method also convert the dateTime if necessary (e.g. when the format is in Universal time), // and change dtfi if necessary (e.g. when the format should use invariant culture). // private static string ExpandPredefinedFormat(ReadOnlySpan<char> format, ref DateTime dateTime, ref DateTimeFormatInfo dtfi, TimeSpan offset) { switch (format[0]) { case 'o': case 'O': // Round trip format dtfi = DateTimeFormatInfo.InvariantInfo; break; case 'r': case 'R': // RFC 1123 Standard case 'u': // Universal time in sortable format. if (offset.Ticks != NullOffset) { // Convert to UTC invariants mean this will be in range dateTime -= offset; } dtfi = DateTimeFormatInfo.InvariantInfo; break; case 's': // Sortable without Time Zone Info dtfi = DateTimeFormatInfo.InvariantInfo; break; case 'U': // Universal time in culture dependent format. if (offset.Ticks != NullOffset) { // This format is not supported by DateTimeOffset throw new FormatException(SR.Format_InvalidString); } // Universal time is always in Gregorian calendar. // // Change the Calendar to be Gregorian Calendar. // dtfi = (DateTimeFormatInfo)dtfi.Clone(); if (dtfi.Calendar.GetType() != typeof(GregorianCalendar)) { dtfi.Calendar = GregorianCalendar.GetDefaultInstance(); } dateTime = dateTime.ToUniversalTime(); break; } return GetRealFormat(format, dtfi); } internal static string Format(DateTime dateTime, string? format, IFormatProvider? provider) { return Format(dateTime, format, provider, new TimeSpan(NullOffset)); } internal static string Format(DateTime dateTime, string? format, IFormatProvider? provider, TimeSpan offset) { if (format != null && format.Length == 1) { // Optimize for these standard formats that are not affected by culture. switch (format[0]) { // Round trip format case 'o': case 'O': const int MinFormatOLength = 27, MaxFormatOLength = 33; Span<char> span = stackalloc char[MaxFormatOLength]; TryFormatO(dateTime, offset, span, out int ochars); Debug.Assert(ochars >= MinFormatOLength && ochars <= MaxFormatOLength); return span.Slice(0, ochars).ToString(); // RFC1123 case 'r': case 'R': const int FormatRLength = 29; string str = string.FastAllocateString(FormatRLength); TryFormatR(dateTime, offset, new Span<char>(ref str.GetRawStringData(), str.Length), out int rchars); Debug.Assert(rchars == str.Length); return str; } } DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(provider); return StringBuilderCache.GetStringAndRelease(FormatStringBuilder(dateTime, format, dtfi, offset)); } internal static bool TryFormat(DateTime dateTime, Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider) => TryFormat(dateTime, destination, out charsWritten, format, provider, new TimeSpan(NullOffset)); internal static bool TryFormat(DateTime dateTime, Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider, TimeSpan offset) { if (format.Length == 1) { // Optimize for these standard formats that are not affected by culture. switch (format[0]) { // Round trip format case 'o': case 'O': return TryFormatO(dateTime, offset, destination, out charsWritten); // RFC1123 case 'r': case 'R': return TryFormatR(dateTime, offset, destination, out charsWritten); } } DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(provider); StringBuilder sb = FormatStringBuilder(dateTime, format, dtfi, offset); bool success = sb.Length <= destination.Length; if (success) { sb.CopyTo(0, destination, sb.Length); charsWritten = sb.Length; } else { charsWritten = 0; } StringBuilderCache.Release(sb); return success; } private static StringBuilder FormatStringBuilder(DateTime dateTime, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi, TimeSpan offset) { Debug.Assert(dtfi != null); if (format.Length == 0) { bool timeOnlySpecialCase = false; if (dateTime.Ticks < Calendar.TicksPerDay) { // If the time is less than 1 day, consider it as time of day. // Just print out the short time format. // // This is a workaround for VB, since they use ticks less then one day to be // time of day. In cultures which use calendar other than Gregorian calendar, these // alternative calendar may not support ticks less than a day. // For example, Japanese calendar only supports date after 1868/9/8. // This will pose a problem when people in VB get the time of day, and use it // to call ToString(), which will use the general format (short date + long time). // Since Japanese calendar does not support Gregorian year 0001, an exception will be // thrown when we try to get the Japanese year for Gregorian year 0001. // Therefore, the workaround allows them to call ToString() for time of day from a DateTime by // formatting as ISO 8601 format. switch (dtfi.Calendar.ID) { case CalendarId.JAPAN: case CalendarId.TAIWAN: case CalendarId.HIJRI: case CalendarId.HEBREW: case CalendarId.JULIAN: case CalendarId.UMALQURA: case CalendarId.PERSIAN: timeOnlySpecialCase = true; dtfi = DateTimeFormatInfo.InvariantInfo; break; } } if (offset.Ticks == NullOffset) { // Default DateTime.ToString case. format = timeOnlySpecialCase ? "s" : "G"; } else { // Default DateTimeOffset.ToString case. format = timeOnlySpecialCase ? RoundtripDateTimeUnfixed : dtfi.DateTimeOffsetPattern; } } if (format.Length == 1) { format = ExpandPredefinedFormat(format, ref dateTime, ref dtfi, offset); } return FormatCustomized(dateTime, format, dtfi, offset, result: null); } internal static bool IsValidCustomDateFormat(ReadOnlySpan<char> format, bool throwOnError) { int i = 0; while (i < format.Length) { switch (format[i]) { case '\\': if (i == format.Length - 1) { if (throwOnError) { throw new FormatException(SR.Format_InvalidString); } return false; } i += 2; break; case '\'': case '"': char quoteChar = format[i++]; while (i < format.Length && format[i] != quoteChar) { i++; } if (i >= format.Length) { if (throwOnError) { throw new FormatException(SR.Format(SR.Format_BadQuote, quoteChar)); } return false; } i++; break; case ':': case 't': case 'f': case 'F': case 'h': case 'H': case 'm': case 's': case 'z': case 'K': // reject non-date formats if (throwOnError) { throw new FormatException(SR.Format_InvalidString); } return false; default: i++; break; } } return true; } internal static bool IsValidCustomTimeFormat(ReadOnlySpan<char> format, bool throwOnError) { int length = format.Length; int i = 0; while (i < length) { switch (format[i]) { case '\\': if (i == length - 1) { if (throwOnError) { throw new FormatException(SR.Format_InvalidString); } return false; } i += 2; break; case '\'': case '"': char quoteChar = format[i++]; while (i < length && format[i] != quoteChar) { i++; } if (i >= length) { if (throwOnError) { throw new FormatException(SR.Format(SR.Format_BadQuote, quoteChar)); } return false; } i++; break; case 'd': case 'M': case 'y': case '/': case 'z': case 'k': if (throwOnError) { throw new FormatException(SR.Format_InvalidString); } return false; default: i++; break; } } return true; } // 012345678901234567890123456789012 // --------------------------------- // 05:30:45.7680000 internal static bool TryFormatTimeOnlyO(int hour, int minute, int second, long fraction, Span<char> destination) { if (destination.Length < 16) { return false; } WriteTwoDecimalDigits((uint)hour, destination, 0); destination[2] = ':'; WriteTwoDecimalDigits((uint)minute, destination, 3); destination[5] = ':'; WriteTwoDecimalDigits((uint)second, destination, 6); destination[8] = '.'; WriteDigits((uint)fraction, destination.Slice(9, 7)); return true; } // 012345678901234567890123456789012 // --------------------------------- // 05:30:45 internal static bool TryFormatTimeOnlyR(int hour, int minute, int second, Span<char> destination) { if (destination.Length < 8) { return false; } WriteTwoDecimalDigits((uint)hour, destination, 0); destination[2] = ':'; WriteTwoDecimalDigits((uint)minute, destination, 3); destination[5] = ':'; WriteTwoDecimalDigits((uint)second, destination, 6); return true; } // Roundtrippable format. One of // 012345678901234567890123456789012 // --------------------------------- // 2017-06-12 internal static bool TryFormatDateOnlyO(int year, int month, int day, Span<char> destination) { if (destination.Length < 10) { return false; } WriteFourDecimalDigits((uint)year, destination, 0); destination[4] = '-'; WriteTwoDecimalDigits((uint)month, destination, 5); destination[7] = '-'; WriteTwoDecimalDigits((uint)day, destination, 8); return true; } // Rfc1123 // 01234567890123456789012345678 // ----------------------------- // Tue, 03 Jan 2017 internal static bool TryFormatDateOnlyR(DayOfWeek dayOfWeek, int year, int month, int day, Span<char> destination) { if (destination.Length < 16) { return false; } string dayAbbrev = InvariantAbbreviatedDayNames[(int)dayOfWeek]; Debug.Assert(dayAbbrev.Length == 3); string monthAbbrev = InvariantAbbreviatedMonthNames[month - 1]; Debug.Assert(monthAbbrev.Length == 3); destination[0] = dayAbbrev[0]; destination[1] = dayAbbrev[1]; destination[2] = dayAbbrev[2]; destination[3] = ','; destination[4] = ' '; WriteTwoDecimalDigits((uint)day, destination, 5); destination[7] = ' '; destination[8] = monthAbbrev[0]; destination[9] = monthAbbrev[1]; destination[10] = monthAbbrev[2]; destination[11] = ' '; WriteFourDecimalDigits((uint)year, destination, 12); return true; } // Roundtrippable format. One of // 012345678901234567890123456789012 // --------------------------------- // 2017-06-12T05:30:45.7680000-07:00 // 2017-06-12T05:30:45.7680000Z (Z is short for "+00:00" but also distinguishes DateTimeKind.Utc from DateTimeKind.Local) // 2017-06-12T05:30:45.7680000 (interpreted as local time wrt to current time zone) private static bool TryFormatO(DateTime dateTime, TimeSpan offset, Span<char> destination, out int charsWritten) { const int MinimumBytesNeeded = 27; int charsRequired = MinimumBytesNeeded; DateTimeKind kind = DateTimeKind.Local; if (offset.Ticks == NullOffset) { kind = dateTime.Kind; if (kind == DateTimeKind.Local) { offset = TimeZoneInfo.Local.GetUtcOffset(dateTime); charsRequired += 6; } else if (kind == DateTimeKind.Utc) { charsRequired++; } } else { charsRequired += 6; } if (destination.Length < charsRequired) { charsWritten = 0; return false; } charsWritten = charsRequired; // Hoist most of the bounds checks on destination. { _ = destination[MinimumBytesNeeded - 1]; } dateTime.GetDate(out int year, out int month, out int day); dateTime.GetTimePrecise(out int hour, out int minute, out int second, out int tick); WriteFourDecimalDigits((uint)year, destination, 0); destination[4] = '-'; WriteTwoDecimalDigits((uint)month, destination, 5); destination[7] = '-'; WriteTwoDecimalDigits((uint)day, destination, 8); destination[10] = 'T'; WriteTwoDecimalDigits((uint)hour, destination, 11); destination[13] = ':'; WriteTwoDecimalDigits((uint)minute, destination, 14); destination[16] = ':'; WriteTwoDecimalDigits((uint)second, destination, 17); destination[19] = '.'; WriteDigits((uint)tick, destination.Slice(20, 7)); if (kind == DateTimeKind.Local) { int offsetTotalMinutes = (int)(offset.Ticks / TimeSpan.TicksPerMinute); char sign; if (offsetTotalMinutes < 0) { sign = '-'; offsetTotalMinutes = -offsetTotalMinutes; } else { sign = '+'; } int offsetHours = Math.DivRem(offsetTotalMinutes, 60, out int offsetMinutes); // Writing the value backward allows the JIT to optimize by // performing a single bounds check against buffer. WriteTwoDecimalDigits((uint)offsetMinutes, destination, 31); destination[30] = ':'; WriteTwoDecimalDigits((uint)offsetHours, destination, 28); destination[27] = sign; } else if (kind == DateTimeKind.Utc) { destination[27] = 'Z'; } return true; } // Rfc1123 // 01234567890123456789012345678 // ----------------------------- // Tue, 03 Jan 2017 08:08:05 GMT private static bool TryFormatR(DateTime dateTime, TimeSpan offset, Span<char> destination, out int charsWritten) { if (destination.Length <= 28) { charsWritten = 0; return false; } if (offset.Ticks != NullOffset) { // Convert to UTC invariants. dateTime -= offset; } dateTime.GetDate(out int year, out int month, out int day); dateTime.GetTime(out int hour, out int minute, out int second); string dayAbbrev = InvariantAbbreviatedDayNames[(int)dateTime.DayOfWeek]; Debug.Assert(dayAbbrev.Length == 3); string monthAbbrev = InvariantAbbreviatedMonthNames[month - 1]; Debug.Assert(monthAbbrev.Length == 3); destination[0] = dayAbbrev[0]; destination[1] = dayAbbrev[1]; destination[2] = dayAbbrev[2]; destination[3] = ','; destination[4] = ' '; WriteTwoDecimalDigits((uint)day, destination, 5); destination[7] = ' '; destination[8] = monthAbbrev[0]; destination[9] = monthAbbrev[1]; destination[10] = monthAbbrev[2]; destination[11] = ' '; WriteFourDecimalDigits((uint)year, destination, 12); destination[16] = ' '; WriteTwoDecimalDigits((uint)hour, destination, 17); destination[19] = ':'; WriteTwoDecimalDigits((uint)minute, destination, 20); destination[22] = ':'; WriteTwoDecimalDigits((uint)second, destination, 23); destination[25] = ' '; destination[26] = 'G'; destination[27] = 'M'; destination[28] = 'T'; charsWritten = 29; return true; } /// <summary> /// Writes a value [ 00 .. 99 ] to the buffer starting at the specified offset. /// This method performs best when the starting index is a constant literal. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteTwoDecimalDigits(uint value, Span<char> destination, int offset) { Debug.Assert(value <= 99); uint temp = '0' + value; value /= 10; destination[offset + 1] = (char)(temp - (value * 10)); destination[offset] = (char)('0' + value); } /// <summary> /// Writes a value [ 0000 .. 9999 ] to the buffer starting at the specified offset. /// This method performs best when the starting index is a constant literal. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteFourDecimalDigits(uint value, Span<char> buffer, int startingIndex = 0) { Debug.Assert(value <= 9999); uint temp = '0' + value; value /= 10; buffer[startingIndex + 3] = (char)(temp - (value * 10)); temp = '0' + value; value /= 10; buffer[startingIndex + 2] = (char)(temp - (value * 10)); temp = '0' + value; value /= 10; buffer[startingIndex + 1] = (char)(temp - (value * 10)); buffer[startingIndex] = (char)('0' + value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteDigits(ulong value, Span<char> buffer) { // We can mutate the 'value' parameter since it's a copy-by-value local. // It'll be used to represent the value left over after each division by 10. for (int i = buffer.Length - 1; i >= 1; i--) { ulong temp = '0' + value; value /= 10; buffer[i] = (char)(temp - (value * 10)); } Debug.Assert(value < 10); buffer[0] = (char)('0' + value); } internal static string[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi) { Debug.Assert(dtfi != null); string[] allFormats; string[] results; switch (format) { case 'd': case 'D': case 'f': case 'F': case 'g': case 'G': case 'm': case 'M': case 't': case 'T': case 'y': case 'Y': allFormats = dtfi.GetAllDateTimePatterns(format); results = new string[allFormats.Length]; for (int i = 0; i < allFormats.Length; i++) { results[i] = Format(dateTime, allFormats[i], dtfi); } break; case 'U': DateTime universalTime = dateTime.ToUniversalTime(); allFormats = dtfi.GetAllDateTimePatterns(format); results = new string[allFormats.Length]; for (int i = 0; i < allFormats.Length; i++) { results[i] = Format(universalTime, allFormats[i], dtfi); } break; // // The following ones are special cases because these patterns are read-only in // DateTimeFormatInfo. // case 'r': case 'R': case 'o': case 'O': case 's': case 'u': results = new string[] { Format(dateTime, char.ToString(format), dtfi) }; break; default: throw new FormatException(SR.Format_InvalidString); } return results; } internal static string[] GetAllDateTimes(DateTime dateTime, DateTimeFormatInfo dtfi) { List<string> results = new List<string>(DEFAULT_ALL_DATETIMES_SIZE); for (int i = 0; i < allStandardFormats.Length; i++) { string[] strings = GetAllDateTimes(dateTime, allStandardFormats[i], dtfi); for (int j = 0; j < strings.Length; j++) { results.Add(strings[j]); } } return results.ToArray(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Text; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System { /* Customized format patterns: P.S. Format in the table below is the internal number format used to display the pattern. Patterns Format Description Example ========= ========== ===================================== ======== "h" "0" hour (12-hour clock)w/o leading zero 3 "hh" "00" hour (12-hour clock)with leading zero 03 "hh*" "00" hour (12-hour clock)with leading zero 03 "H" "0" hour (24-hour clock)w/o leading zero 8 "HH" "00" hour (24-hour clock)with leading zero 08 "HH*" "00" hour (24-hour clock) 08 "m" "0" minute w/o leading zero "mm" "00" minute with leading zero "mm*" "00" minute with leading zero "s" "0" second w/o leading zero "ss" "00" second with leading zero "ss*" "00" second with leading zero "f" "0" second fraction (1 digit) "ff" "00" second fraction (2 digit) "fff" "000" second fraction (3 digit) "ffff" "0000" second fraction (4 digit) "fffff" "00000" second fraction (5 digit) "ffffff" "000000" second fraction (6 digit) "fffffff" "0000000" second fraction (7 digit) "F" "0" second fraction (up to 1 digit) "FF" "00" second fraction (up to 2 digit) "FFF" "000" second fraction (up to 3 digit) "FFFF" "0000" second fraction (up to 4 digit) "FFFFF" "00000" second fraction (up to 5 digit) "FFFFFF" "000000" second fraction (up to 6 digit) "FFFFFFF" "0000000" second fraction (up to 7 digit) "t" first character of AM/PM designator A "tt" AM/PM designator AM "tt*" AM/PM designator PM "d" "0" day w/o leading zero 1 "dd" "00" day with leading zero 01 "ddd" short weekday name (abbreviation) Mon "dddd" full weekday name Monday "dddd*" full weekday name Monday "M" "0" month w/o leading zero 2 "MM" "00" month with leading zero 02 "MMM" short month name (abbreviation) Feb "MMMM" full month name February "MMMM*" full month name February "y" "0" two digit year (year % 100) w/o leading zero 0 "yy" "00" two digit year (year % 100) with leading zero 00 "yyy" "D3" year 2000 "yyyy" "D4" year 2000 "yyyyy" "D5" year 2000 ... "z" "+0;-0" timezone offset w/o leading zero -8 "zz" "+00;-00" timezone offset with leading zero -08 "zzz" "+00;-00" for hour offset, "00" for minute offset full timezone offset -07:30 "zzz*" "+00;-00" for hour offset, "00" for minute offset full timezone offset -08:00 "K" -Local "zzz", e.g. -08:00 -Utc "'Z'", representing UTC -Unspecified "" -DateTimeOffset "zzzzz" e.g -07:30:15 "g*" the current era name A.D. ":" time separator : -- DEPRECATED - Insert separator directly into pattern (eg: "H.mm.ss") "/" date separator /-- DEPRECATED - Insert separator directly into pattern (eg: "M-dd-yyyy") "'" quoted string 'ABC' will insert ABC into the formatted string. '"' quoted string "ABC" will insert ABC into the formatted string. "%" used to quote a single pattern characters E.g.The format character "%y" is to print two digit year. "\" escaped character E.g. '\d' insert the character 'd' into the format string. other characters insert the character into the format string. Pre-defined format characters: (U) to indicate Universal time is used. (G) to indicate Gregorian calendar is used. Format Description Real format Example ========= ================================= ====================== ======================= "d" short date culture-specific 10/31/1999 "D" long data culture-specific Sunday, October 31, 1999 "f" full date (long date + short time) culture-specific Sunday, October 31, 1999 2:00 AM "F" full date (long date + long time) culture-specific Sunday, October 31, 1999 2:00:00 AM "g" general date (short date + short time) culture-specific 10/31/1999 2:00 AM "G" general date (short date + long time) culture-specific 10/31/1999 2:00:00 AM "m"/"M" Month/Day date culture-specific October 31 (G) "o"/"O" Round Trip XML "yyyy-MM-ddTHH:mm:ss.fffffffK" 1999-10-31 02:00:00.0000000Z (G) "r"/"R" RFC 1123 date, "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'" Sun, 31 Oct 1999 10:00:00 GMT (G) "s" Sortable format, based on ISO 8601. "yyyy-MM-dd'T'HH:mm:ss" 1999-10-31T02:00:00 ('T' for local time) "t" short time culture-specific 2:00 AM "T" long time culture-specific 2:00:00 AM (G) "u" Universal time with sortable format, "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" 1999-10-31 10:00:00Z based on ISO 8601. (U) "U" Universal time with full culture-specific Sunday, October 31, 1999 10:00:00 AM (long date + long time) format "y"/"Y" Year/Month day culture-specific October, 1999 */ // This class contains only static members and does not require the serializable attribute. internal static class DateTimeFormat { internal const int MaxSecondsFractionDigits = 7; internal const long NullOffset = long.MinValue; internal static char[] allStandardFormats = { 'd', 'D', 'f', 'F', 'g', 'G', 'm', 'M', 'o', 'O', 'r', 'R', 's', 't', 'T', 'u', 'U', 'y', 'Y', }; internal const string RoundtripFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"; internal const string RoundtripDateTimeUnfixed = "yyyy'-'MM'-'ddTHH':'mm':'ss zzz"; private const int DEFAULT_ALL_DATETIMES_SIZE = 132; internal static readonly DateTimeFormatInfo InvariantFormatInfo = CultureInfo.InvariantCulture.DateTimeFormat; internal static readonly string[] InvariantAbbreviatedMonthNames = InvariantFormatInfo.AbbreviatedMonthNames; internal static readonly string[] InvariantAbbreviatedDayNames = InvariantFormatInfo.AbbreviatedDayNames; internal const string Gmt = "GMT"; internal static string[] fixedNumberFormats = new string[] { "0", "00", "000", "0000", "00000", "000000", "0000000", }; //////////////////////////////////////////////////////////////////////////// // // Format the positive integer value to a string and prefix with assigned // length of leading zero. // // Parameters: // value: The value to format // len: The maximum length for leading zero. // If the digits of the value is greater than len, no leading zero is added. // // Notes: // The function can format to int.MaxValue. // //////////////////////////////////////////////////////////////////////////// internal static void FormatDigits(StringBuilder outputBuffer, int value, int len) { Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0"); FormatDigits(outputBuffer, value, len, false); } internal static unsafe void FormatDigits(StringBuilder outputBuffer, int value, int len, bool overrideLengthLimit) { Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0"); // Limit the use of this function to be two-digits, so that we have the same behavior // as RTM bits. if (!overrideLengthLimit && len > 2) { len = 2; } char* buffer = stackalloc char[16]; char* p = buffer + 16; int n = value; do { *--p = (char)(n % 10 + '0'); n /= 10; } while ((n != 0) && (p > buffer)); int digits = (int)(buffer + 16 - p); // If the repeat count is greater than 0, we're trying // to emulate the "00" format, so we have to prepend // a zero if the string only has one character. while ((digits < len) && (p > buffer)) { *--p = '0'; digits++; } outputBuffer.Append(p, digits); } private static void HebrewFormatDigits(StringBuilder outputBuffer, int digits) { HebrewNumber.Append(outputBuffer, digits); } internal static int ParseRepeatPattern(ReadOnlySpan<char> format, int pos, char patternChar) { int len = format.Length; int index = pos + 1; while ((index < len) && (format[index] == patternChar)) { index++; } return index - pos; } private static string FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi) { Debug.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6"); if (repeat == 3) { return dtfi.GetAbbreviatedDayName((DayOfWeek)dayOfWeek); } // Call dtfi.GetDayName() here, instead of accessing DayNames property, because we don't // want a clone of DayNames, which will hurt perf. return dtfi.GetDayName((DayOfWeek)dayOfWeek); } private static string FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi) { Debug.Assert(month >= 1 && month <= 12, "month >=1 && month <= 12"); if (repeatCount == 3) { return dtfi.GetAbbreviatedMonthName(month); } // Call GetMonthName() here, instead of accessing MonthNames property, because we don't // want a clone of MonthNames, which will hurt perf. return dtfi.GetMonthName(month); } // // FormatHebrewMonthName // // Action: Return the Hebrew month name for the specified DateTime. // Returns: The month name string for the specified DateTime. // Arguments: // time the time to format // month The month is the value of HebrewCalendar.GetMonth(time). // repeat Return abbreviated month name if repeat=3, or full month name if repeat=4 // dtfi The DateTimeFormatInfo which uses the Hebrew calendars as its calendar. // Exceptions: None. // /* Note: If DTFI is using Hebrew calendar, GetMonthName()/GetAbbreviatedMonthName() will return month names like this: 1 Hebrew 1st Month 2 Hebrew 2nd Month .. ... 6 Hebrew 6th Month 7 Hebrew 6th Month II (used only in a leap year) 8 Hebrew 7th Month 9 Hebrew 8th Month 10 Hebrew 9th Month 11 Hebrew 10th Month 12 Hebrew 11th Month 13 Hebrew 12th Month Therefore, if we are in a regular year, we have to increment the month name if month is greater or equal to 7. */ private static string FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi) { Debug.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4"); if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time))) { // This month is in a leap year return dtfi.InternalGetMonthName(month, MonthNameStyles.LeapYear, repeatCount == 3); } // This is in a regular year. if (month >= 7) { month++; } if (repeatCount == 3) { return dtfi.GetAbbreviatedMonthName(month); } return dtfi.GetMonthName(month); } // // The pos should point to a quote character. This method will // append to the result StringBuilder the string enclosed by the quote character. // internal static int ParseQuoteString(ReadOnlySpan<char> format, int pos, StringBuilder result) { // // NOTE : pos will be the index of the quote character in the 'format' string. // int formatLen = format.Length; int beginPos = pos; char quoteChar = format[pos++]; // Get the character used to quote the following string. bool foundQuote = false; while (pos < formatLen) { char ch = format[pos++]; if (ch == quoteChar) { foundQuote = true; break; } else if (ch == '\\') { // The following are used to support escaped character. // Escaped character is also supported in the quoted string. // Therefore, someone can use a format like "'minute:' mm\"" to display: // minute: 45" // because the second double quote is escaped. if (pos < formatLen) { result.Append(format[pos++]); } else { // // This means that '\' is at the end of the formatting string. // throw new FormatException(SR.Format_InvalidString); } } else { result.Append(ch); } } if (!foundQuote) { // Here we can't find the matching quote. throw new FormatException(SR.Format(SR.Format_BadQuote, quoteChar)); } // // Return the character count including the begin/end quote characters and enclosed string. // return pos - beginPos; } // // Get the next character at the index of 'pos' in the 'format' string. // Return value of -1 means 'pos' is already at the end of the 'format' string. // Otherwise, return value is the int value of the next character. // internal static int ParseNextChar(ReadOnlySpan<char> format, int pos) { if (pos >= format.Length - 1) { return -1; } return (int)format[pos + 1]; } // // IsUseGenitiveForm // // Actions: Check the format to see if we should use genitive month in the formatting. // Starting at the position (index) in the (format) string, look back and look ahead to // see if there is "d" or "dd". In the case like "d MMMM" or "MMMM dd", we can use // genitive form. Genitive form is not used if there is more than two "d". // Arguments: // format The format string to be scanned. // index Where we should start the scanning. This is generally where "M" starts. // tokenLen The len of the current pattern character. This indicates how many "M" that we have. // patternToMatch The pattern that we want to search. This generally uses "d" // private static bool IsUseGenitiveForm(ReadOnlySpan<char> format, int index, int tokenLen, char patternToMatch) { int i; int repeat = 0; // // Look back to see if we can find "d" or "ddd" // // Find first "d". for (i = index - 1; i >= 0 && format[i] != patternToMatch; i--) { /*Do nothing here */ } if (i >= 0) { // Find a "d", so look back to see how many "d" that we can find. while (--i >= 0 && format[i] == patternToMatch) { repeat++; } // // repeat == 0 means that we have one (patternToMatch) // repeat == 1 means that we have two (patternToMatch) // if (repeat <= 1) { return true; } // Note that we can't just stop here. We may find "ddd" while looking back, and we have to look // ahead to see if there is "d" or "dd". } // // If we can't find "d" or "dd" by looking back, try look ahead. // // Find first "d" for (i = index + tokenLen; i < format.Length && format[i] != patternToMatch; i++) { /* Do nothing here */ } if (i < format.Length) { repeat = 0; // Find a "d", so contine the walk to see how may "d" that we can find. while (++i < format.Length && format[i] == patternToMatch) { repeat++; } // // repeat == 0 means that we have one (patternToMatch) // repeat == 1 means that we have two (patternToMatch) // if (repeat <= 1) { return true; } } return false; } // // FormatCustomized // // Actions: Format the DateTime instance using the specified format. // private static StringBuilder FormatCustomized( DateTime dateTime, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi, TimeSpan offset, StringBuilder? result) { Calendar cal = dtfi.Calendar; bool resultBuilderIsPooled = false; if (result == null) { resultBuilderIsPooled = true; result = StringBuilderCache.Acquire(); } // This is a flag to indicate if we are formatting the dates using Hebrew calendar. bool isHebrewCalendar = (cal.ID == CalendarId.HEBREW); bool isJapaneseCalendar = (cal.ID == CalendarId.JAPAN); // This is a flag to indicate if we are formatting hour/minute/second only. bool bTimeOnly = true; int i = 0; int tokenLen, hour12; while (i < format.Length) { char ch = format[i]; int nextChar; switch (ch) { case 'g': tokenLen = ParseRepeatPattern(format, i, ch); result.Append(dtfi.GetEraName(cal.GetEra(dateTime))); break; case 'h': tokenLen = ParseRepeatPattern(format, i, ch); hour12 = dateTime.Hour % 12; if (hour12 == 0) { hour12 = 12; } FormatDigits(result, hour12, tokenLen); break; case 'H': tokenLen = ParseRepeatPattern(format, i, ch); FormatDigits(result, dateTime.Hour, tokenLen); break; case 'm': tokenLen = ParseRepeatPattern(format, i, ch); FormatDigits(result, dateTime.Minute, tokenLen); break; case 's': tokenLen = ParseRepeatPattern(format, i, ch); FormatDigits(result, dateTime.Second, tokenLen); break; case 'f': case 'F': tokenLen = ParseRepeatPattern(format, i, ch); if (tokenLen <= MaxSecondsFractionDigits) { long fraction = (dateTime.Ticks % Calendar.TicksPerSecond); fraction /= (long)Math.Pow(10, 7 - tokenLen); if (ch == 'f') { result.AppendSpanFormattable((int)fraction, fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture); } else { int effectiveDigits = tokenLen; while (effectiveDigits > 0) { if (fraction % 10 == 0) { fraction /= 10; effectiveDigits--; } else { break; } } if (effectiveDigits > 0) { result.AppendSpanFormattable((int)fraction, fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture); } else { // No fraction to emit, so see if we should remove decimal also. if (result.Length > 0 && result[result.Length - 1] == '.') { result.Remove(result.Length - 1, 1); } } } } else { if (resultBuilderIsPooled) { StringBuilderCache.Release(result); } throw new FormatException(SR.Format_InvalidString); } break; case 't': tokenLen = ParseRepeatPattern(format, i, ch); if (tokenLen == 1) { if (dateTime.Hour < 12) { if (dtfi.AMDesignator.Length >= 1) { result.Append(dtfi.AMDesignator[0]); } } else { if (dtfi.PMDesignator.Length >= 1) { result.Append(dtfi.PMDesignator[0]); } } } else { result.Append(dateTime.Hour < 12 ? dtfi.AMDesignator : dtfi.PMDesignator); } break; case 'd': // // tokenLen == 1 : Day of month as digits with no leading zero. // tokenLen == 2 : Day of month as digits with leading zero for single-digit months. // tokenLen == 3 : Day of week as a three-letter abbreviation. // tokenLen >= 4 : Day of week as its full name. // tokenLen = ParseRepeatPattern(format, i, ch); if (tokenLen <= 2) { int day = cal.GetDayOfMonth(dateTime); if (isHebrewCalendar) { // For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values. HebrewFormatDigits(result, day); } else { FormatDigits(result, day, tokenLen); } } else { int dayOfWeek = (int)cal.GetDayOfWeek(dateTime); result.Append(FormatDayOfWeek(dayOfWeek, tokenLen, dtfi)); } bTimeOnly = false; break; case 'M': // // tokenLen == 1 : Month as digits with no leading zero. // tokenLen == 2 : Month as digits with leading zero for single-digit months. // tokenLen == 3 : Month as a three-letter abbreviation. // tokenLen >= 4 : Month as its full name. // tokenLen = ParseRepeatPattern(format, i, ch); int month = cal.GetMonth(dateTime); if (tokenLen <= 2) { if (isHebrewCalendar) { // For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values. HebrewFormatDigits(result, month); } else { FormatDigits(result, month, tokenLen); } } else { if (isHebrewCalendar) { result.Append(FormatHebrewMonthName(dateTime, month, tokenLen, dtfi)); } else { if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0) { result.Append( dtfi.InternalGetMonthName( month, IsUseGenitiveForm(format, i, tokenLen, 'd') ? MonthNameStyles.Genitive : MonthNameStyles.Regular, tokenLen == 3)); } else { result.Append(FormatMonth(month, tokenLen, dtfi)); } } } bTimeOnly = false; break; case 'y': // Notes about OS behavior: // y: Always print (year % 100). No leading zero. // yy: Always print (year % 100) with leading zero. // yyy/yyyy/yyyyy/... : Print year value. No leading zero. int year = cal.GetYear(dateTime); tokenLen = ParseRepeatPattern(format, i, ch); if (isJapaneseCalendar && !LocalAppContextSwitches.FormatJapaneseFirstYearAsANumber && year == 1 && ((i + tokenLen < format.Length && format[i + tokenLen] == DateTimeFormatInfoScanner.CJKYearSuff) || (i + tokenLen < format.Length - 1 && format[i + tokenLen] == '\'' && format[i + tokenLen + 1] == DateTimeFormatInfoScanner.CJKYearSuff))) { // We are formatting a Japanese date with year equals 1 and the year number is followed by the year sign \u5e74 // In Japanese dates, the first year in the era is not formatted as a number 1 instead it is formatted as \u5143 which means // first or beginning of the era. result.Append(DateTimeFormatInfo.JapaneseEraStart[0]); } else if (dtfi.HasForceTwoDigitYears) { FormatDigits(result, year, tokenLen <= 2 ? tokenLen : 2); } else if (cal.ID == CalendarId.HEBREW) { HebrewFormatDigits(result, year); } else { if (tokenLen <= 2) { FormatDigits(result, year % 100, tokenLen); } else if (tokenLen <= 16) // FormatDigits has an implicit 16-digit limit { FormatDigits(result, year, tokenLen, overrideLengthLimit: true); } else { result.Append(year.ToString("D" + tokenLen.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture)); } } bTimeOnly = false; break; case 'z': tokenLen = ParseRepeatPattern(format, i, ch); FormatCustomizedTimeZone(dateTime, offset, tokenLen, bTimeOnly, result); break; case 'K': tokenLen = 1; FormatCustomizedRoundripTimeZone(dateTime, offset, result); break; case ':': result.Append(dtfi.TimeSeparator); tokenLen = 1; break; case '/': result.Append(dtfi.DateSeparator); tokenLen = 1; break; case '\'': case '\"': tokenLen = ParseQuoteString(format, i, result); break; case '%': // Optional format character. // For example, format string "%d" will print day of month // without leading zero. Most of the cases, "%" can be ignored. nextChar = ParseNextChar(format, i); // nextChar will be -1 if we have already reached the end of the format string. // Besides, we will not allow "%%" to appear in the pattern. if (nextChar >= 0 && nextChar != '%') { char nextCharChar = (char)nextChar; StringBuilder origStringBuilder = FormatCustomized(dateTime, MemoryMarshal.CreateReadOnlySpan<char>(ref nextCharChar, 1), dtfi, offset, result); Debug.Assert(ReferenceEquals(origStringBuilder, result)); tokenLen = 2; } else { // // This means that '%' is at the end of the format string or // "%%" appears in the format string. // if (resultBuilderIsPooled) { StringBuilderCache.Release(result); } throw new FormatException(SR.Format_InvalidString); } break; case '\\': // Escaped character. Can be used to insert a character into the format string. // For example, "\d" will insert the character 'd' into the string. // // NOTENOTE : we can remove this format character if we enforce the enforced quote // character rule. // That is, we ask everyone to use single quote or double quote to insert characters, // then we can remove this character. // nextChar = ParseNextChar(format, i); if (nextChar >= 0) { result.Append((char)nextChar); tokenLen = 2; } else { // // This means that '\' is at the end of the formatting string. // if (resultBuilderIsPooled) { StringBuilderCache.Release(result); } throw new FormatException(SR.Format_InvalidString); } break; default: // NOTENOTE : we can remove this rule if we enforce the enforced quote // character rule. // That is, if we ask everyone to use single quote or double quote to insert characters, // then we can remove this default block. result.Append(ch); tokenLen = 1; break; } i += tokenLen; } return result; } // output the 'z' family of formats, which output a the offset from UTC, e.g. "-07:30" private static void FormatCustomizedTimeZone(DateTime dateTime, TimeSpan offset, int tokenLen, bool timeOnly, StringBuilder result) { // See if the instance already has an offset bool dateTimeFormat = (offset.Ticks == NullOffset); if (dateTimeFormat) { // No offset. The instance is a DateTime and the output should be the local time zone if (timeOnly && dateTime.Ticks < Calendar.TicksPerDay) { // For time only format and a time only input, the time offset on 0001/01/01 is less // accurate than the system's current offset because of daylight saving time. offset = TimeZoneInfo.GetLocalUtcOffset(DateTime.Now, TimeZoneInfoOptions.NoThrowOnInvalidTime); } else if (dateTime.Kind == DateTimeKind.Utc) { offset = default; // TimeSpan.Zero } else { offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); } } if (offset.Ticks >= 0) { result.Append('+'); } else { result.Append('-'); // get a positive offset, so that you don't need a separate code path for the negative numbers. offset = offset.Negate(); } if (tokenLen <= 1) { // 'z' format e.g "-7" result.Append(CultureInfo.InvariantCulture, $"{offset.Hours:0}"); } else { // 'zz' or longer format e.g "-07" result.Append(CultureInfo.InvariantCulture, $"{offset.Hours:00}"); if (tokenLen >= 3) { // 'zzz*' or longer format e.g "-07:30" result.Append(CultureInfo.InvariantCulture, $":{offset.Minutes:00}"); } } } // output the 'K' format, which is for round-tripping the data private static void FormatCustomizedRoundripTimeZone(DateTime dateTime, TimeSpan offset, StringBuilder result) { // The objective of this format is to round trip the data in the type // For DateTime it should round-trip the Kind value and preserve the time zone. // DateTimeOffset instance, it should do so by using the internal time zone. if (offset.Ticks == NullOffset) { // source is a date time, so behavior depends on the kind. switch (dateTime.Kind) { case DateTimeKind.Local: // This should output the local offset, e.g. "-07:30" offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); // fall through to shared time zone output code break; case DateTimeKind.Utc: // The 'Z' constant is a marker for a UTC date result.Append('Z'); return; default: // If the kind is unspecified, we output nothing here return; } } if (offset.Ticks >= 0) { result.Append('+'); } else { result.Append('-'); // get a positive offset, so that you don't need a separate code path for the negative numbers. offset = offset.Negate(); } Append2DigitNumber(result, offset.Hours); result.Append(':'); Append2DigitNumber(result, offset.Minutes); } private static void Append2DigitNumber(StringBuilder result, int val) { result.Append((char)('0' + (val / 10))); result.Append((char)('0' + (val % 10))); } internal static string GetRealFormat(ReadOnlySpan<char> format, DateTimeFormatInfo dtfi) { string realFormat; switch (format[0]) { case 'd': // Short Date realFormat = dtfi.ShortDatePattern; break; case 'D': // Long Date realFormat = dtfi.LongDatePattern; break; case 'f': // Full (long date + short time) realFormat = dtfi.LongDatePattern + " " + dtfi.ShortTimePattern; break; case 'F': // Full (long date + long time) realFormat = dtfi.FullDateTimePattern; break; case 'g': // General (short date + short time) realFormat = dtfi.GeneralShortTimePattern; break; case 'G': // General (short date + long time) realFormat = dtfi.GeneralLongTimePattern; break; case 'm': case 'M': // Month/Day Date realFormat = dtfi.MonthDayPattern; break; case 'o': case 'O': realFormat = RoundtripFormat; break; case 'r': case 'R': // RFC 1123 Standard realFormat = dtfi.RFC1123Pattern; break; case 's': // Sortable without Time Zone Info realFormat = dtfi.SortableDateTimePattern; break; case 't': // Short Time realFormat = dtfi.ShortTimePattern; break; case 'T': // Long Time realFormat = dtfi.LongTimePattern; break; case 'u': // Universal with Sortable format realFormat = dtfi.UniversalSortableDateTimePattern; break; case 'U': // Universal with Full (long date + long time) format realFormat = dtfi.FullDateTimePattern; break; case 'y': case 'Y': // Year/Month Date realFormat = dtfi.YearMonthPattern; break; default: throw new FormatException(SR.Format_InvalidString); } return realFormat; } // Expand a pre-defined format string (like "D" for long date) to the real format that // we are going to use in the date time parsing. // This method also convert the dateTime if necessary (e.g. when the format is in Universal time), // and change dtfi if necessary (e.g. when the format should use invariant culture). // private static string ExpandPredefinedFormat(ReadOnlySpan<char> format, ref DateTime dateTime, ref DateTimeFormatInfo dtfi, TimeSpan offset) { switch (format[0]) { case 'o': case 'O': // Round trip format dtfi = DateTimeFormatInfo.InvariantInfo; break; case 'r': case 'R': // RFC 1123 Standard case 'u': // Universal time in sortable format. if (offset.Ticks != NullOffset) { // Convert to UTC invariants mean this will be in range dateTime -= offset; } dtfi = DateTimeFormatInfo.InvariantInfo; break; case 's': // Sortable without Time Zone Info dtfi = DateTimeFormatInfo.InvariantInfo; break; case 'U': // Universal time in culture dependent format. if (offset.Ticks != NullOffset) { // This format is not supported by DateTimeOffset throw new FormatException(SR.Format_InvalidString); } // Universal time is always in Gregorian calendar. // // Change the Calendar to be Gregorian Calendar. // dtfi = (DateTimeFormatInfo)dtfi.Clone(); if (dtfi.Calendar.GetType() != typeof(GregorianCalendar)) { dtfi.Calendar = GregorianCalendar.GetDefaultInstance(); } dateTime = dateTime.ToUniversalTime(); break; } return GetRealFormat(format, dtfi); } internal static string Format(DateTime dateTime, string? format, IFormatProvider? provider) { return Format(dateTime, format, provider, new TimeSpan(NullOffset)); } internal static string Format(DateTime dateTime, string? format, IFormatProvider? provider, TimeSpan offset) { if (format != null && format.Length == 1) { // Optimize for these standard formats that are not affected by culture. switch (format[0]) { // Round trip format case 'o': case 'O': const int MinFormatOLength = 27, MaxFormatOLength = 33; Span<char> span = stackalloc char[MaxFormatOLength]; TryFormatO(dateTime, offset, span, out int ochars); Debug.Assert(ochars >= MinFormatOLength && ochars <= MaxFormatOLength); return span.Slice(0, ochars).ToString(); // RFC1123 case 'r': case 'R': const int FormatRLength = 29; string str = string.FastAllocateString(FormatRLength); TryFormatR(dateTime, offset, new Span<char>(ref str.GetRawStringData(), str.Length), out int rchars); Debug.Assert(rchars == str.Length); return str; } } DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(provider); return StringBuilderCache.GetStringAndRelease(FormatStringBuilder(dateTime, format, dtfi, offset)); } internal static bool TryFormat(DateTime dateTime, Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider) => TryFormat(dateTime, destination, out charsWritten, format, provider, new TimeSpan(NullOffset)); internal static bool TryFormat(DateTime dateTime, Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider, TimeSpan offset) { if (format.Length == 1) { // Optimize for these standard formats that are not affected by culture. switch (format[0]) { // Round trip format case 'o': case 'O': return TryFormatO(dateTime, offset, destination, out charsWritten); // RFC1123 case 'r': case 'R': return TryFormatR(dateTime, offset, destination, out charsWritten); } } DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(provider); StringBuilder sb = FormatStringBuilder(dateTime, format, dtfi, offset); bool success = sb.Length <= destination.Length; if (success) { sb.CopyTo(0, destination, sb.Length); charsWritten = sb.Length; } else { charsWritten = 0; } StringBuilderCache.Release(sb); return success; } private static StringBuilder FormatStringBuilder(DateTime dateTime, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi, TimeSpan offset) { Debug.Assert(dtfi != null); if (format.Length == 0) { bool timeOnlySpecialCase = false; if (dateTime.Ticks < Calendar.TicksPerDay) { // If the time is less than 1 day, consider it as time of day. // Just print out the short time format. // // This is a workaround for VB, since they use ticks less then one day to be // time of day. In cultures which use calendar other than Gregorian calendar, these // alternative calendar may not support ticks less than a day. // For example, Japanese calendar only supports date after 1868/9/8. // This will pose a problem when people in VB get the time of day, and use it // to call ToString(), which will use the general format (short date + long time). // Since Japanese calendar does not support Gregorian year 0001, an exception will be // thrown when we try to get the Japanese year for Gregorian year 0001. // Therefore, the workaround allows them to call ToString() for time of day from a DateTime by // formatting as ISO 8601 format. switch (dtfi.Calendar.ID) { case CalendarId.JAPAN: case CalendarId.TAIWAN: case CalendarId.HIJRI: case CalendarId.HEBREW: case CalendarId.JULIAN: case CalendarId.UMALQURA: case CalendarId.PERSIAN: timeOnlySpecialCase = true; dtfi = DateTimeFormatInfo.InvariantInfo; break; } } if (offset.Ticks == NullOffset) { // Default DateTime.ToString case. format = timeOnlySpecialCase ? "s" : "G"; } else { // Default DateTimeOffset.ToString case. format = timeOnlySpecialCase ? RoundtripDateTimeUnfixed : dtfi.DateTimeOffsetPattern; } } if (format.Length == 1) { format = ExpandPredefinedFormat(format, ref dateTime, ref dtfi, offset); } return FormatCustomized(dateTime, format, dtfi, offset, result: null); } internal static bool IsValidCustomDateFormat(ReadOnlySpan<char> format, bool throwOnError) { int i = 0; while (i < format.Length) { switch (format[i]) { case '\\': if (i == format.Length - 1) { if (throwOnError) { throw new FormatException(SR.Format_InvalidString); } return false; } i += 2; break; case '\'': case '"': char quoteChar = format[i++]; while (i < format.Length && format[i] != quoteChar) { i++; } if (i >= format.Length) { if (throwOnError) { throw new FormatException(SR.Format(SR.Format_BadQuote, quoteChar)); } return false; } i++; break; case ':': case 't': case 'f': case 'F': case 'h': case 'H': case 'm': case 's': case 'z': case 'K': // reject non-date formats if (throwOnError) { throw new FormatException(SR.Format_InvalidString); } return false; default: i++; break; } } return true; } internal static bool IsValidCustomTimeFormat(ReadOnlySpan<char> format, bool throwOnError) { int length = format.Length; int i = 0; while (i < length) { switch (format[i]) { case '\\': if (i == length - 1) { if (throwOnError) { throw new FormatException(SR.Format_InvalidString); } return false; } i += 2; break; case '\'': case '"': char quoteChar = format[i++]; while (i < length && format[i] != quoteChar) { i++; } if (i >= length) { if (throwOnError) { throw new FormatException(SR.Format(SR.Format_BadQuote, quoteChar)); } return false; } i++; break; case 'd': case 'M': case 'y': case '/': case 'z': case 'k': if (throwOnError) { throw new FormatException(SR.Format_InvalidString); } return false; default: i++; break; } } return true; } // 012345678901234567890123456789012 // --------------------------------- // 05:30:45.7680000 internal static bool TryFormatTimeOnlyO(int hour, int minute, int second, long fraction, Span<char> destination) { if (destination.Length < 16) { return false; } WriteTwoDecimalDigits((uint)hour, destination, 0); destination[2] = ':'; WriteTwoDecimalDigits((uint)minute, destination, 3); destination[5] = ':'; WriteTwoDecimalDigits((uint)second, destination, 6); destination[8] = '.'; WriteDigits((uint)fraction, destination.Slice(9, 7)); return true; } // 012345678901234567890123456789012 // --------------------------------- // 05:30:45 internal static bool TryFormatTimeOnlyR(int hour, int minute, int second, Span<char> destination) { if (destination.Length < 8) { return false; } WriteTwoDecimalDigits((uint)hour, destination, 0); destination[2] = ':'; WriteTwoDecimalDigits((uint)minute, destination, 3); destination[5] = ':'; WriteTwoDecimalDigits((uint)second, destination, 6); return true; } // Roundtrippable format. One of // 012345678901234567890123456789012 // --------------------------------- // 2017-06-12 internal static bool TryFormatDateOnlyO(int year, int month, int day, Span<char> destination) { if (destination.Length < 10) { return false; } WriteFourDecimalDigits((uint)year, destination, 0); destination[4] = '-'; WriteTwoDecimalDigits((uint)month, destination, 5); destination[7] = '-'; WriteTwoDecimalDigits((uint)day, destination, 8); return true; } // Rfc1123 // 01234567890123456789012345678 // ----------------------------- // Tue, 03 Jan 2017 internal static bool TryFormatDateOnlyR(DayOfWeek dayOfWeek, int year, int month, int day, Span<char> destination) { if (destination.Length < 16) { return false; } string dayAbbrev = InvariantAbbreviatedDayNames[(int)dayOfWeek]; Debug.Assert(dayAbbrev.Length == 3); string monthAbbrev = InvariantAbbreviatedMonthNames[month - 1]; Debug.Assert(monthAbbrev.Length == 3); destination[0] = dayAbbrev[0]; destination[1] = dayAbbrev[1]; destination[2] = dayAbbrev[2]; destination[3] = ','; destination[4] = ' '; WriteTwoDecimalDigits((uint)day, destination, 5); destination[7] = ' '; destination[8] = monthAbbrev[0]; destination[9] = monthAbbrev[1]; destination[10] = monthAbbrev[2]; destination[11] = ' '; WriteFourDecimalDigits((uint)year, destination, 12); return true; } // Roundtrippable format. One of // 012345678901234567890123456789012 // --------------------------------- // 2017-06-12T05:30:45.7680000-07:00 // 2017-06-12T05:30:45.7680000Z (Z is short for "+00:00" but also distinguishes DateTimeKind.Utc from DateTimeKind.Local) // 2017-06-12T05:30:45.7680000 (interpreted as local time wrt to current time zone) private static bool TryFormatO(DateTime dateTime, TimeSpan offset, Span<char> destination, out int charsWritten) { const int MinimumBytesNeeded = 27; int charsRequired = MinimumBytesNeeded; DateTimeKind kind = DateTimeKind.Local; if (offset.Ticks == NullOffset) { kind = dateTime.Kind; if (kind == DateTimeKind.Local) { offset = TimeZoneInfo.Local.GetUtcOffset(dateTime); charsRequired += 6; } else if (kind == DateTimeKind.Utc) { charsRequired++; } } else { charsRequired += 6; } if (destination.Length < charsRequired) { charsWritten = 0; return false; } charsWritten = charsRequired; // Hoist most of the bounds checks on destination. { _ = destination[MinimumBytesNeeded - 1]; } dateTime.GetDate(out int year, out int month, out int day); dateTime.GetTimePrecise(out int hour, out int minute, out int second, out int tick); WriteFourDecimalDigits((uint)year, destination, 0); destination[4] = '-'; WriteTwoDecimalDigits((uint)month, destination, 5); destination[7] = '-'; WriteTwoDecimalDigits((uint)day, destination, 8); destination[10] = 'T'; WriteTwoDecimalDigits((uint)hour, destination, 11); destination[13] = ':'; WriteTwoDecimalDigits((uint)minute, destination, 14); destination[16] = ':'; WriteTwoDecimalDigits((uint)second, destination, 17); destination[19] = '.'; WriteDigits((uint)tick, destination.Slice(20, 7)); if (kind == DateTimeKind.Local) { int offsetTotalMinutes = (int)(offset.Ticks / TimeSpan.TicksPerMinute); char sign; if (offsetTotalMinutes < 0) { sign = '-'; offsetTotalMinutes = -offsetTotalMinutes; } else { sign = '+'; } int offsetHours = Math.DivRem(offsetTotalMinutes, 60, out int offsetMinutes); // Writing the value backward allows the JIT to optimize by // performing a single bounds check against buffer. WriteTwoDecimalDigits((uint)offsetMinutes, destination, 31); destination[30] = ':'; WriteTwoDecimalDigits((uint)offsetHours, destination, 28); destination[27] = sign; } else if (kind == DateTimeKind.Utc) { destination[27] = 'Z'; } return true; } // Rfc1123 // 01234567890123456789012345678 // ----------------------------- // Tue, 03 Jan 2017 08:08:05 GMT private static bool TryFormatR(DateTime dateTime, TimeSpan offset, Span<char> destination, out int charsWritten) { if (destination.Length <= 28) { charsWritten = 0; return false; } if (offset.Ticks != NullOffset) { // Convert to UTC invariants. dateTime -= offset; } dateTime.GetDate(out int year, out int month, out int day); dateTime.GetTime(out int hour, out int minute, out int second); string dayAbbrev = InvariantAbbreviatedDayNames[(int)dateTime.DayOfWeek]; Debug.Assert(dayAbbrev.Length == 3); string monthAbbrev = InvariantAbbreviatedMonthNames[month - 1]; Debug.Assert(monthAbbrev.Length == 3); destination[0] = dayAbbrev[0]; destination[1] = dayAbbrev[1]; destination[2] = dayAbbrev[2]; destination[3] = ','; destination[4] = ' '; WriteTwoDecimalDigits((uint)day, destination, 5); destination[7] = ' '; destination[8] = monthAbbrev[0]; destination[9] = monthAbbrev[1]; destination[10] = monthAbbrev[2]; destination[11] = ' '; WriteFourDecimalDigits((uint)year, destination, 12); destination[16] = ' '; WriteTwoDecimalDigits((uint)hour, destination, 17); destination[19] = ':'; WriteTwoDecimalDigits((uint)minute, destination, 20); destination[22] = ':'; WriteTwoDecimalDigits((uint)second, destination, 23); destination[25] = ' '; destination[26] = 'G'; destination[27] = 'M'; destination[28] = 'T'; charsWritten = 29; return true; } /// <summary> /// Writes a value [ 00 .. 99 ] to the buffer starting at the specified offset. /// This method performs best when the starting index is a constant literal. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteTwoDecimalDigits(uint value, Span<char> destination, int offset) { Debug.Assert(value <= 99); uint temp = '0' + value; value /= 10; destination[offset + 1] = (char)(temp - (value * 10)); destination[offset] = (char)('0' + value); } /// <summary> /// Writes a value [ 0000 .. 9999 ] to the buffer starting at the specified offset. /// This method performs best when the starting index is a constant literal. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteFourDecimalDigits(uint value, Span<char> buffer, int startingIndex = 0) { Debug.Assert(value <= 9999); uint temp = '0' + value; value /= 10; buffer[startingIndex + 3] = (char)(temp - (value * 10)); temp = '0' + value; value /= 10; buffer[startingIndex + 2] = (char)(temp - (value * 10)); temp = '0' + value; value /= 10; buffer[startingIndex + 1] = (char)(temp - (value * 10)); buffer[startingIndex] = (char)('0' + value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteDigits(ulong value, Span<char> buffer) { // We can mutate the 'value' parameter since it's a copy-by-value local. // It'll be used to represent the value left over after each division by 10. for (int i = buffer.Length - 1; i >= 1; i--) { ulong temp = '0' + value; value /= 10; buffer[i] = (char)(temp - (value * 10)); } Debug.Assert(value < 10); buffer[0] = (char)('0' + value); } internal static string[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi) { Debug.Assert(dtfi != null); string[] allFormats; string[] results; switch (format) { case 'd': case 'D': case 'f': case 'F': case 'g': case 'G': case 'm': case 'M': case 't': case 'T': case 'y': case 'Y': allFormats = dtfi.GetAllDateTimePatterns(format); results = new string[allFormats.Length]; for (int i = 0; i < allFormats.Length; i++) { results[i] = Format(dateTime, allFormats[i], dtfi); } break; case 'U': DateTime universalTime = dateTime.ToUniversalTime(); allFormats = dtfi.GetAllDateTimePatterns(format); results = new string[allFormats.Length]; for (int i = 0; i < allFormats.Length; i++) { results[i] = Format(universalTime, allFormats[i], dtfi); } break; // // The following ones are special cases because these patterns are read-only in // DateTimeFormatInfo. // case 'r': case 'R': case 'o': case 'O': case 's': case 'u': results = new string[] { Format(dateTime, char.ToString(format), dtfi) }; break; default: throw new FormatException(SR.Format_InvalidString); } return results; } internal static string[] GetAllDateTimes(DateTime dateTime, DateTimeFormatInfo dtfi) { List<string> results = new List<string>(DEFAULT_ALL_DATETIMES_SIZE); for (int i = 0; i < allStandardFormats.Length; i++) { string[] strings = GetAllDateTimes(dateTime, allStandardFormats[i], dtfi); for (int j = 0; j < strings.Length; j++) { results.Add(strings[j]); } } return results.ToArray(); } } }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/And.Vector128.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.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void And_Vector128_Int32() { var test = new SimpleBinaryOpTest__And_Vector128_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__And_Vector128_Int32 { 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 != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<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__And_Vector128_Int32 testClass) { var result = AdvSimd.And(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__And_Vector128_Int32 testClass) { fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.And( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.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__And_Vector128_Int32() { 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__And_Vector128_Int32() { 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 => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.And( 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 = AdvSimd.And( AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((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(AdvSimd).GetMethod(nameof(AdvSimd.And), 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(AdvSimd).GetMethod(nameof(AdvSimd.And), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((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 = AdvSimd.And( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.And( AdvSimd.LoadVector128((Int32*)(pClsVar1)), AdvSimd.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 = AdvSimd.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__And_Vector128_Int32(); var result = AdvSimd.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__And_Vector128_Int32(); fixed (Vector128<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.And( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.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 = AdvSimd.And(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.And( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.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 = AdvSimd.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.And( AdvSimd.LoadVector128((Int32*)(&test._fld1)), AdvSimd.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; for (var i = 0; i < RetElementCount; i++) { if (Helpers.And(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.And)}<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.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void And_Vector128_Int32() { var test = new SimpleBinaryOpTest__And_Vector128_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__And_Vector128_Int32 { 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 != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<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__And_Vector128_Int32 testClass) { var result = AdvSimd.And(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__And_Vector128_Int32 testClass) { fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.And( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.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__And_Vector128_Int32() { 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__And_Vector128_Int32() { 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 => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.And( 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 = AdvSimd.And( AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((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(AdvSimd).GetMethod(nameof(AdvSimd.And), 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(AdvSimd).GetMethod(nameof(AdvSimd.And), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((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 = AdvSimd.And( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.And( AdvSimd.LoadVector128((Int32*)(pClsVar1)), AdvSimd.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 = AdvSimd.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__And_Vector128_Int32(); var result = AdvSimd.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__And_Vector128_Int32(); fixed (Vector128<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.And( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.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 = AdvSimd.And(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.And( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.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 = AdvSimd.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.And( AdvSimd.LoadVector128((Int32*)(&test._fld1)), AdvSimd.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; for (var i = 0; i < RetElementCount; i++) { if (Helpers.And(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.And)}<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,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.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.Runtime; using System.Runtime.Serialization; using System.Reflection; using System.Xml; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Runtime.Serialization.Json { internal class JsonDataContract { private readonly JsonDataContractCriticalHelper _helper; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] protected JsonDataContract(DataContract traditionalDataContract) { _helper = new JsonDataContractCriticalHelper(traditionalDataContract); } protected JsonDataContract(JsonDataContractCriticalHelper helper) { _helper = helper; } internal virtual string? TypeName => null; protected JsonDataContractCriticalHelper Helper => _helper; protected DataContract TraditionalDataContract => _helper.TraditionalDataContract; private Dictionary<XmlQualifiedName, DataContract>? KnownDataContracts => _helper.KnownDataContracts; public static JsonReadWriteDelegates? GetGeneratedReadWriteDelegates(DataContract c) { // this method used to be rewritten by an IL transform // with the restructuring for multi-file, this is no longer true - instead // this has become a normal method JsonReadWriteDelegates? result; return JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(c, out result) ? result : null; } internal static JsonReadWriteDelegates GetReadWriteDelegatesFromGeneratedAssembly(DataContract c) { JsonReadWriteDelegates? result = GetGeneratedReadWriteDelegates(c); if (result == null) { throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, c.UnderlyingType)); } else { return result; } } internal static JsonReadWriteDelegates? TryGetReadWriteDelegatesFromGeneratedAssembly(DataContract c) { JsonReadWriteDelegates? result = GetGeneratedReadWriteDelegates(c); return result; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract) { return JsonDataContractCriticalHelper.GetJsonDataContract(traditionalDataContract); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public object? ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { PushKnownDataContracts(context); object? deserializedObject = ReadJsonValueCore(jsonReader, context); PopKnownDataContracts(context); return deserializedObject; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public virtual object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { return TraditionalDataContract.ReadXmlValue(jsonReader, context); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle) { PushKnownDataContracts(context); WriteJsonValueCore(jsonWriter, obj, context, declaredTypeHandle); PopKnownDataContracts(context); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle) { TraditionalDataContract.WriteXmlValue(jsonWriter, obj, context); } protected static object HandleReadValue(object obj, XmlObjectSerializerReadContext context) { context.AddNewObject(obj); return obj; } protected static bool TryReadNullAtTopLevel(XmlReaderDelegator reader) { if (reader.MoveToAttribute(JsonGlobals.typeString) && (reader.Value == JsonGlobals.nullString)) { reader.Skip(); reader.MoveToElement(); return true; } reader.MoveToElement(); return false; } protected void PopKnownDataContracts(XmlObjectSerializerContext? context) { if (KnownDataContracts != null) { Debug.Assert(context != null); context.scopedKnownTypes.Pop(); } } protected void PushKnownDataContracts(XmlObjectSerializerContext? context) { if (KnownDataContracts != null) { Debug.Assert(context != null); context.scopedKnownTypes.Push(KnownDataContracts); } } internal class JsonDataContractCriticalHelper { private static readonly object s_cacheLock = new object(); private static readonly object s_createDataContractLock = new object(); private static JsonDataContract[] s_dataContractCache = new JsonDataContract[32]; private static int s_dataContractID; private static readonly TypeHandleRef s_typeHandleRef = new TypeHandleRef(); private static readonly Dictionary<TypeHandleRef, IntRef> s_typeToIDCache = new Dictionary<TypeHandleRef, IntRef>(new TypeHandleRefEqualityComparer()); private Dictionary<XmlQualifiedName, DataContract>? _knownDataContracts; private readonly DataContract _traditionalDataContract; private readonly string _typeName; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal JsonDataContractCriticalHelper(DataContract traditionalDataContract) { _traditionalDataContract = traditionalDataContract; AddCollectionItemContractsToKnownDataContracts(); _typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value)); } internal Dictionary<XmlQualifiedName, DataContract>? KnownDataContracts => _knownDataContracts; internal DataContract TraditionalDataContract => _traditionalDataContract; internal virtual string TypeName => _typeName; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract) { int id = JsonDataContractCriticalHelper.GetId(traditionalDataContract.UnderlyingType.TypeHandle); JsonDataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { dataContract = CreateJsonDataContract(id, traditionalDataContract); s_dataContractCache[id] = dataContract; } return dataContract; } internal static int GetId(RuntimeTypeHandle typeHandle) { lock (s_cacheLock) { IntRef? id; s_typeHandleRef.Value = typeHandle; if (!s_typeToIDCache.TryGetValue(s_typeHandleRef, out id)) { int value = s_dataContractID++; if (value >= s_dataContractCache.Length) { int newSize = (value < int.MaxValue / 2) ? value * 2 : int.MaxValue; if (newSize <= value) { Fx.Assert("DataContract cache overflow"); throw new SerializationException(SR.DataContractCacheOverflow); } Array.Resize<JsonDataContract>(ref s_dataContractCache, newSize); } id = new IntRef(value); try { s_typeToIDCache.Add(new TypeHandleRef(typeHandle), id); } catch (Exception ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } return id.Value; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static JsonDataContract CreateJsonDataContract(int id, DataContract traditionalDataContract) { lock (s_createDataContractLock) { JsonDataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { Type traditionalDataContractType = traditionalDataContract.GetType(); if (traditionalDataContractType == typeof(ObjectDataContract)) { dataContract = new JsonObjectDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(StringDataContract)) { dataContract = new JsonStringDataContract((StringDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(UriDataContract)) { dataContract = new JsonUriDataContract((UriDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(QNameDataContract)) { dataContract = new JsonQNameDataContract((QNameDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(ByteArrayDataContract)) { dataContract = new JsonByteArrayDataContract((ByteArrayDataContract)traditionalDataContract); } else if (traditionalDataContract.IsPrimitive || traditionalDataContract.UnderlyingType == Globals.TypeOfXmlQualifiedName) { dataContract = new JsonDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(ClassDataContract)) { dataContract = new JsonClassDataContract((ClassDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(EnumDataContract)) { dataContract = new JsonEnumDataContract((EnumDataContract)traditionalDataContract); } else if ((traditionalDataContractType == typeof(GenericParameterDataContract)) || (traditionalDataContractType == typeof(SpecialTypeDataContract))) { dataContract = new JsonDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(CollectionDataContract)) { dataContract = new JsonCollectionDataContract((CollectionDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(XmlDataContract)) { dataContract = new JsonXmlDataContract((XmlDataContract)traditionalDataContract); } else { throw new ArgumentException(SR.Format(SR.JsonTypeNotSupportedByDataContractJsonSerializer, traditionalDataContract.UnderlyingType), nameof(traditionalDataContract)); } } return dataContract; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private void AddCollectionItemContractsToKnownDataContracts() { if (_traditionalDataContract.KnownDataContracts != null) { foreach (KeyValuePair<XmlQualifiedName, DataContract> knownDataContract in _traditionalDataContract.KnownDataContracts) { CollectionDataContract? collectionDataContract = knownDataContract.Value as CollectionDataContract; while (collectionDataContract != null) { DataContract itemContract = collectionDataContract.ItemContract; if (_knownDataContracts == null) { _knownDataContracts = new Dictionary<XmlQualifiedName, DataContract>(); } _knownDataContracts.TryAdd(itemContract.StableName, itemContract); if (collectionDataContract.ItemType.IsGenericType && collectionDataContract.ItemType.GetGenericTypeDefinition() == typeof(KeyValue<,>)) { DataContract itemDataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GenericTypeArguments)); _knownDataContracts.TryAdd(itemDataContract.StableName, itemDataContract); } if (!(itemContract is CollectionDataContract)) { break; } collectionDataContract = itemContract as CollectionDataContract; } } } } } } internal sealed class JsonReadWriteDelegates { // this is the global dictionary for JSON delegates introduced for multi-file private static readonly Dictionary<DataContract, JsonReadWriteDelegates> s_jsonDelegates = new Dictionary<DataContract, JsonReadWriteDelegates>(); public static Dictionary<DataContract, JsonReadWriteDelegates> GetJsonDelegates() { return s_jsonDelegates; } public JsonFormatClassWriterDelegate? ClassWriterDelegate { get; set; } public JsonFormatClassReaderDelegate? ClassReaderDelegate { get; set; } public JsonFormatCollectionWriterDelegate? CollectionWriterDelegate { get; set; } public JsonFormatCollectionReaderDelegate? CollectionReaderDelegate { get; set; } public JsonFormatGetOnlyCollectionReaderDelegate? GetOnlyCollectionReaderDelegate { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Runtime; using System.Runtime.Serialization; using System.Reflection; using System.Xml; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Runtime.Serialization.Json { internal class JsonDataContract { private readonly JsonDataContractCriticalHelper _helper; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] protected JsonDataContract(DataContract traditionalDataContract) { _helper = new JsonDataContractCriticalHelper(traditionalDataContract); } protected JsonDataContract(JsonDataContractCriticalHelper helper) { _helper = helper; } internal virtual string? TypeName => null; protected JsonDataContractCriticalHelper Helper => _helper; protected DataContract TraditionalDataContract => _helper.TraditionalDataContract; private Dictionary<XmlQualifiedName, DataContract>? KnownDataContracts => _helper.KnownDataContracts; public static JsonReadWriteDelegates? GetGeneratedReadWriteDelegates(DataContract c) { // this method used to be rewritten by an IL transform // with the restructuring for multi-file, this is no longer true - instead // this has become a normal method JsonReadWriteDelegates? result; return JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(c, out result) ? result : null; } internal static JsonReadWriteDelegates GetReadWriteDelegatesFromGeneratedAssembly(DataContract c) { JsonReadWriteDelegates? result = GetGeneratedReadWriteDelegates(c); if (result == null) { throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, c.UnderlyingType)); } else { return result; } } internal static JsonReadWriteDelegates? TryGetReadWriteDelegatesFromGeneratedAssembly(DataContract c) { JsonReadWriteDelegates? result = GetGeneratedReadWriteDelegates(c); return result; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract) { return JsonDataContractCriticalHelper.GetJsonDataContract(traditionalDataContract); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public object? ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { PushKnownDataContracts(context); object? deserializedObject = ReadJsonValueCore(jsonReader, context); PopKnownDataContracts(context); return deserializedObject; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public virtual object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { return TraditionalDataContract.ReadXmlValue(jsonReader, context); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle) { PushKnownDataContracts(context); WriteJsonValueCore(jsonWriter, obj, context, declaredTypeHandle); PopKnownDataContracts(context); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle) { TraditionalDataContract.WriteXmlValue(jsonWriter, obj, context); } protected static object HandleReadValue(object obj, XmlObjectSerializerReadContext context) { context.AddNewObject(obj); return obj; } protected static bool TryReadNullAtTopLevel(XmlReaderDelegator reader) { if (reader.MoveToAttribute(JsonGlobals.typeString) && (reader.Value == JsonGlobals.nullString)) { reader.Skip(); reader.MoveToElement(); return true; } reader.MoveToElement(); return false; } protected void PopKnownDataContracts(XmlObjectSerializerContext? context) { if (KnownDataContracts != null) { Debug.Assert(context != null); context.scopedKnownTypes.Pop(); } } protected void PushKnownDataContracts(XmlObjectSerializerContext? context) { if (KnownDataContracts != null) { Debug.Assert(context != null); context.scopedKnownTypes.Push(KnownDataContracts); } } internal class JsonDataContractCriticalHelper { private static readonly object s_cacheLock = new object(); private static readonly object s_createDataContractLock = new object(); private static JsonDataContract[] s_dataContractCache = new JsonDataContract[32]; private static int s_dataContractID; private static readonly TypeHandleRef s_typeHandleRef = new TypeHandleRef(); private static readonly Dictionary<TypeHandleRef, IntRef> s_typeToIDCache = new Dictionary<TypeHandleRef, IntRef>(new TypeHandleRefEqualityComparer()); private Dictionary<XmlQualifiedName, DataContract>? _knownDataContracts; private readonly DataContract _traditionalDataContract; private readonly string _typeName; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal JsonDataContractCriticalHelper(DataContract traditionalDataContract) { _traditionalDataContract = traditionalDataContract; AddCollectionItemContractsToKnownDataContracts(); _typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value)); } internal Dictionary<XmlQualifiedName, DataContract>? KnownDataContracts => _knownDataContracts; internal DataContract TraditionalDataContract => _traditionalDataContract; internal virtual string TypeName => _typeName; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract) { int id = JsonDataContractCriticalHelper.GetId(traditionalDataContract.UnderlyingType.TypeHandle); JsonDataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { dataContract = CreateJsonDataContract(id, traditionalDataContract); s_dataContractCache[id] = dataContract; } return dataContract; } internal static int GetId(RuntimeTypeHandle typeHandle) { lock (s_cacheLock) { IntRef? id; s_typeHandleRef.Value = typeHandle; if (!s_typeToIDCache.TryGetValue(s_typeHandleRef, out id)) { int value = s_dataContractID++; if (value >= s_dataContractCache.Length) { int newSize = (value < int.MaxValue / 2) ? value * 2 : int.MaxValue; if (newSize <= value) { Fx.Assert("DataContract cache overflow"); throw new SerializationException(SR.DataContractCacheOverflow); } Array.Resize<JsonDataContract>(ref s_dataContractCache, newSize); } id = new IntRef(value); try { s_typeToIDCache.Add(new TypeHandleRef(typeHandle), id); } catch (Exception ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } return id.Value; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static JsonDataContract CreateJsonDataContract(int id, DataContract traditionalDataContract) { lock (s_createDataContractLock) { JsonDataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { Type traditionalDataContractType = traditionalDataContract.GetType(); if (traditionalDataContractType == typeof(ObjectDataContract)) { dataContract = new JsonObjectDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(StringDataContract)) { dataContract = new JsonStringDataContract((StringDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(UriDataContract)) { dataContract = new JsonUriDataContract((UriDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(QNameDataContract)) { dataContract = new JsonQNameDataContract((QNameDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(ByteArrayDataContract)) { dataContract = new JsonByteArrayDataContract((ByteArrayDataContract)traditionalDataContract); } else if (traditionalDataContract.IsPrimitive || traditionalDataContract.UnderlyingType == Globals.TypeOfXmlQualifiedName) { dataContract = new JsonDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(ClassDataContract)) { dataContract = new JsonClassDataContract((ClassDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(EnumDataContract)) { dataContract = new JsonEnumDataContract((EnumDataContract)traditionalDataContract); } else if ((traditionalDataContractType == typeof(GenericParameterDataContract)) || (traditionalDataContractType == typeof(SpecialTypeDataContract))) { dataContract = new JsonDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(CollectionDataContract)) { dataContract = new JsonCollectionDataContract((CollectionDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(XmlDataContract)) { dataContract = new JsonXmlDataContract((XmlDataContract)traditionalDataContract); } else { throw new ArgumentException(SR.Format(SR.JsonTypeNotSupportedByDataContractJsonSerializer, traditionalDataContract.UnderlyingType), nameof(traditionalDataContract)); } } return dataContract; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private void AddCollectionItemContractsToKnownDataContracts() { if (_traditionalDataContract.KnownDataContracts != null) { foreach (KeyValuePair<XmlQualifiedName, DataContract> knownDataContract in _traditionalDataContract.KnownDataContracts) { CollectionDataContract? collectionDataContract = knownDataContract.Value as CollectionDataContract; while (collectionDataContract != null) { DataContract itemContract = collectionDataContract.ItemContract; if (_knownDataContracts == null) { _knownDataContracts = new Dictionary<XmlQualifiedName, DataContract>(); } _knownDataContracts.TryAdd(itemContract.StableName, itemContract); if (collectionDataContract.ItemType.IsGenericType && collectionDataContract.ItemType.GetGenericTypeDefinition() == typeof(KeyValue<,>)) { DataContract itemDataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GenericTypeArguments)); _knownDataContracts.TryAdd(itemDataContract.StableName, itemDataContract); } if (!(itemContract is CollectionDataContract)) { break; } collectionDataContract = itemContract as CollectionDataContract; } } } } } } internal sealed class JsonReadWriteDelegates { // this is the global dictionary for JSON delegates introduced for multi-file private static readonly Dictionary<DataContract, JsonReadWriteDelegates> s_jsonDelegates = new Dictionary<DataContract, JsonReadWriteDelegates>(); public static Dictionary<DataContract, JsonReadWriteDelegates> GetJsonDelegates() { return s_jsonDelegates; } public JsonFormatClassWriterDelegate? ClassWriterDelegate { get; set; } public JsonFormatClassReaderDelegate? ClassReaderDelegate { get; set; } public JsonFormatCollectionWriterDelegate? CollectionWriterDelegate { get; set; } public JsonFormatCollectionReaderDelegate? CollectionReaderDelegate { get; set; } public JsonFormatGetOnlyCollectionReaderDelegate? GetOnlyCollectionReaderDelegate { get; set; } } }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/tests/JIT/HardwareIntrinsics/General/Vector128/Sqrt.Single.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 SqrtSingle() { var test = new VectorUnaryOpTest__SqrtSingle(); // 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 VectorUnaryOpTest__SqrtSingle { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__SqrtSingle testClass) { var result = Vector128.Sqrt(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__SqrtSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public VectorUnaryOpTest__SqrtSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.Sqrt( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.Sqrt), new Type[] { typeof(Vector128<Single>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.Sqrt), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Single)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.Sqrt( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var result = Vector128.Sqrt(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__SqrtSingle(); var result = Vector128.Sqrt(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.Sqrt(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.Sqrt(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (float)(MathF.Sqrt(firstOp[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (float)(MathF.Sqrt(firstOp[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.Sqrt)}<Single>(Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 SqrtSingle() { var test = new VectorUnaryOpTest__SqrtSingle(); // 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 VectorUnaryOpTest__SqrtSingle { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__SqrtSingle testClass) { var result = Vector128.Sqrt(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__SqrtSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public VectorUnaryOpTest__SqrtSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.Sqrt( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.Sqrt), new Type[] { typeof(Vector128<Single>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.Sqrt), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Single)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.Sqrt( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var result = Vector128.Sqrt(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__SqrtSingle(); var result = Vector128.Sqrt(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.Sqrt(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.Sqrt(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (float)(MathF.Sqrt(firstOp[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (float)(MathF.Sqrt(firstOp[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.Sqrt)}<Single>(Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/tests/JIT/jit64/valuetypes/nullable/castclass/castclass/castclass010.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // <Area> Nullable - CastClass </Area> // <Title> Nullable type with castclass expr </Title> // <Description> // checking type of ulong using cast expr // </Description> // <RelatedBugs> </RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQ(object o) { return Helper.Compare((ulong)(ValueType)o, Helper.Create(default(ulong))); } private static bool BoxUnboxToQ(object o) { return Helper.Compare((ulong?)(ValueType)o, Helper.Create(default(ulong))); } private static int Main() { ulong? s = Helper.Create(default(ulong)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // <Area> Nullable - CastClass </Area> // <Title> Nullable type with castclass expr </Title> // <Description> // checking type of ulong using cast expr // </Description> // <RelatedBugs> </RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQ(object o) { return Helper.Compare((ulong)(ValueType)o, Helper.Create(default(ulong))); } private static bool BoxUnboxToQ(object o) { return Helper.Compare((ulong?)(ValueType)o, Helper.Create(default(ulong))); } private static int Main() { ulong? s = Helper.Create(default(ulong)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/Common/src/System/Net/Http/aspnetcore/Http3/Frames/Http3ErrorCode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Net.Http { internal enum Http3ErrorCode : long { /// <summary> /// H3_NO_ERROR (0x100): /// No error. This is used when the connection or stream needs to be closed, but there is no error to signal. /// </summary> NoError = 0x100, /// <summary> /// H3_GENERAL_PROTOCOL_ERROR (0x101): /// Peer violated protocol requirements in a way which doesn't match a more specific error code, /// or endpoint declines to use the more specific error code. /// </summary> ProtocolError = 0x101, /// <summary> /// H3_INTERNAL_ERROR (0x102): /// An internal error has occurred in the HTTP stack. /// </summary> InternalError = 0x102, /// <summary> /// H3_STREAM_CREATION_ERROR (0x103): /// The endpoint detected that its peer created a stream that it will not accept. /// </summary> StreamCreationError = 0x103, /// <summary> /// H3_CLOSED_CRITICAL_STREAM (0x104): /// A stream required by the connection was closed or reset. /// </summary> ClosedCriticalStream = 0x104, /// <summary> /// H3_FRAME_UNEXPECTED (0x105): /// A frame was received which was not permitted in the current state. /// </summary> UnexpectedFrame = 0x105, /// <summary> /// H3_FRAME_ERROR (0x106): /// A frame that fails to satisfy layout requirements or with an invalid size was received. /// </summary> FrameError = 0x106, /// <summary> /// H3_EXCESSIVE_LOAD (0x107): /// The endpoint detected that its peer is exhibiting a behavior that might be generating excessive load. /// </summary> ExcessiveLoad = 0x107, /// <summary> /// H3_ID_ERROR (0x109): /// A Stream ID, Push ID, or Placeholder ID was used incorrectly, such as exceeding a limit, reducing a limit, or being reused. /// </summary> IdError = 0x108, /// <summary> /// H3_SETTINGS_ERROR (0x109): /// An endpoint detected an error in the payload of a SETTINGS frame. /// </summary> SettingsError = 0x109, /// <summary> /// H3_MISSING_SETTINGS (0x10A): /// No SETTINGS frame was received at the beginning of the control stream. /// </summary> MissingSettings = 0x10a, /// <summary> /// H3_REQUEST_REJECTED (0x10B): /// A server rejected a request without performing any application processing. /// </summary> RequestRejected = 0x10b, /// <summary> /// H3_REQUEST_CANCELLED (0x10C): /// The request or its response (including pushed response) is cancelled. /// </summary> RequestCancelled = 0x10c, /// <summary> /// H3_REQUEST_INCOMPLETE (0x10D): /// The client's stream terminated without containing a fully-formed request. /// </summary> RequestIncomplete = 0x10d, /// <summary> /// H3_MESSAGE_ERROR (0x10E): /// An HTTP message was malformed and cannot be processed. /// </summary> MessageError = 0x10e, /// <summary> /// H3_CONNECT_ERROR (0x10F): /// The connection established in response to a CONNECT request was reset or abnormally closed. /// </summary> ConnectError = 0x10f, /// <summary> /// H3_VERSION_FALLBACK (0x110): /// The requested operation cannot be served over HTTP/3. The peer should retry over HTTP/1.1. /// </summary> VersionFallback = 0x110, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Net.Http { internal enum Http3ErrorCode : long { /// <summary> /// H3_NO_ERROR (0x100): /// No error. This is used when the connection or stream needs to be closed, but there is no error to signal. /// </summary> NoError = 0x100, /// <summary> /// H3_GENERAL_PROTOCOL_ERROR (0x101): /// Peer violated protocol requirements in a way which doesn't match a more specific error code, /// or endpoint declines to use the more specific error code. /// </summary> ProtocolError = 0x101, /// <summary> /// H3_INTERNAL_ERROR (0x102): /// An internal error has occurred in the HTTP stack. /// </summary> InternalError = 0x102, /// <summary> /// H3_STREAM_CREATION_ERROR (0x103): /// The endpoint detected that its peer created a stream that it will not accept. /// </summary> StreamCreationError = 0x103, /// <summary> /// H3_CLOSED_CRITICAL_STREAM (0x104): /// A stream required by the connection was closed or reset. /// </summary> ClosedCriticalStream = 0x104, /// <summary> /// H3_FRAME_UNEXPECTED (0x105): /// A frame was received which was not permitted in the current state. /// </summary> UnexpectedFrame = 0x105, /// <summary> /// H3_FRAME_ERROR (0x106): /// A frame that fails to satisfy layout requirements or with an invalid size was received. /// </summary> FrameError = 0x106, /// <summary> /// H3_EXCESSIVE_LOAD (0x107): /// The endpoint detected that its peer is exhibiting a behavior that might be generating excessive load. /// </summary> ExcessiveLoad = 0x107, /// <summary> /// H3_ID_ERROR (0x109): /// A Stream ID, Push ID, or Placeholder ID was used incorrectly, such as exceeding a limit, reducing a limit, or being reused. /// </summary> IdError = 0x108, /// <summary> /// H3_SETTINGS_ERROR (0x109): /// An endpoint detected an error in the payload of a SETTINGS frame. /// </summary> SettingsError = 0x109, /// <summary> /// H3_MISSING_SETTINGS (0x10A): /// No SETTINGS frame was received at the beginning of the control stream. /// </summary> MissingSettings = 0x10a, /// <summary> /// H3_REQUEST_REJECTED (0x10B): /// A server rejected a request without performing any application processing. /// </summary> RequestRejected = 0x10b, /// <summary> /// H3_REQUEST_CANCELLED (0x10C): /// The request or its response (including pushed response) is cancelled. /// </summary> RequestCancelled = 0x10c, /// <summary> /// H3_REQUEST_INCOMPLETE (0x10D): /// The client's stream terminated without containing a fully-formed request. /// </summary> RequestIncomplete = 0x10d, /// <summary> /// H3_MESSAGE_ERROR (0x10E): /// An HTTP message was malformed and cannot be processed. /// </summary> MessageError = 0x10e, /// <summary> /// H3_CONNECT_ERROR (0x10F): /// The connection established in response to a CONNECT request was reset or abnormally closed. /// </summary> ConnectError = 0x10f, /// <summary> /// H3_VERSION_FALLBACK (0x110): /// The requested operation cannot be served over HTTP/3. The peer should retry over HTTP/1.1. /// </summary> VersionFallback = 0x110, } }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/PingCompletedEventArgs.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; namespace System.Net.NetworkInformation { public delegate void PingCompletedEventHandler(object sender, PingCompletedEventArgs e); public class PingCompletedEventArgs : AsyncCompletedEventArgs { internal PingCompletedEventArgs(PingReply? reply, Exception? error, bool cancelled, object? userToken) : base(error, cancelled, userToken) { Reply = reply; } public PingReply? Reply { 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.ComponentModel; namespace System.Net.NetworkInformation { public delegate void PingCompletedEventHandler(object sender, PingCompletedEventArgs e); public class PingCompletedEventArgs : AsyncCompletedEventArgs { internal PingCompletedEventArgs(PingReply? reply, Exception? error, bool cancelled, object? userToken) : base(error, cancelled, userToken) { Reply = reply; } public PingReply? Reply { get; } } }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Net.WebSockets.Client/tests/ClientWebSocketOptionsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net.Http; using System.Net.Security; using System.Net.Test.Common; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.WebSockets.Client.Tests { public class ClientWebSocketOptionsTests : ClientWebSocketTestBase { public ClientWebSocketOptionsTests(ITestOutputHelper output) : base(output) { } [ConditionalFact(nameof(WebSocketsSupported))] [SkipOnPlatform(TestPlatforms.Browser, "Credentials not supported on browser")] public static void UseDefaultCredentials_Roundtrips() { var cws = new ClientWebSocket(); Assert.False(cws.Options.UseDefaultCredentials); cws.Options.UseDefaultCredentials = true; Assert.True(cws.Options.UseDefaultCredentials); cws.Options.UseDefaultCredentials = false; Assert.False(cws.Options.UseDefaultCredentials); } [ConditionalFact(nameof(WebSocketsSupported))] [SkipOnPlatform(TestPlatforms.Browser, "Proxy not supported on browser")] public static void Proxy_Roundtrips() { var cws = new ClientWebSocket(); Assert.NotNull(cws.Options.Proxy); Assert.Same(cws.Options.Proxy, cws.Options.Proxy); IWebProxy p = new WebProxy(); cws.Options.Proxy = p; Assert.Same(p, cws.Options.Proxy); cws.Options.Proxy = null; Assert.Null(cws.Options.Proxy); } [OuterLoop] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] [ActiveIssue("https://github.com/dotnet/runtime/issues/43751")] public async Task Proxy_SetNull_ConnectsSuccessfully(Uri server) { for (int i = 0; i < 3; i++) // Connect and disconnect multiple times to exercise shared handler on netcoreapp { var ws = await WebSocketHelper.Retry(_output, async () => { var cws = new ClientWebSocket(); cws.Options.Proxy = null; await cws.ConnectAsync(server, default); return cws; }); await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, default); ws.Dispose(); } } [ActiveIssue("https://github.com/dotnet/runtime/issues/25440")] [OuterLoop] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task Proxy_ConnectThruProxy_Success(Uri server) { string proxyServerUri = System.Net.Test.Common.Configuration.WebSockets.ProxyServerUri; if (string.IsNullOrEmpty(proxyServerUri)) { _output.WriteLine("Skipping test...no proxy server defined."); return; } _output.WriteLine($"ProxyServer: {proxyServerUri}"); IWebProxy proxy = new WebProxy(new Uri(proxyServerUri)); using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket( server, TimeOutMilliseconds, _output, default(TimeSpan), proxy)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); Assert.Equal(WebSocketState.Open, cws.State); var closeStatus = WebSocketCloseStatus.NormalClosure; string closeDescription = "Normal Closure"; await cws.CloseAsync(closeStatus, closeDescription, cts.Token); // Verify a clean close frame handshake. Assert.Equal(WebSocketState.Closed, cws.State); Assert.Equal(closeStatus, cws.CloseStatus); Assert.Equal(closeDescription, cws.CloseStatusDescription); } } [ConditionalFact(nameof(WebSocketsSupported))] [SkipOnPlatform(TestPlatforms.Browser, "Buffer not supported on browser")] public static void SetBuffer_InvalidArgs_Throws() { // Recreate the minimum WebSocket buffer size values from the .NET Framework version of WebSocket, // and pick the correct name of the buffer used when throwing an ArgumentOutOfRangeException. int minSendBufferSize = 1; int minReceiveBufferSize = 1; string bufferName = "buffer"; var cws = new ClientWebSocket(); AssertExtensions.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => cws.Options.SetBuffer(0, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => cws.Options.SetBuffer(0, minSendBufferSize)); AssertExtensions.Throws<ArgumentOutOfRangeException>("sendBufferSize", () => cws.Options.SetBuffer(minReceiveBufferSize, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => cws.Options.SetBuffer(0, 0, new ArraySegment<byte>(new byte[1]))); AssertExtensions.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => cws.Options.SetBuffer(0, minSendBufferSize, new ArraySegment<byte>(new byte[1]))); AssertExtensions.Throws<ArgumentOutOfRangeException>("sendBufferSize", () => cws.Options.SetBuffer(minReceiveBufferSize, 0, new ArraySegment<byte>(new byte[1]))); AssertExtensions.Throws<ArgumentNullException>("buffer.Array", () => cws.Options.SetBuffer(minReceiveBufferSize, minSendBufferSize, default(ArraySegment<byte>))); AssertExtensions.Throws<ArgumentOutOfRangeException>(bufferName, () => cws.Options.SetBuffer(minReceiveBufferSize, minSendBufferSize, new ArraySegment<byte>(new byte[0]))); } [ConditionalFact(nameof(WebSocketsSupported))] [SkipOnPlatform(TestPlatforms.Browser, "KeepAlive not supported on browser")] public static void KeepAliveInterval_Roundtrips() { var cws = new ClientWebSocket(); Assert.True(cws.Options.KeepAliveInterval > TimeSpan.Zero); cws.Options.KeepAliveInterval = TimeSpan.Zero; Assert.Equal(TimeSpan.Zero, cws.Options.KeepAliveInterval); cws.Options.KeepAliveInterval = TimeSpan.MaxValue; Assert.Equal(TimeSpan.MaxValue, cws.Options.KeepAliveInterval); cws.Options.KeepAliveInterval = Timeout.InfiniteTimeSpan; Assert.Equal(Timeout.InfiniteTimeSpan, cws.Options.KeepAliveInterval); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => cws.Options.KeepAliveInterval = TimeSpan.MinValue); } [ConditionalFact(nameof(WebSocketsSupported))] [SkipOnPlatform(TestPlatforms.Browser, "Certificates not supported on browser")] public void RemoteCertificateValidationCallback_Roundtrips() { using (var cws = new ClientWebSocket()) { Assert.Null(cws.Options.RemoteCertificateValidationCallback); RemoteCertificateValidationCallback callback = delegate { return true; }; cws.Options.RemoteCertificateValidationCallback = callback; Assert.Same(callback, cws.Options.RemoteCertificateValidationCallback); cws.Options.RemoteCertificateValidationCallback = null; Assert.Null(cws.Options.RemoteCertificateValidationCallback); } } [OuterLoop("Connects to remote service")] [ConditionalTheory(nameof(WebSocketsSupported))] [InlineData(false)] [InlineData(true)] [SkipOnPlatform(TestPlatforms.Browser, "Certificates not supported on browser")] public async Task RemoteCertificateValidationCallback_PassedRemoteCertificateInfo(bool secure) { if (PlatformDetection.IsWindows7) { return; // see https://github.com/dotnet/runtime/issues/1491#issuecomment-376392057 for more details } bool callbackInvoked = false; await LoopbackServer.CreateClientAndServerAsync(async uri => { using (var cws = new ClientWebSocket()) using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { cws.Options.RemoteCertificateValidationCallback = (source, cert, chain, errors) => { Assert.NotNull(source); Assert.NotNull(cert); Assert.NotNull(chain); Assert.NotEqual(SslPolicyErrors.None, errors); callbackInvoked = true; return true; }; await cws.ConnectAsync(uri, cts.Token); } }, server => server.AcceptConnectionAsync(async connection => { Assert.NotNull(await LoopbackHelper.WebSocketHandshakeAsync(connection)); }), new LoopbackServer.Options { UseSsl = secure, WebSocketEndpoint = true }); Assert.Equal(secure, callbackInvoked); } [OuterLoop("Connects to remote service")] [ConditionalFact(nameof(WebSocketsSupported))] [SkipOnPlatform(TestPlatforms.Browser, "Credentials not supported on browser")] public async Task ClientCertificates_ValidCertificate_ServerReceivesCertificateAndConnectAsyncSucceeds() { if (PlatformDetection.IsWindows7) { return; // see https://github.com/dotnet/runtime/issues/1491#issuecomment-376392057 for more details } using (X509Certificate2 clientCert = Test.Common.Configuration.Certificates.GetClientCertificate()) { await LoopbackServer.CreateClientAndServerAsync(async uri => { using (var clientSocket = new ClientWebSocket()) using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { clientSocket.Options.ClientCertificates.Add(clientCert); clientSocket.Options.RemoteCertificateValidationCallback = delegate { return true; }; await clientSocket.ConnectAsync(uri, cts.Token); } }, server => server.AcceptConnectionAsync(async connection => { // Validate that the client certificate received by the server matches the one configured on // the client-side socket. SslStream sslStream = Assert.IsType<SslStream>(connection.Stream); Assert.NotNull(sslStream.RemoteCertificate); Assert.Equal(clientCert, new X509Certificate2(sslStream.RemoteCertificate)); // Complete the WebSocket upgrade over the secure channel. After this is done, the client-side // ConnectAsync should complete. Assert.NotNull(await LoopbackHelper.WebSocketHandshakeAsync(connection)); }), new LoopbackServer.Options { UseSsl = true, WebSocketEndpoint = true }); } } [ConditionalTheory(nameof(WebSocketsSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/34690", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] [InlineData("ws")] [InlineData("wss")] [SkipOnPlatform(TestPlatforms.Browser, "Credentials not supported on browser")] public async Task Connect_ViaProxy_ProxyTunnelRequestIssued(string scheme) { if (PlatformDetection.IsWindows7) { return; // see https://github.com/dotnet/runtime/issues/1491#issuecomment-376392057 for more details } bool connectionAccepted = false; await LoopbackServer.CreateClientAndServerAsync(async proxyUri => { using (var cws = new ClientWebSocket()) { cws.Options.Proxy = new WebProxy(proxyUri); WebSocketException wse = await Assert.ThrowsAnyAsync<WebSocketException>(async () => await cws.ConnectAsync(new Uri($"{scheme}://doesntmatter.invalid"), default)); // Inner exception should indicate proxy connect failure with the error code we send (403) HttpRequestException hre = Assert.IsType<HttpRequestException>(wse.InnerException); Assert.Contains("403", hre.Message); } }, server => server.AcceptConnectionAsync(async connection => { var lines = await connection.ReadRequestHeaderAsync(); Assert.Contains("CONNECT", lines[0]); connectionAccepted = true; // Send non-success error code so that SocketsHttpHandler won't retry. await connection.SendResponseAsync(statusCode: HttpStatusCode.Forbidden); connection.Dispose(); })); Assert.True(connectionAccepted); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net.Http; using System.Net.Security; using System.Net.Test.Common; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.WebSockets.Client.Tests { public class ClientWebSocketOptionsTests : ClientWebSocketTestBase { public ClientWebSocketOptionsTests(ITestOutputHelper output) : base(output) { } [ConditionalFact(nameof(WebSocketsSupported))] [SkipOnPlatform(TestPlatforms.Browser, "Credentials not supported on browser")] public static void UseDefaultCredentials_Roundtrips() { var cws = new ClientWebSocket(); Assert.False(cws.Options.UseDefaultCredentials); cws.Options.UseDefaultCredentials = true; Assert.True(cws.Options.UseDefaultCredentials); cws.Options.UseDefaultCredentials = false; Assert.False(cws.Options.UseDefaultCredentials); } [ConditionalFact(nameof(WebSocketsSupported))] [SkipOnPlatform(TestPlatforms.Browser, "Proxy not supported on browser")] public static void Proxy_Roundtrips() { var cws = new ClientWebSocket(); Assert.NotNull(cws.Options.Proxy); Assert.Same(cws.Options.Proxy, cws.Options.Proxy); IWebProxy p = new WebProxy(); cws.Options.Proxy = p; Assert.Same(p, cws.Options.Proxy); cws.Options.Proxy = null; Assert.Null(cws.Options.Proxy); } [OuterLoop] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] [ActiveIssue("https://github.com/dotnet/runtime/issues/43751")] public async Task Proxy_SetNull_ConnectsSuccessfully(Uri server) { for (int i = 0; i < 3; i++) // Connect and disconnect multiple times to exercise shared handler on netcoreapp { var ws = await WebSocketHelper.Retry(_output, async () => { var cws = new ClientWebSocket(); cws.Options.Proxy = null; await cws.ConnectAsync(server, default); return cws; }); await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, default); ws.Dispose(); } } [ActiveIssue("https://github.com/dotnet/runtime/issues/25440")] [OuterLoop] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task Proxy_ConnectThruProxy_Success(Uri server) { string proxyServerUri = System.Net.Test.Common.Configuration.WebSockets.ProxyServerUri; if (string.IsNullOrEmpty(proxyServerUri)) { _output.WriteLine("Skipping test...no proxy server defined."); return; } _output.WriteLine($"ProxyServer: {proxyServerUri}"); IWebProxy proxy = new WebProxy(new Uri(proxyServerUri)); using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket( server, TimeOutMilliseconds, _output, default(TimeSpan), proxy)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); Assert.Equal(WebSocketState.Open, cws.State); var closeStatus = WebSocketCloseStatus.NormalClosure; string closeDescription = "Normal Closure"; await cws.CloseAsync(closeStatus, closeDescription, cts.Token); // Verify a clean close frame handshake. Assert.Equal(WebSocketState.Closed, cws.State); Assert.Equal(closeStatus, cws.CloseStatus); Assert.Equal(closeDescription, cws.CloseStatusDescription); } } [ConditionalFact(nameof(WebSocketsSupported))] [SkipOnPlatform(TestPlatforms.Browser, "Buffer not supported on browser")] public static void SetBuffer_InvalidArgs_Throws() { // Recreate the minimum WebSocket buffer size values from the .NET Framework version of WebSocket, // and pick the correct name of the buffer used when throwing an ArgumentOutOfRangeException. int minSendBufferSize = 1; int minReceiveBufferSize = 1; string bufferName = "buffer"; var cws = new ClientWebSocket(); AssertExtensions.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => cws.Options.SetBuffer(0, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => cws.Options.SetBuffer(0, minSendBufferSize)); AssertExtensions.Throws<ArgumentOutOfRangeException>("sendBufferSize", () => cws.Options.SetBuffer(minReceiveBufferSize, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => cws.Options.SetBuffer(0, 0, new ArraySegment<byte>(new byte[1]))); AssertExtensions.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => cws.Options.SetBuffer(0, minSendBufferSize, new ArraySegment<byte>(new byte[1]))); AssertExtensions.Throws<ArgumentOutOfRangeException>("sendBufferSize", () => cws.Options.SetBuffer(minReceiveBufferSize, 0, new ArraySegment<byte>(new byte[1]))); AssertExtensions.Throws<ArgumentNullException>("buffer.Array", () => cws.Options.SetBuffer(minReceiveBufferSize, minSendBufferSize, default(ArraySegment<byte>))); AssertExtensions.Throws<ArgumentOutOfRangeException>(bufferName, () => cws.Options.SetBuffer(minReceiveBufferSize, minSendBufferSize, new ArraySegment<byte>(new byte[0]))); } [ConditionalFact(nameof(WebSocketsSupported))] [SkipOnPlatform(TestPlatforms.Browser, "KeepAlive not supported on browser")] public static void KeepAliveInterval_Roundtrips() { var cws = new ClientWebSocket(); Assert.True(cws.Options.KeepAliveInterval > TimeSpan.Zero); cws.Options.KeepAliveInterval = TimeSpan.Zero; Assert.Equal(TimeSpan.Zero, cws.Options.KeepAliveInterval); cws.Options.KeepAliveInterval = TimeSpan.MaxValue; Assert.Equal(TimeSpan.MaxValue, cws.Options.KeepAliveInterval); cws.Options.KeepAliveInterval = Timeout.InfiniteTimeSpan; Assert.Equal(Timeout.InfiniteTimeSpan, cws.Options.KeepAliveInterval); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => cws.Options.KeepAliveInterval = TimeSpan.MinValue); } [ConditionalFact(nameof(WebSocketsSupported))] [SkipOnPlatform(TestPlatforms.Browser, "Certificates not supported on browser")] public void RemoteCertificateValidationCallback_Roundtrips() { using (var cws = new ClientWebSocket()) { Assert.Null(cws.Options.RemoteCertificateValidationCallback); RemoteCertificateValidationCallback callback = delegate { return true; }; cws.Options.RemoteCertificateValidationCallback = callback; Assert.Same(callback, cws.Options.RemoteCertificateValidationCallback); cws.Options.RemoteCertificateValidationCallback = null; Assert.Null(cws.Options.RemoteCertificateValidationCallback); } } [OuterLoop("Connects to remote service")] [ConditionalTheory(nameof(WebSocketsSupported))] [InlineData(false)] [InlineData(true)] [SkipOnPlatform(TestPlatforms.Browser, "Certificates not supported on browser")] public async Task RemoteCertificateValidationCallback_PassedRemoteCertificateInfo(bool secure) { if (PlatformDetection.IsWindows7) { return; // see https://github.com/dotnet/runtime/issues/1491#issuecomment-376392057 for more details } bool callbackInvoked = false; await LoopbackServer.CreateClientAndServerAsync(async uri => { using (var cws = new ClientWebSocket()) using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { cws.Options.RemoteCertificateValidationCallback = (source, cert, chain, errors) => { Assert.NotNull(source); Assert.NotNull(cert); Assert.NotNull(chain); Assert.NotEqual(SslPolicyErrors.None, errors); callbackInvoked = true; return true; }; await cws.ConnectAsync(uri, cts.Token); } }, server => server.AcceptConnectionAsync(async connection => { Assert.NotNull(await LoopbackHelper.WebSocketHandshakeAsync(connection)); }), new LoopbackServer.Options { UseSsl = secure, WebSocketEndpoint = true }); Assert.Equal(secure, callbackInvoked); } [OuterLoop("Connects to remote service")] [ConditionalFact(nameof(WebSocketsSupported))] [SkipOnPlatform(TestPlatforms.Browser, "Credentials not supported on browser")] public async Task ClientCertificates_ValidCertificate_ServerReceivesCertificateAndConnectAsyncSucceeds() { if (PlatformDetection.IsWindows7) { return; // see https://github.com/dotnet/runtime/issues/1491#issuecomment-376392057 for more details } using (X509Certificate2 clientCert = Test.Common.Configuration.Certificates.GetClientCertificate()) { await LoopbackServer.CreateClientAndServerAsync(async uri => { using (var clientSocket = new ClientWebSocket()) using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { clientSocket.Options.ClientCertificates.Add(clientCert); clientSocket.Options.RemoteCertificateValidationCallback = delegate { return true; }; await clientSocket.ConnectAsync(uri, cts.Token); } }, server => server.AcceptConnectionAsync(async connection => { // Validate that the client certificate received by the server matches the one configured on // the client-side socket. SslStream sslStream = Assert.IsType<SslStream>(connection.Stream); Assert.NotNull(sslStream.RemoteCertificate); Assert.Equal(clientCert, new X509Certificate2(sslStream.RemoteCertificate)); // Complete the WebSocket upgrade over the secure channel. After this is done, the client-side // ConnectAsync should complete. Assert.NotNull(await LoopbackHelper.WebSocketHandshakeAsync(connection)); }), new LoopbackServer.Options { UseSsl = true, WebSocketEndpoint = true }); } } [ConditionalTheory(nameof(WebSocketsSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/34690", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] [InlineData("ws")] [InlineData("wss")] [SkipOnPlatform(TestPlatforms.Browser, "Credentials not supported on browser")] public async Task Connect_ViaProxy_ProxyTunnelRequestIssued(string scheme) { if (PlatformDetection.IsWindows7) { return; // see https://github.com/dotnet/runtime/issues/1491#issuecomment-376392057 for more details } bool connectionAccepted = false; await LoopbackServer.CreateClientAndServerAsync(async proxyUri => { using (var cws = new ClientWebSocket()) { cws.Options.Proxy = new WebProxy(proxyUri); WebSocketException wse = await Assert.ThrowsAnyAsync<WebSocketException>(async () => await cws.ConnectAsync(new Uri($"{scheme}://doesntmatter.invalid"), default)); // Inner exception should indicate proxy connect failure with the error code we send (403) HttpRequestException hre = Assert.IsType<HttpRequestException>(wse.InnerException); Assert.Contains("403", hre.Message); } }, server => server.AcceptConnectionAsync(async connection => { var lines = await connection.ReadRequestHeaderAsync(); Assert.Contains("CONNECT", lines[0]); connectionAccepted = true; // Send non-success error code so that SocketsHttpHandler won't retry. await connection.SendResponseAsync(statusCode: HttpStatusCode.Forbidden); connection.Dispose(); })); Assert.True(connectionAccepted); } } }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/Common/tests/System/Xml/XPath/XmlDocument/CreateNavigatorFromXmlDocument.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Xml; using System.Xml.XPath; using XPathTests.Common; namespace XPathTests { public class CreateNavigatorFromXmlDocument : ICreateNavigator { public XPathNavigator CreateNavigatorFromFile(string fileName) { var stream = FileHelper.CreateStreamFromFile(fileName); var xmlDocument = new XmlDocument { PreserveWhitespace = true }; xmlDocument.Load(stream); return xmlDocument.CreateNavigator(); } public XPathNavigator CreateNavigator(string xml) { var xmlDocument = new XmlDocument { PreserveWhitespace = true }; xmlDocument.LoadXml(xml); return xmlDocument.CreateNavigator(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Xml; using System.Xml.XPath; using XPathTests.Common; namespace XPathTests { public class CreateNavigatorFromXmlDocument : ICreateNavigator { public XPathNavigator CreateNavigatorFromFile(string fileName) { var stream = FileHelper.CreateStreamFromFile(fileName); var xmlDocument = new XmlDocument { PreserveWhitespace = true }; xmlDocument.Load(stream); return xmlDocument.CreateNavigator(); } public XPathNavigator CreateNavigator(string xml) { var xmlDocument = new XmlDocument { PreserveWhitespace = true }; xmlDocument.LoadXml(xml); return xmlDocument.CreateNavigator(); } } }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/tests/JIT/Methodical/doublearray/dblarray3_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="dblarray3.cs" /> </ItemGroup> </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="dblarray3.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/CorHeader.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Reflection.PortableExecutable { public sealed class CorHeader { public ushort MajorRuntimeVersion { get; } public ushort MinorRuntimeVersion { get; } public DirectoryEntry MetadataDirectory { get; } public CorFlags Flags { get; } public int EntryPointTokenOrRelativeVirtualAddress { get; } public DirectoryEntry ResourcesDirectory { get; } public DirectoryEntry StrongNameSignatureDirectory { get; } public DirectoryEntry CodeManagerTableDirectory { get; } public DirectoryEntry VtableFixupsDirectory { get; } public DirectoryEntry ExportAddressTableJumpsDirectory { get; } public DirectoryEntry ManagedNativeHeaderDirectory { get; } internal CorHeader(ref PEBinaryReader reader) { // byte count reader.ReadInt32(); MajorRuntimeVersion = reader.ReadUInt16(); MinorRuntimeVersion = reader.ReadUInt16(); MetadataDirectory = new DirectoryEntry(ref reader); Flags = (CorFlags)reader.ReadUInt32(); EntryPointTokenOrRelativeVirtualAddress = reader.ReadInt32(); ResourcesDirectory = new DirectoryEntry(ref reader); StrongNameSignatureDirectory = new DirectoryEntry(ref reader); CodeManagerTableDirectory = new DirectoryEntry(ref reader); VtableFixupsDirectory = new DirectoryEntry(ref reader); ExportAddressTableJumpsDirectory = new DirectoryEntry(ref reader); ManagedNativeHeaderDirectory = new DirectoryEntry(ref reader); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Reflection.PortableExecutable { public sealed class CorHeader { public ushort MajorRuntimeVersion { get; } public ushort MinorRuntimeVersion { get; } public DirectoryEntry MetadataDirectory { get; } public CorFlags Flags { get; } public int EntryPointTokenOrRelativeVirtualAddress { get; } public DirectoryEntry ResourcesDirectory { get; } public DirectoryEntry StrongNameSignatureDirectory { get; } public DirectoryEntry CodeManagerTableDirectory { get; } public DirectoryEntry VtableFixupsDirectory { get; } public DirectoryEntry ExportAddressTableJumpsDirectory { get; } public DirectoryEntry ManagedNativeHeaderDirectory { get; } internal CorHeader(ref PEBinaryReader reader) { // byte count reader.ReadInt32(); MajorRuntimeVersion = reader.ReadUInt16(); MinorRuntimeVersion = reader.ReadUInt16(); MetadataDirectory = new DirectoryEntry(ref reader); Flags = (CorFlags)reader.ReadUInt32(); EntryPointTokenOrRelativeVirtualAddress = reader.ReadInt32(); ResourcesDirectory = new DirectoryEntry(ref reader); StrongNameSignatureDirectory = new DirectoryEntry(ref reader); CodeManagerTableDirectory = new DirectoryEntry(ref reader); VtableFixupsDirectory = new DirectoryEntry(ref reader); ExportAddressTableJumpsDirectory = new DirectoryEntry(ref reader); ManagedNativeHeaderDirectory = new DirectoryEntry(ref reader); } } }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/tests/JIT/Regression/VS-ia64-JIT/V2.0-Beta2/b360587/b360587.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="repro.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="repro.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/StreamExtensions.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.IO; namespace System.Reflection.Internal { internal static partial class StreamExtensions { internal static unsafe int Read(this Stream stream, byte* buffer, int size) => stream.Read(new Span<byte>(buffer, size)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; namespace System.Reflection.Internal { internal static partial class StreamExtensions { internal static unsafe int Read(this Stream stream, byte* buffer, int size) => stream.Read(new Span<byte>(buffer, size)); } }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ConvertToUInt32RoundToPositiveInfinity.Vector64.Single.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ConvertToUInt32RoundToPositiveInfinity_Vector64_Single() { var test = new SimpleUnaryOpTest__ConvertToUInt32RoundToPositiveInfinity_Vector64_Single(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ConvertToUInt32RoundToPositiveInfinity_Vector64_Single { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__ConvertToUInt32RoundToPositiveInfinity_Vector64_Single testClass) { var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__ConvertToUInt32RoundToPositiveInfinity_Vector64_Single testClass) { fixed (Vector64<Single>* pFld1 = &_fld1) { var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity( AdvSimd.LoadVector64((Single*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector64<Single> _clsVar1; private Vector64<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__ConvertToUInt32RoundToPositiveInfinity_Vector64_Single() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); } public SimpleUnaryOpTest__ConvertToUInt32RoundToPositiveInfinity_Vector64_Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new UInt32[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.ConvertToUInt32RoundToPositiveInfinity( Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity( AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ConvertToUInt32RoundToPositiveInfinity), new Type[] { typeof(Vector64<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ConvertToUInt32RoundToPositiveInfinity), new Type[] { typeof(Vector64<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Single>* pClsVar1 = &_clsVar1) { var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity( AdvSimd.LoadVector64((Single*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr); var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)); var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__ConvertToUInt32RoundToPositiveInfinity_Vector64_Single(); var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__ConvertToUInt32RoundToPositiveInfinity_Vector64_Single(); fixed (Vector64<Single>* pFld1 = &test._fld1) { var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity( AdvSimd.LoadVector64((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Single>* pFld1 = &_fld1) { var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity( AdvSimd.LoadVector64((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity( AdvSimd.LoadVector64((Single*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ConvertToUInt32RoundToPositiveInfinity(firstOp[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ConvertToUInt32RoundToPositiveInfinity)}<UInt32>(Vector64<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ConvertToUInt32RoundToPositiveInfinity_Vector64_Single() { var test = new SimpleUnaryOpTest__ConvertToUInt32RoundToPositiveInfinity_Vector64_Single(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ConvertToUInt32RoundToPositiveInfinity_Vector64_Single { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__ConvertToUInt32RoundToPositiveInfinity_Vector64_Single testClass) { var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__ConvertToUInt32RoundToPositiveInfinity_Vector64_Single testClass) { fixed (Vector64<Single>* pFld1 = &_fld1) { var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity( AdvSimd.LoadVector64((Single*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector64<Single> _clsVar1; private Vector64<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__ConvertToUInt32RoundToPositiveInfinity_Vector64_Single() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); } public SimpleUnaryOpTest__ConvertToUInt32RoundToPositiveInfinity_Vector64_Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new UInt32[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.ConvertToUInt32RoundToPositiveInfinity( Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity( AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ConvertToUInt32RoundToPositiveInfinity), new Type[] { typeof(Vector64<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ConvertToUInt32RoundToPositiveInfinity), new Type[] { typeof(Vector64<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Single>* pClsVar1 = &_clsVar1) { var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity( AdvSimd.LoadVector64((Single*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr); var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)); var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__ConvertToUInt32RoundToPositiveInfinity_Vector64_Single(); var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__ConvertToUInt32RoundToPositiveInfinity_Vector64_Single(); fixed (Vector64<Single>* pFld1 = &test._fld1) { var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity( AdvSimd.LoadVector64((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Single>* pFld1 = &_fld1) { var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity( AdvSimd.LoadVector64((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ConvertToUInt32RoundToPositiveInfinity( AdvSimd.LoadVector64((Single*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ConvertToUInt32RoundToPositiveInfinity(firstOp[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ConvertToUInt32RoundToPositiveInfinity)}<UInt32>(Vector64<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Management/src/System/Management/ManagementClass.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Specialized; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.CodeDom; namespace System.Management { //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Represents a CIM management class from WMI. CIM (Common Information Model) classes /// represent management information including hardware, software, processes, etc. /// For more information about the CIM classes available in Windows search for "win32 classes".</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates getting information about a class using the ManagementClass object /// class Sample_ManagementClass /// { /// public static int Main(string[] args) { /// ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk"); /// diskClass.Get(); /// Console.WriteLine("Logical Disk class has " + diskClass.Properties.Count + " properties"); /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example demonstrates getting information about a class using the ManagementClass object /// Class Sample_ManagementClass /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim diskClass As New ManagementClass("Win32_LogicalDisk") /// diskClass.Get() /// Console.WriteLine(("Logical Disk class has " &amp; _ /// diskClass.Properties.Count.ToString() &amp; _ /// " properties")) /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class ManagementClass : ManagementObject { private MethodDataCollection methods; protected override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } /// <summary> /// Internal factory for classes, used when deriving a class /// or cloning a class. For these purposes we always mark /// the class as "bound". /// </summary> /// <param name="wbemObject">The underlying WMI object</param> /// <param name="mgObj">Seed class from which we will get initialization info</param> internal static ManagementClass GetManagementClass( IWbemClassObjectFreeThreaded wbemObject, ManagementClass mgObj) { ManagementClass newClass = new ManagementClass(); newClass.wbemObject = wbemObject; if (null != mgObj) { newClass.scope = ManagementScope._Clone(mgObj.scope); ManagementPath objPath = mgObj.Path; if (null != objPath) newClass.path = ManagementPath._Clone(objPath); // Ensure we have our class name in the path object className = null; int dummy = 0; int status = wbemObject.Get_("__CLASS", 0, ref className, ref dummy, ref dummy); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } if (className != System.DBNull.Value) newClass.path.internalClassName = (string)className; ObjectGetOptions options = mgObj.Options; if (null != options) newClass.options = ObjectGetOptions._Clone(options); // Finally we ensure that this object is marked as bound. // We do this as a last step since setting certain properties // (Options, Path and Scope) would mark it as unbound // // *** // * Changed isBound flag to wbemObject==null check. // * newClass.IsBound = true; // *** } return newClass; } internal static ManagementClass GetManagementClass( IWbemClassObjectFreeThreaded wbemObject, ManagementScope scope) { ManagementClass newClass = new ManagementClass(); newClass.path = new ManagementPath(ManagementPath.GetManagementPath(wbemObject)); if (null != scope) newClass.scope = ManagementScope._Clone(scope); newClass.wbemObject = wbemObject; return newClass; } //default constructor /// <overload> /// Initializes a new instance /// of the <see cref='System.Management.ManagementClass'/> class. /// </overload> /// <summary> /// <para> Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class. This is the /// default constructor.</para> /// </summary> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass(); /// </code> /// <code lang='VB'>Dim c As New ManagementClass() /// </code> /// </example> public ManagementClass() : this((ManagementScope)null, (ManagementPath)null, null) { } //parameterized constructors /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class initialized to the /// given path.</para> /// </summary> /// <param name='path'>A <see cref='System.Management.ManagementPath'/> specifying which WMI class to bind to.</param> /// <remarks> /// <para>The <paramref name="path"/> parameter must specify a WMI class /// path.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass( /// new ManagementPath("Win32_LogicalDisk")); /// </code> /// <code lang='VB'>Dim c As New ManagementClass( _ /// New ManagementPath("Win32_LogicalDisk")) /// </code> /// </example> public ManagementClass(ManagementPath path) : this(null, path, null) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class initialized to the given path.</para> /// </summary> /// <param name='path'>The path to the WMI class.</param> /// <example> /// <code lang='C#'>ManagementClass c = new /// ManagementClass("Win32_LogicalDisk"); /// </code> /// <code lang='VB'>Dim c As New ManagementClass("Win32_LogicalDisk") /// </code> /// </example> public ManagementClass(string path) : this(null, new ManagementPath(path), null) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class initialized to the /// given WMI class path using the specified options.</para> /// </summary> /// <param name='path'>A <see cref='System.Management.ManagementPath'/> representing the WMI class path.</param> /// <param name=' options'>An <see cref='System.Management.ObjectGetOptions'/> representing the options to use when retrieving this class.</param> /// <example> /// <code lang='C#'>ManagementPath p = new ManagementPath("Win32_Process"); /// //Options specify that amended qualifiers are to be retrieved along with the class /// ObjectGetOptions o = new ObjectGetOptions(null, true); /// ManagementClass c = new ManagementClass(p,o); /// </code> /// <code lang='VB'>Dim p As New ManagementPath("Win32_Process") /// ' Options specify that amended qualifiers are to be retrieved along with the class /// Dim o As New ObjectGetOptions(Null, True) /// Dim c As New ManagementClass(p,o) /// </code> /// </example> public ManagementClass(ManagementPath path, ObjectGetOptions options) : this(null, path, options) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class initialized to the given WMI class path /// using the specified options.</para> /// </summary> /// <param name='path'>The path to the WMI class.</param> /// <param name=' options'>An <see cref='System.Management.ObjectGetOptions'/> representing the options to use when retrieving the WMI class.</param> /// <example> /// <code lang='C#'>//Options specify that amended qualifiers should be retrieved along with the class /// ObjectGetOptions o = new ObjectGetOptions(null, true); /// ManagementClass c = new ManagementClass("Win32_ComputerSystem",o); /// </code> /// <code lang='VB'>' Options specify that amended qualifiers should be retrieved along with the class /// Dim o As New ObjectGetOptions(Null, True) /// Dim c As New ManagementClass("Win32_ComputerSystem",o) /// </code> /// </example> public ManagementClass(string path, ObjectGetOptions options) : this(null, new ManagementPath(path), options) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class for the specified /// WMI class in the specified scope and with the specified options.</para> /// </summary> /// <param name='scope'>A <see cref='System.Management.ManagementScope'/> that specifies the scope (server and namespace) where the WMI class resides. </param> /// <param name=' path'>A <see cref='System.Management.ManagementPath'/> that represents the path to the WMI class in the specified scope.</param> /// <param name=' options'>An <see cref='System.Management.ObjectGetOptions'/> that specifies the options to use when retrieving the WMI class.</param> /// <remarks> /// <para> The path can be specified as a full /// path (including server and namespace). However, if a scope is specified, it will /// override the first portion of the full path.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementScope s = new ManagementScope("\\\\MyBox\\root\\cimv2"); /// ManagementPath p = new ManagementPath("Win32_Environment"); /// ObjectGetOptions o = new ObjectGetOptions(null, true); /// ManagementClass c = new ManagementClass(s, p, o); /// </code> /// <code lang='VB'>Dim s As New ManagementScope("\\MyBox\root\cimv2") /// Dim p As New ManagementPath("Win32_Environment") /// Dim o As New ObjectGetOptions(Null, True) /// Dim c As New ManagementClass(s, p, o) /// </code> /// </example> public ManagementClass(ManagementScope scope, ManagementPath path, ObjectGetOptions options) : base(scope, path, options) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class for the specified WMI class, in the /// specified scope, and with the specified options.</para> /// </summary> /// <param name='scope'>The scope in which the WMI class resides.</param> /// <param name=' path'>The path to the WMI class within the specified scope.</param> /// <param name=' options'>An <see cref='System.Management.ObjectGetOptions'/> that specifies the options to use when retrieving the WMI class.</param> /// <remarks> /// <para> The path can be specified as a full /// path (including server and namespace). However, if a scope is specified, it will /// override the first portion of the full path.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass("\\\\MyBox\\root\\cimv2", /// "Win32_Environment", /// new ObjectGetOptions(null, true)); /// </code> /// <code lang='VB'>Dim c As New ManagementClass("\\MyBox\root\cimv2", _ /// "Win32_Environment", _ /// new ObjectGetOptions(Null, True)) /// </code> /// </example> public ManagementClass(string scope, string path, ObjectGetOptions options) : base(new ManagementScope(scope), new ManagementPath(path), options) { } protected ManagementClass(SerializationInfo info, StreamingContext context) : base(info, context) { throw new PlatformNotSupportedException(); } /// <summary> /// <para>Gets or sets the path of the WMI class to /// which the <see cref='System.Management.ManagementClass'/> /// object is bound.</para> /// </summary> /// <value> /// <para>The path of the object's class.</para> /// </value> /// <remarks> /// <para> When the property is set to a new value, /// the <see cref='System.Management.ManagementClass'/> /// object will be /// disconnected from any previously-bound WMI class. Reconnect to the new WMI class path.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass(); /// c.Path = "Win32_Environment"; /// </code> /// <code lang='VB'>Dim c As New ManagementClass() /// c.Path = "Win32_Environment" /// </code> /// </example> public override ManagementPath Path { get { return base.Path; } set { // This must be a class path or empty (don't allow instance paths) if ((null == value) || value.IsClass || value.IsEmpty) base.Path = value; else throw new ArgumentOutOfRangeException(nameof(value)); } } /// <summary> /// <para> Gets or sets an array containing all WMI classes in the /// inheritance hierarchy from this class to the top.</para> /// </summary> /// <value> /// A string collection containing the /// names of all WMI classes in the inheritance hierarchy of this class. /// </value> /// <remarks> /// <para>This property is read-only.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass("Win32_LogicalDisk"); /// foreach (string s in c.Derivation) /// Console.WriteLine("Further derived from : ", s); /// </code> /// <code lang='VB'>Dim c As New ManagementClass("Win32_LogicalDisk") /// Dim s As String /// For Each s In c.Derivation /// Console.WriteLine("Further derived from : " &amp; s) /// Next s /// </code> /// </example> public StringCollection Derivation { get { StringCollection result = new StringCollection(); int dummy1 = 0, dummy2 = 0; object val = null; int status = wbemObject.Get_("__DERIVATION", 0, ref val, ref dummy1, ref dummy2); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } if (null != val) result.AddRange((string[])val); return result; } } /// <summary> /// <para>Gets or sets a collection of <see cref='System.Management.MethodData'/> objects that /// represent the methods defined in the WMI class.</para> /// </summary> /// <value> /// <para>A <see cref='System.Management.MethodDataCollection'/> representing the methods defined in the WMI class.</para> /// </value> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass("Win32_Process"); /// foreach (Method m in c.Methods) /// Console.WriteLine("This class contains this method : ", m.Name); /// </code> /// <code lang='VB'>Dim c As New ManagementClass("Win32_Process") /// Dim m As Method /// For Each m in c.Methods /// Console.WriteLine("This class contains this method : " &amp; m.Name) /// </code> /// </example> public MethodDataCollection Methods { get { Initialize(true); if (methods == null) methods = new MethodDataCollection(this); return methods; } } // //Methods // //****************************************************** //GetInstances //****************************************************** /// <overload> /// Returns the collection of /// all instances of the class. /// </overload> /// <summary> /// <para>Returns the collection of all instances of the class.</para> /// </summary> /// <returns> /// <para>A collection of the <see cref='System.Management.ManagementObject'/> objects /// representing the instances of the class.</para> /// </returns> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass("Win32_Process"); /// foreach (ManagementObject o in c.GetInstances()) /// Console.WriteLine("Next instance of Win32_Process : ", o.Path); /// </code> /// <code lang='VB'>Dim c As New ManagementClass("Win32_Process") /// Dim o As ManagementObject /// For Each o In c.GetInstances() /// Console.WriteLine("Next instance of Win32_Process : " &amp; o.Path) /// Next o /// </code> /// </example> public ManagementObjectCollection GetInstances() { return GetInstances((EnumerationOptions)null); } /// <summary> /// <para>Returns the collection of all instances of the class using the specified options.</para> /// </summary> /// <param name='options'>The additional operation options.</param> /// <returns> /// <para>A collection of the <see cref='System.Management.ManagementObject'/> objects /// representing the instances of the class, according to the specified options.</para> /// </returns> /// <example> /// <code lang='C#'>EnumerationOptions opt = new EnumerationOptions(); /// //Will enumerate instances of the given class and any subclasses. /// o.enumerateDeep = true; /// ManagementClass c = new ManagementClass("CIM_Service"); /// foreach (ManagementObject o in c.GetInstances(opt)) /// Console.WriteLine(o["Name"]); /// </code> /// <code lang='VB'>Dim opt As New EnumerationOptions() /// 'Will enumerate instances of the given class and any subclasses. /// o.enumerateDeep = True /// Dim c As New ManagementClass("CIM_Service") /// Dim o As ManagementObject /// For Each o In c.GetInstances(opt) /// Console.WriteLine(o["Name"]) /// Next o /// </code> /// </example> public ManagementObjectCollection GetInstances(EnumerationOptions options) { if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); Initialize(false); IEnumWbemClassObject enumWbem = null; EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); //Need to make sure that we're not passing invalid flags to enumeration APIs. //The only flags in EnumerationOptions not valid for enumerations are EnsureLocatable & PrototypeOnly. o.EnsureLocatable = false; o.PrototypeOnly = false; SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; try { securityHandler = Scope.GetSecurityHandler(); status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).CreateInstanceEnum_( ClassName, o.Flags, o.GetContext(), ref enumWbem); } finally { if (securityHandler != null) securityHandler.Reset(); } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return new ManagementObjectCollection(Scope, o, enumWbem); } /// <summary> /// <para>Returns the collection of all instances of the class, asynchronously.</para> /// </summary> /// <param name='watcher'>The object to handle the asynchronous operation's progress. </param> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass("Win32_Share"); /// MyHandler h = new MyHandler(); /// ManagementOperationObserver ob = new ManagementOperationObserver(); /// ob.ObjectReady += new ObjectReadyEventHandler (h.NewObject); /// ob.Completed += new CompletedEventHandler (h.Done); /// /// c.GetInstances(ob); /// /// while (!h.Completed) /// System.Threading.Thread.Sleep (1000); /// /// //Here you can use the object /// Console.WriteLine(o["SomeProperty"]); /// /// public class MyHandler /// { /// private bool completed = false; /// /// public void NewObject(object sender, ObjectReadyEventArgs e) { /// Console.WriteLine("New result arrived !", ((ManagementObject)(e.NewObject))["Name"]); /// } /// /// public void Done(object sender, CompletedEventArgs e) { /// Console.WriteLine("async Get completed !"); /// completed = true; /// } /// /// public bool Completed { /// get { /// return completed; /// } /// } /// } /// </code> /// <code lang='VB'>Dim c As New ManagementClass("Win32_Share") /// Dim h As New MyHandler() /// Dim ob As New ManagementOperationObserver() /// ob.ObjectReady += New ObjectReadyEventHandler(h.NewObject) /// ob.Completed += New CompletedEventHandler(h.Done) /// /// c.GetInstances(ob) /// /// While Not h.Completed /// System.Threading.Thread.Sleep(1000) /// End While /// /// 'Here you can use the object /// Console.WriteLine(o("SomeProperty")) /// /// Public Class MyHandler /// Private completed As Boolean = false /// /// Public Sub Done(sender As Object, e As EventArrivedEventArgs) /// Console.WriteLine("async Get completed !") /// completed = True /// End Sub /// /// Public ReadOnly Property Completed() As Boolean /// Get /// Return completed /// End Get /// End Property /// End Class /// </code> /// </example> public void GetInstances(ManagementOperationObserver watcher) { GetInstances(watcher, (EnumerationOptions)null); } /// <summary> /// <para>Returns the collection of all instances of the class, asynchronously, using /// the specified options.</para> /// </summary> /// <param name='watcher'>The object to handle the asynchronous operation's progress. </param> /// <param name=' options'>The specified additional options for getting the instances.</param> public void GetInstances(ManagementOperationObserver watcher, EnumerationOptions options) { if (null == watcher) throw new ArgumentNullException(nameof(watcher)); if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); Initialize(false); EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); //Need to make sure that we're not passing invalid flags to enumeration APIs. //The only flags in EnumerationOptions not valid for enumerations are EnsureLocatable & PrototypeOnly. o.EnsureLocatable = false; o.PrototypeOnly = false; // Ensure we switch off ReturnImmediately as this is invalid for async calls o.ReturnImmediately = false; // If someone has registered for progress, make sure we flag it if (watcher.HaveListenersForProgress) o.SendStatus = true; WmiEventSink sink = watcher.GetNewSink(Scope, o.Context); SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; securityHandler = Scope.GetSecurityHandler(); status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).CreateInstanceEnumAsync_( ClassName, o.Flags, o.GetContext(), sink.Stub); if (securityHandler != null) securityHandler.Reset(); if (status < 0) { watcher.RemoveSink(sink); if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } //****************************************************** //GetSubclasses //****************************************************** /// <overload> /// Returns the collection of /// all derived classes for the class. /// </overload> /// <summary> /// <para>Returns the collection of all subclasses for the class.</para> /// </summary> /// <returns> /// <para>A collection of the <see cref='System.Management.ManagementObject'/> objects that /// represent the subclasses of the WMI class.</para> /// </returns> public ManagementObjectCollection GetSubclasses() { return GetSubclasses((EnumerationOptions)null); } /// <summary> /// <para>Retrieves the subclasses of the class using the specified /// options.</para> /// </summary> /// <param name='options'>The specified additional options for retrieving subclasses of the class.</param> /// <returns> /// <para>A collection of the <see cref='System.Management.ManagementObject'/> objects /// representing the subclasses of the WMI class, according to the specified /// options.</para> /// </returns> /// <example> /// <code lang='C#'>EnumerationOptions opt = new EnumerationOptions(); /// /// //Causes return of deep subclasses as opposed to only immediate ones. /// opt.enumerateDeep = true; /// /// ManagementObjectCollection c = (new /// ManagementClass("Win32_Share")).GetSubclasses(opt); /// </code> /// <code lang='VB'>Dim opt As New EnumerationOptions() /// /// 'Causes return of deep subclasses as opposed to only immediate ones. /// opt.enumerateDeep = true /// /// Dim cls As New ManagementClass("Win32_Share") /// Dim c As ManagementObjectCollection /// /// c = cls.GetSubClasses(opt) /// </code> /// </example> public ManagementObjectCollection GetSubclasses(EnumerationOptions options) { if (null == Path) throw new InvalidOperationException(); Initialize(false); IEnumWbemClassObject enumWbem = null; EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); //Need to make sure that we're not passing invalid flags to enumeration APIs. //The only flags in EnumerationOptions not valid for enumerations are EnsureLocatable & PrototypeOnly. o.EnsureLocatable = false; o.PrototypeOnly = false; SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; try { securityHandler = Scope.GetSecurityHandler(); status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).CreateClassEnum_( ClassName, o.Flags, o.GetContext(), ref enumWbem); } finally { if (securityHandler != null) securityHandler.Reset(); } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return new ManagementObjectCollection(Scope, o, enumWbem); } /// <summary> /// <para>Returns the collection of all classes derived from this class, asynchronously.</para> /// </summary> /// <param name='watcher'>The object to handle the asynchronous operation's progress. </param> public void GetSubclasses(ManagementOperationObserver watcher) { GetSubclasses(watcher, (EnumerationOptions)null); } /// <summary> /// <para>Retrieves all classes derived from this class, asynchronously, using the specified /// options.</para> /// </summary> /// <param name='watcher'>The object to handle the asynchronous operation's progress. </param> /// <param name='options'>The specified additional options to use in the derived class retrieval.</param> public void GetSubclasses(ManagementOperationObserver watcher, EnumerationOptions options) { if (null == watcher) throw new ArgumentNullException(nameof(watcher)); if (null == Path) throw new InvalidOperationException(); Initialize(false); EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); //Need to make sure that we're not passing invalid flags to enumeration APIs. //The only flags in EnumerationOptions not valid for enumerations are EnsureLocatable & PrototypeOnly. o.EnsureLocatable = false; o.PrototypeOnly = false; // Ensure we switch off ReturnImmediately as this is invalid for async calls o.ReturnImmediately = false; // If someone has registered for progress, make sure we flag it if (watcher.HaveListenersForProgress) o.SendStatus = true; WmiEventSink sink = watcher.GetNewSink(Scope, o.Context); SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; securityHandler = Scope.GetSecurityHandler(); status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).CreateClassEnumAsync_( ClassName, o.Flags, o.GetContext(), sink.Stub); if (securityHandler != null) securityHandler.Reset(); if (status < 0) { watcher.RemoveSink(sink); if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } //****************************************************** //Derive //****************************************************** /// <summary> /// <para>Derives a new class from this class.</para> /// </summary> /// <param name='newClassName'>The name of the new class to be derived.</param> /// <returns> /// <para>A new <see cref='System.Management.ManagementClass'/> /// that represents a new WMI class derived from the original class.</para> /// </returns> /// <remarks> /// <para>Note that the newly returned class has not been committed /// until the <see cref='System.Management.ManagementObject.Put()'/> method is explicitly called.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementClass existingClass = new ManagementClass("CIM_Service"); /// ManagementClass newClass = existingClass.Derive("My_Service"); /// newClass.Put(); //to commit the new class to the WMI repository. /// </code> /// <code lang='VB'>Dim existingClass As New ManagementClass("CIM_Service") /// Dim newClass As ManagementClass /// /// newClass = existingClass.Derive("My_Service") /// newClass.Put() 'to commit the new class to the WMI repository. /// </code> /// </example> public ManagementClass Derive(string newClassName) { ManagementClass newClass = null; if (null == newClassName) throw new ArgumentNullException(nameof(newClassName)); else { // Check the path is valid ManagementPath path = new ManagementPath(); try { path.ClassName = newClassName; } catch { throw new ArgumentOutOfRangeException(nameof(newClassName)); } if (!path.IsClass) throw new ArgumentOutOfRangeException(nameof(newClassName)); } if (PutButNotGot) { Get(); PutButNotGot = false; } IWbemClassObjectFreeThreaded newWbemClass = null; int status = this.wbemObject.SpawnDerivedClass_(0, out newWbemClass); if (status >= 0) { object val = newClassName; status = newWbemClass.Put_("__CLASS", 0, ref val, 0); if (status >= 0) newClass = ManagementClass.GetManagementClass(newWbemClass, this); } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return newClass; } //****************************************************** //CreateInstance //****************************************************** /// <summary> /// <para>Creates a new instance of the WMI class.</para> /// </summary> /// <returns> /// <para>A <see cref='System.Management.ManagementObject'/> that represents a new /// instance of the WMI class.</para> /// </returns> /// <remarks> /// <para>Note that the new instance is not committed until the /// <see cref='System.Management.ManagementObject.Put()'/> method is called. Before committing it, the key properties must /// be specified.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementClass envClass = new ManagementClass("Win32_Environment"); /// ManagementObject newInstance = /// existingClass.CreateInstance("My_Service"); /// newInstance["Name"] = "Cori"; /// newInstance.Put(); //to commit the new instance. /// </code> /// <code lang='VB'>Dim envClass As New ManagementClass("Win32_Environment") /// Dim newInstance As ManagementObject /// /// newInstance = existingClass.CreateInstance("My_Service") /// newInstance("Name") = "Cori" /// newInstance.Put() 'to commit the new instance. /// </code> /// </example> public ManagementObject CreateInstance() { ManagementObject newInstance = null; if (PutButNotGot) { Get(); PutButNotGot = false; } IWbemClassObjectFreeThreaded newWbemInstance = null; int status = this.wbemObject.SpawnInstance_(0, out newWbemInstance); if (status >= 0) newInstance = ManagementObject.GetManagementObject(newWbemInstance, Scope); else { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return newInstance; } /// <summary> /// <para>Returns a copy of the object.</para> /// </summary> /// <returns> /// <para> The cloned /// object.</para> /// </returns> /// <remarks> /// <para>Note that this does not create a copy of the /// WMI class; only an additional representation is created.</para> /// </remarks> public override object Clone() { IWbemClassObjectFreeThreaded theClone = null; int status = wbemObject.Clone_(out theClone); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return ManagementClass.GetManagementClass(theClone, this); } //****************************************************** //GetRelatedClasses //****************************************************** /// <overload> /// Retrieves classes related /// to the WMI class. /// </overload> /// <summary> /// <para> Retrieves classes related to the WMI class.</para> /// </summary> /// <returns> /// <para>A collection of the <see cref='System.Management.ManagementClass'/> or <see cref='System.Management.ManagementObject'/> /// objects that represents WMI classes or instances related to /// the WMI class.</para> /// </returns> /// <remarks> /// <para>The method queries the WMI schema for all /// possible associations that the WMI class may have with other classes, or in rare /// cases, to instances.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass("Win32_LogicalDisk"); /// /// foreach (ManagementClass r in c.GetRelatedClasses()) /// Console.WriteLine("Instances of {0} may have /// relationships to this class", r["__CLASS"]); /// </code> /// <code lang='VB'>Dim c As New ManagementClass("Win32_LogicalDisk") /// Dim r As ManagementClass /// /// For Each r In c.GetRelatedClasses() /// Console.WriteLine("Instances of {0} may have relationships _ /// to this class", r("__CLASS")) /// Next r /// </code> /// </example> public ManagementObjectCollection GetRelatedClasses() { return GetRelatedClasses((string)null); } /// <summary> /// <para> Retrieves classes related to the WMI class.</para> /// </summary> /// <param name='relatedClass'><para>The class from which resulting classes have to be derived.</para></param> /// <returns> /// A collection of classes related to /// this class. /// </returns> public ManagementObjectCollection GetRelatedClasses( string relatedClass) { return GetRelatedClasses(relatedClass, null, null, null, null, null, null); } /// <summary> /// <para> Retrieves classes related to the WMI class based on the specified /// options.</para> /// </summary> /// <param name=' relatedClass'><para>The class from which resulting classes have to be derived.</para></param> /// <param name=' relationshipClass'> The relationship type which resulting classes must have with the source class.</param> /// <param name=' relationshipQualifier'>This qualifier must be present on the relationship.</param> /// <param name=' relatedQualifier'>This qualifier must be present on the resulting classes.</param> /// <param name=' relatedRole'>The resulting classes must have this role in the relationship.</param> /// <param name=' thisRole'>The source class must have this role in the relationship.</param> /// <param name=' options'>The options for retrieving the resulting classes.</param> /// <returns> /// <para>A collection of classes related to /// this class.</para> /// </returns> public ManagementObjectCollection GetRelatedClasses( string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, EnumerationOptions options) { if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); Initialize(false); IEnumWbemClassObject enumWbem = null; EnumerationOptions o = (null != options) ? (EnumerationOptions)options.Clone() : new EnumerationOptions(); //Ensure EnumerateDeep flag bit is turned off as it's invalid for queries o.EnumerateDeep = true; RelatedObjectQuery q = new RelatedObjectQuery(true, Path.Path, relatedClass, relationshipClass, relatedQualifier, relationshipQualifier, relatedRole, thisRole); SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; try { securityHandler = Scope.GetSecurityHandler(); status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecQuery_( q.QueryLanguage, q.QueryString, o.Flags, o.GetContext(), ref enumWbem); } finally { if (securityHandler != null) securityHandler.Reset(); } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } //Create collection object return new ManagementObjectCollection(Scope, o, enumWbem); } /// <summary> /// <para> Retrieves classes /// related to the WMI class, asynchronously.</para> /// </summary> /// <param name='watcher'>The object to handle the asynchronous operation's progress. </param> public void GetRelatedClasses( ManagementOperationObserver watcher) { GetRelatedClasses(watcher, (string)null); } /// <summary> /// <para> Retrieves classes related to the WMI class, asynchronously, given the related /// class name.</para> /// </summary> /// <param name='watcher'>The object to handle the asynchronous operation's progress. </param> /// <param name=' relatedClass'>The name of the related class.</param> public void GetRelatedClasses( ManagementOperationObserver watcher, string relatedClass) { GetRelatedClasses(watcher, relatedClass, null, null, null, null, null, null); } /// <summary> /// <para> Retrieves classes related to the /// WMI class, asynchronously, using the specified options.</para> /// </summary> /// <param name='watcher'>Handler for progress and results of the asynchronous operation.</param> /// <param name=' relatedClass'><para>The class from which resulting classes have to be derived.</para></param> /// <param name=' relationshipClass'> The relationship type which resulting classes must have with the source class.</param> /// <param name=' relationshipQualifier'>This qualifier must be present on the relationship.</param> /// <param name=' relatedQualifier'>This qualifier must be present on the resulting classes.</param> /// <param name=' relatedRole'>The resulting classes must have this role in the relationship.</param> /// <param name=' thisRole'>The source class must have this role in the relationship.</param> /// <param name=' options'>The options for retrieving the resulting classes.</param> public void GetRelatedClasses( ManagementOperationObserver watcher, string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, EnumerationOptions options) { if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); Initialize(true); if (null == watcher) throw new ArgumentNullException(nameof(watcher)); else { EnumerationOptions o = (null != options) ? (EnumerationOptions)options.Clone() : new EnumerationOptions(); //Ensure EnumerateDeep flag bit is turned off as it's invalid for queries o.EnumerateDeep = true; // Ensure we switch off ReturnImmediately as this is invalid for async calls o.ReturnImmediately = false; // If someone has registered for progress, make sure we flag it if (watcher.HaveListenersForProgress) o.SendStatus = true; WmiEventSink sink = watcher.GetNewSink( Scope, o.Context); RelatedObjectQuery q = new RelatedObjectQuery(true, Path.Path, relatedClass, relationshipClass, relatedQualifier, relationshipQualifier, relatedRole, thisRole); SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; securityHandler = Scope.GetSecurityHandler(); status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecQueryAsync_( q.QueryLanguage, q.QueryString, o.Flags, o.GetContext(), sink.Stub); if (securityHandler != null) securityHandler.Reset(); if (status < 0) { watcher.RemoveSink(sink); if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } } //****************************************************** //GetRelationshipClasses //****************************************************** /// <overload> /// Retrieves relationship /// classes that relate the class to others. /// </overload> /// <summary> /// <para>Retrieves relationship classes that relate the class to others.</para> /// </summary> /// <returns> /// <para>A collection of association classes /// that relate the class to any other class.</para> /// </returns> public ManagementObjectCollection GetRelationshipClasses() { return GetRelationshipClasses((string)null); } /// <summary> /// <para>Retrieves relationship classes that relate the class to others, where the /// endpoint class is the specified class.</para> /// </summary> /// <param name='relationshipClass'>The endpoint class for all relationship classes returned.</param> /// <returns> /// <para>A collection of association classes /// that relate the class to the specified class.</para> /// </returns> public ManagementObjectCollection GetRelationshipClasses( string relationshipClass) { return GetRelationshipClasses(relationshipClass, null, null, null); } /// <summary> /// <para> Retrieves relationship classes that relate this class to others, according to /// specified options.</para> /// </summary> /// <param name='relationshipClass'><para> All resulting relationship classes must derive from this class.</para></param> /// <param name=' relationshipQualifier'>Resulting relationship classes must have this qualifier.</param> /// <param name=' thisRole'>The source class must have this role in the resulting relationship classes.</param> /// <param name=' options'>Specifies options for retrieving the results.</param> /// <returns> /// <para>A collection of association classes /// that relate this class to others, according to the specified options.</para> /// </returns> public ManagementObjectCollection GetRelationshipClasses( string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options) { if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); Initialize(false); IEnumWbemClassObject enumWbem = null; EnumerationOptions o = (null != options) ? options : new EnumerationOptions(); //Ensure EnumerateDeep flag is turned off as it's invalid for queries o.EnumerateDeep = true; RelationshipQuery q = new RelationshipQuery(true, Path.Path, relationshipClass, relationshipQualifier, thisRole); SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; //Execute WMI query try { securityHandler = Scope.GetSecurityHandler(); status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecQuery_( q.QueryLanguage, q.QueryString, o.Flags, o.GetContext(), ref enumWbem); } finally { if (securityHandler != null) securityHandler.Reset(); } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } //Create collection object return new ManagementObjectCollection(Scope, o, enumWbem); } /// <summary> /// <para>Retrieves relationship classes that relate the class to others, /// asynchronously.</para> /// </summary> /// <param name='watcher'>The object to handle the asynchronous operation's progress. </param> public void GetRelationshipClasses( ManagementOperationObserver watcher) { GetRelationshipClasses(watcher, (string)null); } /// <summary> /// <para>Retrieves relationship classes that relate the class to the specified WMI class, /// asynchronously.</para> /// </summary> /// <param name='watcher'>The object to handle the asynchronous operation's progress. </param> /// <param name=' relationshipClass'>The WMI class to which all returned relationships should point.</param> public void GetRelationshipClasses( ManagementOperationObserver watcher, string relationshipClass) { GetRelationshipClasses(watcher, relationshipClass, null, null, null); } /// <summary> /// <para>Retrieves relationship classes that relate the class according to the specified /// options, asynchronously.</para> /// </summary> /// <param name='watcher'>The handler for progress and results of the asynchronous operation.</param> /// <param name='relationshipClass'><para>The class from which all resulting relationship classes must derive.</para></param> /// <param name=' relationshipQualifier'>The qualifier which the resulting relationship classes must have.</param> /// <param name=' thisRole'>The role which the source class must have in the resulting relationship classes.</param> /// <param name=' options'> The options for retrieving the results.</param> public void GetRelationshipClasses( ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options) { if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); if (null == watcher) throw new ArgumentNullException(nameof(watcher)); else { Initialize(true); EnumerationOptions o = (null != options) ? (EnumerationOptions)options.Clone() : new EnumerationOptions(); //Ensure EnumerateDeep flag is turned off as it's invalid for queries o.EnumerateDeep = true; // Ensure we switch off ReturnImmediately as this is invalid for async calls o.ReturnImmediately = false; // If someone has registered for progress, make sure we flag it if (watcher.HaveListenersForProgress) o.SendStatus = true; WmiEventSink sink = watcher.GetNewSink(Scope, o.Context); RelationshipQuery q = new RelationshipQuery(true, Path.Path, relationshipClass, relationshipQualifier, thisRole); SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; securityHandler = Scope.GetSecurityHandler(); status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecQueryAsync_( q.QueryLanguage, q.QueryString, o.Flags, o.GetContext(), sink.Stub); if (securityHandler != null) securityHandler.Reset(); if (status < 0) { watcher.RemoveSink(sink); if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } } /// <overload> /// <para>Generates a strongly-typed class for a given WMI class.</para> /// </overload> /// <summary> /// <para>Generates a strongly-typed class for a given WMI class.</para> /// </summary> /// <param name='includeSystemClassInClassDef'><see langword='true'/> if the class for managing system properties must be included; otherwise, <see langword='false'/>.</param> /// <param name='systemPropertyClass'><see langword='true'/> if the generated class will manage system properties; otherwise, <see langword='false'/>.</param> /// <returns> /// <para>A <see cref='System.CodeDom.CodeTypeDeclaration'/> instance /// representing the declaration for the strongly-typed class.</para> /// </returns> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// using System.CodeDom; /// using System.IO; /// using System.CodeDom.Compiler; /// using Microsoft.CSharp; /// /// void GenerateCSharpCode() /// { /// string strFilePath = "C:\\temp\\LogicalDisk.cs"; /// CodeTypeDeclaration ClsDom; /// /// ManagementClass cls1 = new ManagementClass(null,"Win32_LogicalDisk",null); /// ClsDom = cls1.GetStronglyTypedClassCode(false,false); /// /// ICodeGenerator cg = (new CSharpCodeProvider()).CreateGenerator (); /// CodeNamespace cn = new CodeNamespace("TestNamespace"); /// /// // Add any imports to the code /// cn.Imports.Add (new CodeNamespaceImport("System")); /// cn.Imports.Add (new CodeNamespaceImport("System.ComponentModel")); /// cn.Imports.Add (new CodeNamespaceImport("System.Management")); /// cn.Imports.Add(new CodeNamespaceImport("System.Collections")); /// /// // Add class to the namespace /// cn.Types.Add (ClsDom); /// /// //Now create the filestream (output file) /// TextWriter tw = new StreamWriter(new /// FileStream (strFilePath,FileMode.Create)); /// /// // And write it to the file /// cg.GenerateCodeFromNamespace (cn, tw, new CodeGeneratorOptions()); /// /// tw.Close(); /// } /// </code> /// </example> public CodeTypeDeclaration GetStronglyTypedClassCode(bool includeSystemClassInClassDef, bool systemPropertyClass) { // Ensure that the object is valid Get(); ManagementClassGenerator classGen = new ManagementClassGenerator(this); return classGen.GenerateCode(includeSystemClassInClassDef, systemPropertyClass); } /// <summary> /// <para>Generates a strongly-typed class for a given WMI class. This function generates code for Visual Basic, /// C#, or JScript, depending on the input parameters.</para> /// </summary> /// <param name='lang'>The language of the code to be generated.</param> /// <param name='filePath'>The path of the file where the code is to be written.</param> /// <param name='classNamespace'>The .NET namespace into which the class should be generated. If this is empty, the namespace will be generated from the WMI namespace.</param> /// <returns> /// <para><see langword='true'/>, if the method succeeded; /// otherwise, <see langword='false'/> .</para> /// </returns> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// ManagementClass cls = new ManagementClass(null,"Win32_LogicalDisk",null,""); /// cls.GetStronglyTypedClassCode(CodeLanguage.CSharp,"C:\temp\Logicaldisk.cs",String.Empty); /// </code> /// </example> public bool GetStronglyTypedClassCode(CodeLanguage lang, string filePath, string classNamespace) { // Ensure that the object is valid Get(); ManagementClassGenerator classGen = new ManagementClassGenerator(this); return classGen.GenerateCode(lang, filePath, classNamespace); } }//ManagementClass }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Specialized; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.CodeDom; namespace System.Management { //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Represents a CIM management class from WMI. CIM (Common Information Model) classes /// represent management information including hardware, software, processes, etc. /// For more information about the CIM classes available in Windows search for "win32 classes".</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates getting information about a class using the ManagementClass object /// class Sample_ManagementClass /// { /// public static int Main(string[] args) { /// ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk"); /// diskClass.Get(); /// Console.WriteLine("Logical Disk class has " + diskClass.Properties.Count + " properties"); /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example demonstrates getting information about a class using the ManagementClass object /// Class Sample_ManagementClass /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim diskClass As New ManagementClass("Win32_LogicalDisk") /// diskClass.Get() /// Console.WriteLine(("Logical Disk class has " &amp; _ /// diskClass.Properties.Count.ToString() &amp; _ /// " properties")) /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class ManagementClass : ManagementObject { private MethodDataCollection methods; protected override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } /// <summary> /// Internal factory for classes, used when deriving a class /// or cloning a class. For these purposes we always mark /// the class as "bound". /// </summary> /// <param name="wbemObject">The underlying WMI object</param> /// <param name="mgObj">Seed class from which we will get initialization info</param> internal static ManagementClass GetManagementClass( IWbemClassObjectFreeThreaded wbemObject, ManagementClass mgObj) { ManagementClass newClass = new ManagementClass(); newClass.wbemObject = wbemObject; if (null != mgObj) { newClass.scope = ManagementScope._Clone(mgObj.scope); ManagementPath objPath = mgObj.Path; if (null != objPath) newClass.path = ManagementPath._Clone(objPath); // Ensure we have our class name in the path object className = null; int dummy = 0; int status = wbemObject.Get_("__CLASS", 0, ref className, ref dummy, ref dummy); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } if (className != System.DBNull.Value) newClass.path.internalClassName = (string)className; ObjectGetOptions options = mgObj.Options; if (null != options) newClass.options = ObjectGetOptions._Clone(options); // Finally we ensure that this object is marked as bound. // We do this as a last step since setting certain properties // (Options, Path and Scope) would mark it as unbound // // *** // * Changed isBound flag to wbemObject==null check. // * newClass.IsBound = true; // *** } return newClass; } internal static ManagementClass GetManagementClass( IWbemClassObjectFreeThreaded wbemObject, ManagementScope scope) { ManagementClass newClass = new ManagementClass(); newClass.path = new ManagementPath(ManagementPath.GetManagementPath(wbemObject)); if (null != scope) newClass.scope = ManagementScope._Clone(scope); newClass.wbemObject = wbemObject; return newClass; } //default constructor /// <overload> /// Initializes a new instance /// of the <see cref='System.Management.ManagementClass'/> class. /// </overload> /// <summary> /// <para> Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class. This is the /// default constructor.</para> /// </summary> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass(); /// </code> /// <code lang='VB'>Dim c As New ManagementClass() /// </code> /// </example> public ManagementClass() : this((ManagementScope)null, (ManagementPath)null, null) { } //parameterized constructors /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class initialized to the /// given path.</para> /// </summary> /// <param name='path'>A <see cref='System.Management.ManagementPath'/> specifying which WMI class to bind to.</param> /// <remarks> /// <para>The <paramref name="path"/> parameter must specify a WMI class /// path.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass( /// new ManagementPath("Win32_LogicalDisk")); /// </code> /// <code lang='VB'>Dim c As New ManagementClass( _ /// New ManagementPath("Win32_LogicalDisk")) /// </code> /// </example> public ManagementClass(ManagementPath path) : this(null, path, null) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class initialized to the given path.</para> /// </summary> /// <param name='path'>The path to the WMI class.</param> /// <example> /// <code lang='C#'>ManagementClass c = new /// ManagementClass("Win32_LogicalDisk"); /// </code> /// <code lang='VB'>Dim c As New ManagementClass("Win32_LogicalDisk") /// </code> /// </example> public ManagementClass(string path) : this(null, new ManagementPath(path), null) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class initialized to the /// given WMI class path using the specified options.</para> /// </summary> /// <param name='path'>A <see cref='System.Management.ManagementPath'/> representing the WMI class path.</param> /// <param name=' options'>An <see cref='System.Management.ObjectGetOptions'/> representing the options to use when retrieving this class.</param> /// <example> /// <code lang='C#'>ManagementPath p = new ManagementPath("Win32_Process"); /// //Options specify that amended qualifiers are to be retrieved along with the class /// ObjectGetOptions o = new ObjectGetOptions(null, true); /// ManagementClass c = new ManagementClass(p,o); /// </code> /// <code lang='VB'>Dim p As New ManagementPath("Win32_Process") /// ' Options specify that amended qualifiers are to be retrieved along with the class /// Dim o As New ObjectGetOptions(Null, True) /// Dim c As New ManagementClass(p,o) /// </code> /// </example> public ManagementClass(ManagementPath path, ObjectGetOptions options) : this(null, path, options) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class initialized to the given WMI class path /// using the specified options.</para> /// </summary> /// <param name='path'>The path to the WMI class.</param> /// <param name=' options'>An <see cref='System.Management.ObjectGetOptions'/> representing the options to use when retrieving the WMI class.</param> /// <example> /// <code lang='C#'>//Options specify that amended qualifiers should be retrieved along with the class /// ObjectGetOptions o = new ObjectGetOptions(null, true); /// ManagementClass c = new ManagementClass("Win32_ComputerSystem",o); /// </code> /// <code lang='VB'>' Options specify that amended qualifiers should be retrieved along with the class /// Dim o As New ObjectGetOptions(Null, True) /// Dim c As New ManagementClass("Win32_ComputerSystem",o) /// </code> /// </example> public ManagementClass(string path, ObjectGetOptions options) : this(null, new ManagementPath(path), options) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class for the specified /// WMI class in the specified scope and with the specified options.</para> /// </summary> /// <param name='scope'>A <see cref='System.Management.ManagementScope'/> that specifies the scope (server and namespace) where the WMI class resides. </param> /// <param name=' path'>A <see cref='System.Management.ManagementPath'/> that represents the path to the WMI class in the specified scope.</param> /// <param name=' options'>An <see cref='System.Management.ObjectGetOptions'/> that specifies the options to use when retrieving the WMI class.</param> /// <remarks> /// <para> The path can be specified as a full /// path (including server and namespace). However, if a scope is specified, it will /// override the first portion of the full path.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementScope s = new ManagementScope("\\\\MyBox\\root\\cimv2"); /// ManagementPath p = new ManagementPath("Win32_Environment"); /// ObjectGetOptions o = new ObjectGetOptions(null, true); /// ManagementClass c = new ManagementClass(s, p, o); /// </code> /// <code lang='VB'>Dim s As New ManagementScope("\\MyBox\root\cimv2") /// Dim p As New ManagementPath("Win32_Environment") /// Dim o As New ObjectGetOptions(Null, True) /// Dim c As New ManagementClass(s, p, o) /// </code> /// </example> public ManagementClass(ManagementScope scope, ManagementPath path, ObjectGetOptions options) : base(scope, path, options) { } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementClass'/> class for the specified WMI class, in the /// specified scope, and with the specified options.</para> /// </summary> /// <param name='scope'>The scope in which the WMI class resides.</param> /// <param name=' path'>The path to the WMI class within the specified scope.</param> /// <param name=' options'>An <see cref='System.Management.ObjectGetOptions'/> that specifies the options to use when retrieving the WMI class.</param> /// <remarks> /// <para> The path can be specified as a full /// path (including server and namespace). However, if a scope is specified, it will /// override the first portion of the full path.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass("\\\\MyBox\\root\\cimv2", /// "Win32_Environment", /// new ObjectGetOptions(null, true)); /// </code> /// <code lang='VB'>Dim c As New ManagementClass("\\MyBox\root\cimv2", _ /// "Win32_Environment", _ /// new ObjectGetOptions(Null, True)) /// </code> /// </example> public ManagementClass(string scope, string path, ObjectGetOptions options) : base(new ManagementScope(scope), new ManagementPath(path), options) { } protected ManagementClass(SerializationInfo info, StreamingContext context) : base(info, context) { throw new PlatformNotSupportedException(); } /// <summary> /// <para>Gets or sets the path of the WMI class to /// which the <see cref='System.Management.ManagementClass'/> /// object is bound.</para> /// </summary> /// <value> /// <para>The path of the object's class.</para> /// </value> /// <remarks> /// <para> When the property is set to a new value, /// the <see cref='System.Management.ManagementClass'/> /// object will be /// disconnected from any previously-bound WMI class. Reconnect to the new WMI class path.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass(); /// c.Path = "Win32_Environment"; /// </code> /// <code lang='VB'>Dim c As New ManagementClass() /// c.Path = "Win32_Environment" /// </code> /// </example> public override ManagementPath Path { get { return base.Path; } set { // This must be a class path or empty (don't allow instance paths) if ((null == value) || value.IsClass || value.IsEmpty) base.Path = value; else throw new ArgumentOutOfRangeException(nameof(value)); } } /// <summary> /// <para> Gets or sets an array containing all WMI classes in the /// inheritance hierarchy from this class to the top.</para> /// </summary> /// <value> /// A string collection containing the /// names of all WMI classes in the inheritance hierarchy of this class. /// </value> /// <remarks> /// <para>This property is read-only.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass("Win32_LogicalDisk"); /// foreach (string s in c.Derivation) /// Console.WriteLine("Further derived from : ", s); /// </code> /// <code lang='VB'>Dim c As New ManagementClass("Win32_LogicalDisk") /// Dim s As String /// For Each s In c.Derivation /// Console.WriteLine("Further derived from : " &amp; s) /// Next s /// </code> /// </example> public StringCollection Derivation { get { StringCollection result = new StringCollection(); int dummy1 = 0, dummy2 = 0; object val = null; int status = wbemObject.Get_("__DERIVATION", 0, ref val, ref dummy1, ref dummy2); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } if (null != val) result.AddRange((string[])val); return result; } } /// <summary> /// <para>Gets or sets a collection of <see cref='System.Management.MethodData'/> objects that /// represent the methods defined in the WMI class.</para> /// </summary> /// <value> /// <para>A <see cref='System.Management.MethodDataCollection'/> representing the methods defined in the WMI class.</para> /// </value> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass("Win32_Process"); /// foreach (Method m in c.Methods) /// Console.WriteLine("This class contains this method : ", m.Name); /// </code> /// <code lang='VB'>Dim c As New ManagementClass("Win32_Process") /// Dim m As Method /// For Each m in c.Methods /// Console.WriteLine("This class contains this method : " &amp; m.Name) /// </code> /// </example> public MethodDataCollection Methods { get { Initialize(true); if (methods == null) methods = new MethodDataCollection(this); return methods; } } // //Methods // //****************************************************** //GetInstances //****************************************************** /// <overload> /// Returns the collection of /// all instances of the class. /// </overload> /// <summary> /// <para>Returns the collection of all instances of the class.</para> /// </summary> /// <returns> /// <para>A collection of the <see cref='System.Management.ManagementObject'/> objects /// representing the instances of the class.</para> /// </returns> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass("Win32_Process"); /// foreach (ManagementObject o in c.GetInstances()) /// Console.WriteLine("Next instance of Win32_Process : ", o.Path); /// </code> /// <code lang='VB'>Dim c As New ManagementClass("Win32_Process") /// Dim o As ManagementObject /// For Each o In c.GetInstances() /// Console.WriteLine("Next instance of Win32_Process : " &amp; o.Path) /// Next o /// </code> /// </example> public ManagementObjectCollection GetInstances() { return GetInstances((EnumerationOptions)null); } /// <summary> /// <para>Returns the collection of all instances of the class using the specified options.</para> /// </summary> /// <param name='options'>The additional operation options.</param> /// <returns> /// <para>A collection of the <see cref='System.Management.ManagementObject'/> objects /// representing the instances of the class, according to the specified options.</para> /// </returns> /// <example> /// <code lang='C#'>EnumerationOptions opt = new EnumerationOptions(); /// //Will enumerate instances of the given class and any subclasses. /// o.enumerateDeep = true; /// ManagementClass c = new ManagementClass("CIM_Service"); /// foreach (ManagementObject o in c.GetInstances(opt)) /// Console.WriteLine(o["Name"]); /// </code> /// <code lang='VB'>Dim opt As New EnumerationOptions() /// 'Will enumerate instances of the given class and any subclasses. /// o.enumerateDeep = True /// Dim c As New ManagementClass("CIM_Service") /// Dim o As ManagementObject /// For Each o In c.GetInstances(opt) /// Console.WriteLine(o["Name"]) /// Next o /// </code> /// </example> public ManagementObjectCollection GetInstances(EnumerationOptions options) { if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); Initialize(false); IEnumWbemClassObject enumWbem = null; EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); //Need to make sure that we're not passing invalid flags to enumeration APIs. //The only flags in EnumerationOptions not valid for enumerations are EnsureLocatable & PrototypeOnly. o.EnsureLocatable = false; o.PrototypeOnly = false; SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; try { securityHandler = Scope.GetSecurityHandler(); status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).CreateInstanceEnum_( ClassName, o.Flags, o.GetContext(), ref enumWbem); } finally { if (securityHandler != null) securityHandler.Reset(); } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return new ManagementObjectCollection(Scope, o, enumWbem); } /// <summary> /// <para>Returns the collection of all instances of the class, asynchronously.</para> /// </summary> /// <param name='watcher'>The object to handle the asynchronous operation's progress. </param> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass("Win32_Share"); /// MyHandler h = new MyHandler(); /// ManagementOperationObserver ob = new ManagementOperationObserver(); /// ob.ObjectReady += new ObjectReadyEventHandler (h.NewObject); /// ob.Completed += new CompletedEventHandler (h.Done); /// /// c.GetInstances(ob); /// /// while (!h.Completed) /// System.Threading.Thread.Sleep (1000); /// /// //Here you can use the object /// Console.WriteLine(o["SomeProperty"]); /// /// public class MyHandler /// { /// private bool completed = false; /// /// public void NewObject(object sender, ObjectReadyEventArgs e) { /// Console.WriteLine("New result arrived !", ((ManagementObject)(e.NewObject))["Name"]); /// } /// /// public void Done(object sender, CompletedEventArgs e) { /// Console.WriteLine("async Get completed !"); /// completed = true; /// } /// /// public bool Completed { /// get { /// return completed; /// } /// } /// } /// </code> /// <code lang='VB'>Dim c As New ManagementClass("Win32_Share") /// Dim h As New MyHandler() /// Dim ob As New ManagementOperationObserver() /// ob.ObjectReady += New ObjectReadyEventHandler(h.NewObject) /// ob.Completed += New CompletedEventHandler(h.Done) /// /// c.GetInstances(ob) /// /// While Not h.Completed /// System.Threading.Thread.Sleep(1000) /// End While /// /// 'Here you can use the object /// Console.WriteLine(o("SomeProperty")) /// /// Public Class MyHandler /// Private completed As Boolean = false /// /// Public Sub Done(sender As Object, e As EventArrivedEventArgs) /// Console.WriteLine("async Get completed !") /// completed = True /// End Sub /// /// Public ReadOnly Property Completed() As Boolean /// Get /// Return completed /// End Get /// End Property /// End Class /// </code> /// </example> public void GetInstances(ManagementOperationObserver watcher) { GetInstances(watcher, (EnumerationOptions)null); } /// <summary> /// <para>Returns the collection of all instances of the class, asynchronously, using /// the specified options.</para> /// </summary> /// <param name='watcher'>The object to handle the asynchronous operation's progress. </param> /// <param name=' options'>The specified additional options for getting the instances.</param> public void GetInstances(ManagementOperationObserver watcher, EnumerationOptions options) { if (null == watcher) throw new ArgumentNullException(nameof(watcher)); if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); Initialize(false); EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); //Need to make sure that we're not passing invalid flags to enumeration APIs. //The only flags in EnumerationOptions not valid for enumerations are EnsureLocatable & PrototypeOnly. o.EnsureLocatable = false; o.PrototypeOnly = false; // Ensure we switch off ReturnImmediately as this is invalid for async calls o.ReturnImmediately = false; // If someone has registered for progress, make sure we flag it if (watcher.HaveListenersForProgress) o.SendStatus = true; WmiEventSink sink = watcher.GetNewSink(Scope, o.Context); SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; securityHandler = Scope.GetSecurityHandler(); status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).CreateInstanceEnumAsync_( ClassName, o.Flags, o.GetContext(), sink.Stub); if (securityHandler != null) securityHandler.Reset(); if (status < 0) { watcher.RemoveSink(sink); if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } //****************************************************** //GetSubclasses //****************************************************** /// <overload> /// Returns the collection of /// all derived classes for the class. /// </overload> /// <summary> /// <para>Returns the collection of all subclasses for the class.</para> /// </summary> /// <returns> /// <para>A collection of the <see cref='System.Management.ManagementObject'/> objects that /// represent the subclasses of the WMI class.</para> /// </returns> public ManagementObjectCollection GetSubclasses() { return GetSubclasses((EnumerationOptions)null); } /// <summary> /// <para>Retrieves the subclasses of the class using the specified /// options.</para> /// </summary> /// <param name='options'>The specified additional options for retrieving subclasses of the class.</param> /// <returns> /// <para>A collection of the <see cref='System.Management.ManagementObject'/> objects /// representing the subclasses of the WMI class, according to the specified /// options.</para> /// </returns> /// <example> /// <code lang='C#'>EnumerationOptions opt = new EnumerationOptions(); /// /// //Causes return of deep subclasses as opposed to only immediate ones. /// opt.enumerateDeep = true; /// /// ManagementObjectCollection c = (new /// ManagementClass("Win32_Share")).GetSubclasses(opt); /// </code> /// <code lang='VB'>Dim opt As New EnumerationOptions() /// /// 'Causes return of deep subclasses as opposed to only immediate ones. /// opt.enumerateDeep = true /// /// Dim cls As New ManagementClass("Win32_Share") /// Dim c As ManagementObjectCollection /// /// c = cls.GetSubClasses(opt) /// </code> /// </example> public ManagementObjectCollection GetSubclasses(EnumerationOptions options) { if (null == Path) throw new InvalidOperationException(); Initialize(false); IEnumWbemClassObject enumWbem = null; EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); //Need to make sure that we're not passing invalid flags to enumeration APIs. //The only flags in EnumerationOptions not valid for enumerations are EnsureLocatable & PrototypeOnly. o.EnsureLocatable = false; o.PrototypeOnly = false; SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; try { securityHandler = Scope.GetSecurityHandler(); status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).CreateClassEnum_( ClassName, o.Flags, o.GetContext(), ref enumWbem); } finally { if (securityHandler != null) securityHandler.Reset(); } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return new ManagementObjectCollection(Scope, o, enumWbem); } /// <summary> /// <para>Returns the collection of all classes derived from this class, asynchronously.</para> /// </summary> /// <param name='watcher'>The object to handle the asynchronous operation's progress. </param> public void GetSubclasses(ManagementOperationObserver watcher) { GetSubclasses(watcher, (EnumerationOptions)null); } /// <summary> /// <para>Retrieves all classes derived from this class, asynchronously, using the specified /// options.</para> /// </summary> /// <param name='watcher'>The object to handle the asynchronous operation's progress. </param> /// <param name='options'>The specified additional options to use in the derived class retrieval.</param> public void GetSubclasses(ManagementOperationObserver watcher, EnumerationOptions options) { if (null == watcher) throw new ArgumentNullException(nameof(watcher)); if (null == Path) throw new InvalidOperationException(); Initialize(false); EnumerationOptions o = (null == options) ? new EnumerationOptions() : (EnumerationOptions)options.Clone(); //Need to make sure that we're not passing invalid flags to enumeration APIs. //The only flags in EnumerationOptions not valid for enumerations are EnsureLocatable & PrototypeOnly. o.EnsureLocatable = false; o.PrototypeOnly = false; // Ensure we switch off ReturnImmediately as this is invalid for async calls o.ReturnImmediately = false; // If someone has registered for progress, make sure we flag it if (watcher.HaveListenersForProgress) o.SendStatus = true; WmiEventSink sink = watcher.GetNewSink(Scope, o.Context); SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; securityHandler = Scope.GetSecurityHandler(); status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).CreateClassEnumAsync_( ClassName, o.Flags, o.GetContext(), sink.Stub); if (securityHandler != null) securityHandler.Reset(); if (status < 0) { watcher.RemoveSink(sink); if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } //****************************************************** //Derive //****************************************************** /// <summary> /// <para>Derives a new class from this class.</para> /// </summary> /// <param name='newClassName'>The name of the new class to be derived.</param> /// <returns> /// <para>A new <see cref='System.Management.ManagementClass'/> /// that represents a new WMI class derived from the original class.</para> /// </returns> /// <remarks> /// <para>Note that the newly returned class has not been committed /// until the <see cref='System.Management.ManagementObject.Put()'/> method is explicitly called.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementClass existingClass = new ManagementClass("CIM_Service"); /// ManagementClass newClass = existingClass.Derive("My_Service"); /// newClass.Put(); //to commit the new class to the WMI repository. /// </code> /// <code lang='VB'>Dim existingClass As New ManagementClass("CIM_Service") /// Dim newClass As ManagementClass /// /// newClass = existingClass.Derive("My_Service") /// newClass.Put() 'to commit the new class to the WMI repository. /// </code> /// </example> public ManagementClass Derive(string newClassName) { ManagementClass newClass = null; if (null == newClassName) throw new ArgumentNullException(nameof(newClassName)); else { // Check the path is valid ManagementPath path = new ManagementPath(); try { path.ClassName = newClassName; } catch { throw new ArgumentOutOfRangeException(nameof(newClassName)); } if (!path.IsClass) throw new ArgumentOutOfRangeException(nameof(newClassName)); } if (PutButNotGot) { Get(); PutButNotGot = false; } IWbemClassObjectFreeThreaded newWbemClass = null; int status = this.wbemObject.SpawnDerivedClass_(0, out newWbemClass); if (status >= 0) { object val = newClassName; status = newWbemClass.Put_("__CLASS", 0, ref val, 0); if (status >= 0) newClass = ManagementClass.GetManagementClass(newWbemClass, this); } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return newClass; } //****************************************************** //CreateInstance //****************************************************** /// <summary> /// <para>Creates a new instance of the WMI class.</para> /// </summary> /// <returns> /// <para>A <see cref='System.Management.ManagementObject'/> that represents a new /// instance of the WMI class.</para> /// </returns> /// <remarks> /// <para>Note that the new instance is not committed until the /// <see cref='System.Management.ManagementObject.Put()'/> method is called. Before committing it, the key properties must /// be specified.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementClass envClass = new ManagementClass("Win32_Environment"); /// ManagementObject newInstance = /// existingClass.CreateInstance("My_Service"); /// newInstance["Name"] = "Cori"; /// newInstance.Put(); //to commit the new instance. /// </code> /// <code lang='VB'>Dim envClass As New ManagementClass("Win32_Environment") /// Dim newInstance As ManagementObject /// /// newInstance = existingClass.CreateInstance("My_Service") /// newInstance("Name") = "Cori" /// newInstance.Put() 'to commit the new instance. /// </code> /// </example> public ManagementObject CreateInstance() { ManagementObject newInstance = null; if (PutButNotGot) { Get(); PutButNotGot = false; } IWbemClassObjectFreeThreaded newWbemInstance = null; int status = this.wbemObject.SpawnInstance_(0, out newWbemInstance); if (status >= 0) newInstance = ManagementObject.GetManagementObject(newWbemInstance, Scope); else { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return newInstance; } /// <summary> /// <para>Returns a copy of the object.</para> /// </summary> /// <returns> /// <para> The cloned /// object.</para> /// </returns> /// <remarks> /// <para>Note that this does not create a copy of the /// WMI class; only an additional representation is created.</para> /// </remarks> public override object Clone() { IWbemClassObjectFreeThreaded theClone = null; int status = wbemObject.Clone_(out theClone); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return ManagementClass.GetManagementClass(theClone, this); } //****************************************************** //GetRelatedClasses //****************************************************** /// <overload> /// Retrieves classes related /// to the WMI class. /// </overload> /// <summary> /// <para> Retrieves classes related to the WMI class.</para> /// </summary> /// <returns> /// <para>A collection of the <see cref='System.Management.ManagementClass'/> or <see cref='System.Management.ManagementObject'/> /// objects that represents WMI classes or instances related to /// the WMI class.</para> /// </returns> /// <remarks> /// <para>The method queries the WMI schema for all /// possible associations that the WMI class may have with other classes, or in rare /// cases, to instances.</para> /// </remarks> /// <example> /// <code lang='C#'>ManagementClass c = new ManagementClass("Win32_LogicalDisk"); /// /// foreach (ManagementClass r in c.GetRelatedClasses()) /// Console.WriteLine("Instances of {0} may have /// relationships to this class", r["__CLASS"]); /// </code> /// <code lang='VB'>Dim c As New ManagementClass("Win32_LogicalDisk") /// Dim r As ManagementClass /// /// For Each r In c.GetRelatedClasses() /// Console.WriteLine("Instances of {0} may have relationships _ /// to this class", r("__CLASS")) /// Next r /// </code> /// </example> public ManagementObjectCollection GetRelatedClasses() { return GetRelatedClasses((string)null); } /// <summary> /// <para> Retrieves classes related to the WMI class.</para> /// </summary> /// <param name='relatedClass'><para>The class from which resulting classes have to be derived.</para></param> /// <returns> /// A collection of classes related to /// this class. /// </returns> public ManagementObjectCollection GetRelatedClasses( string relatedClass) { return GetRelatedClasses(relatedClass, null, null, null, null, null, null); } /// <summary> /// <para> Retrieves classes related to the WMI class based on the specified /// options.</para> /// </summary> /// <param name=' relatedClass'><para>The class from which resulting classes have to be derived.</para></param> /// <param name=' relationshipClass'> The relationship type which resulting classes must have with the source class.</param> /// <param name=' relationshipQualifier'>This qualifier must be present on the relationship.</param> /// <param name=' relatedQualifier'>This qualifier must be present on the resulting classes.</param> /// <param name=' relatedRole'>The resulting classes must have this role in the relationship.</param> /// <param name=' thisRole'>The source class must have this role in the relationship.</param> /// <param name=' options'>The options for retrieving the resulting classes.</param> /// <returns> /// <para>A collection of classes related to /// this class.</para> /// </returns> public ManagementObjectCollection GetRelatedClasses( string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, EnumerationOptions options) { if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); Initialize(false); IEnumWbemClassObject enumWbem = null; EnumerationOptions o = (null != options) ? (EnumerationOptions)options.Clone() : new EnumerationOptions(); //Ensure EnumerateDeep flag bit is turned off as it's invalid for queries o.EnumerateDeep = true; RelatedObjectQuery q = new RelatedObjectQuery(true, Path.Path, relatedClass, relationshipClass, relatedQualifier, relationshipQualifier, relatedRole, thisRole); SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; try { securityHandler = Scope.GetSecurityHandler(); status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecQuery_( q.QueryLanguage, q.QueryString, o.Flags, o.GetContext(), ref enumWbem); } finally { if (securityHandler != null) securityHandler.Reset(); } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } //Create collection object return new ManagementObjectCollection(Scope, o, enumWbem); } /// <summary> /// <para> Retrieves classes /// related to the WMI class, asynchronously.</para> /// </summary> /// <param name='watcher'>The object to handle the asynchronous operation's progress. </param> public void GetRelatedClasses( ManagementOperationObserver watcher) { GetRelatedClasses(watcher, (string)null); } /// <summary> /// <para> Retrieves classes related to the WMI class, asynchronously, given the related /// class name.</para> /// </summary> /// <param name='watcher'>The object to handle the asynchronous operation's progress. </param> /// <param name=' relatedClass'>The name of the related class.</param> public void GetRelatedClasses( ManagementOperationObserver watcher, string relatedClass) { GetRelatedClasses(watcher, relatedClass, null, null, null, null, null, null); } /// <summary> /// <para> Retrieves classes related to the /// WMI class, asynchronously, using the specified options.</para> /// </summary> /// <param name='watcher'>Handler for progress and results of the asynchronous operation.</param> /// <param name=' relatedClass'><para>The class from which resulting classes have to be derived.</para></param> /// <param name=' relationshipClass'> The relationship type which resulting classes must have with the source class.</param> /// <param name=' relationshipQualifier'>This qualifier must be present on the relationship.</param> /// <param name=' relatedQualifier'>This qualifier must be present on the resulting classes.</param> /// <param name=' relatedRole'>The resulting classes must have this role in the relationship.</param> /// <param name=' thisRole'>The source class must have this role in the relationship.</param> /// <param name=' options'>The options for retrieving the resulting classes.</param> public void GetRelatedClasses( ManagementOperationObserver watcher, string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, EnumerationOptions options) { if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); Initialize(true); if (null == watcher) throw new ArgumentNullException(nameof(watcher)); else { EnumerationOptions o = (null != options) ? (EnumerationOptions)options.Clone() : new EnumerationOptions(); //Ensure EnumerateDeep flag bit is turned off as it's invalid for queries o.EnumerateDeep = true; // Ensure we switch off ReturnImmediately as this is invalid for async calls o.ReturnImmediately = false; // If someone has registered for progress, make sure we flag it if (watcher.HaveListenersForProgress) o.SendStatus = true; WmiEventSink sink = watcher.GetNewSink( Scope, o.Context); RelatedObjectQuery q = new RelatedObjectQuery(true, Path.Path, relatedClass, relationshipClass, relatedQualifier, relationshipQualifier, relatedRole, thisRole); SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; securityHandler = Scope.GetSecurityHandler(); status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecQueryAsync_( q.QueryLanguage, q.QueryString, o.Flags, o.GetContext(), sink.Stub); if (securityHandler != null) securityHandler.Reset(); if (status < 0) { watcher.RemoveSink(sink); if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } } //****************************************************** //GetRelationshipClasses //****************************************************** /// <overload> /// Retrieves relationship /// classes that relate the class to others. /// </overload> /// <summary> /// <para>Retrieves relationship classes that relate the class to others.</para> /// </summary> /// <returns> /// <para>A collection of association classes /// that relate the class to any other class.</para> /// </returns> public ManagementObjectCollection GetRelationshipClasses() { return GetRelationshipClasses((string)null); } /// <summary> /// <para>Retrieves relationship classes that relate the class to others, where the /// endpoint class is the specified class.</para> /// </summary> /// <param name='relationshipClass'>The endpoint class for all relationship classes returned.</param> /// <returns> /// <para>A collection of association classes /// that relate the class to the specified class.</para> /// </returns> public ManagementObjectCollection GetRelationshipClasses( string relationshipClass) { return GetRelationshipClasses(relationshipClass, null, null, null); } /// <summary> /// <para> Retrieves relationship classes that relate this class to others, according to /// specified options.</para> /// </summary> /// <param name='relationshipClass'><para> All resulting relationship classes must derive from this class.</para></param> /// <param name=' relationshipQualifier'>Resulting relationship classes must have this qualifier.</param> /// <param name=' thisRole'>The source class must have this role in the resulting relationship classes.</param> /// <param name=' options'>Specifies options for retrieving the results.</param> /// <returns> /// <para>A collection of association classes /// that relate this class to others, according to the specified options.</para> /// </returns> public ManagementObjectCollection GetRelationshipClasses( string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options) { if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); Initialize(false); IEnumWbemClassObject enumWbem = null; EnumerationOptions o = (null != options) ? options : new EnumerationOptions(); //Ensure EnumerateDeep flag is turned off as it's invalid for queries o.EnumerateDeep = true; RelationshipQuery q = new RelationshipQuery(true, Path.Path, relationshipClass, relationshipQualifier, thisRole); SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; //Execute WMI query try { securityHandler = Scope.GetSecurityHandler(); status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecQuery_( q.QueryLanguage, q.QueryString, o.Flags, o.GetContext(), ref enumWbem); } finally { if (securityHandler != null) securityHandler.Reset(); } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } //Create collection object return new ManagementObjectCollection(Scope, o, enumWbem); } /// <summary> /// <para>Retrieves relationship classes that relate the class to others, /// asynchronously.</para> /// </summary> /// <param name='watcher'>The object to handle the asynchronous operation's progress. </param> public void GetRelationshipClasses( ManagementOperationObserver watcher) { GetRelationshipClasses(watcher, (string)null); } /// <summary> /// <para>Retrieves relationship classes that relate the class to the specified WMI class, /// asynchronously.</para> /// </summary> /// <param name='watcher'>The object to handle the asynchronous operation's progress. </param> /// <param name=' relationshipClass'>The WMI class to which all returned relationships should point.</param> public void GetRelationshipClasses( ManagementOperationObserver watcher, string relationshipClass) { GetRelationshipClasses(watcher, relationshipClass, null, null, null); } /// <summary> /// <para>Retrieves relationship classes that relate the class according to the specified /// options, asynchronously.</para> /// </summary> /// <param name='watcher'>The handler for progress and results of the asynchronous operation.</param> /// <param name='relationshipClass'><para>The class from which all resulting relationship classes must derive.</para></param> /// <param name=' relationshipQualifier'>The qualifier which the resulting relationship classes must have.</param> /// <param name=' thisRole'>The role which the source class must have in the resulting relationship classes.</param> /// <param name=' options'> The options for retrieving the results.</param> public void GetRelationshipClasses( ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, EnumerationOptions options) { if ((null == Path) || (null == Path.Path) || (0 == Path.Path.Length)) throw new InvalidOperationException(); if (null == watcher) throw new ArgumentNullException(nameof(watcher)); else { Initialize(true); EnumerationOptions o = (null != options) ? (EnumerationOptions)options.Clone() : new EnumerationOptions(); //Ensure EnumerateDeep flag is turned off as it's invalid for queries o.EnumerateDeep = true; // Ensure we switch off ReturnImmediately as this is invalid for async calls o.ReturnImmediately = false; // If someone has registered for progress, make sure we flag it if (watcher.HaveListenersForProgress) o.SendStatus = true; WmiEventSink sink = watcher.GetNewSink(Scope, o.Context); RelationshipQuery q = new RelationshipQuery(true, Path.Path, relationshipClass, relationshipQualifier, thisRole); SecurityHandler securityHandler = null; int status = (int)ManagementStatus.NoError; securityHandler = Scope.GetSecurityHandler(); status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecQueryAsync_( q.QueryLanguage, q.QueryString, o.Flags, o.GetContext(), sink.Stub); if (securityHandler != null) securityHandler.Reset(); if (status < 0) { watcher.RemoveSink(sink); if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } } /// <overload> /// <para>Generates a strongly-typed class for a given WMI class.</para> /// </overload> /// <summary> /// <para>Generates a strongly-typed class for a given WMI class.</para> /// </summary> /// <param name='includeSystemClassInClassDef'><see langword='true'/> if the class for managing system properties must be included; otherwise, <see langword='false'/>.</param> /// <param name='systemPropertyClass'><see langword='true'/> if the generated class will manage system properties; otherwise, <see langword='false'/>.</param> /// <returns> /// <para>A <see cref='System.CodeDom.CodeTypeDeclaration'/> instance /// representing the declaration for the strongly-typed class.</para> /// </returns> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// using System.CodeDom; /// using System.IO; /// using System.CodeDom.Compiler; /// using Microsoft.CSharp; /// /// void GenerateCSharpCode() /// { /// string strFilePath = "C:\\temp\\LogicalDisk.cs"; /// CodeTypeDeclaration ClsDom; /// /// ManagementClass cls1 = new ManagementClass(null,"Win32_LogicalDisk",null); /// ClsDom = cls1.GetStronglyTypedClassCode(false,false); /// /// ICodeGenerator cg = (new CSharpCodeProvider()).CreateGenerator (); /// CodeNamespace cn = new CodeNamespace("TestNamespace"); /// /// // Add any imports to the code /// cn.Imports.Add (new CodeNamespaceImport("System")); /// cn.Imports.Add (new CodeNamespaceImport("System.ComponentModel")); /// cn.Imports.Add (new CodeNamespaceImport("System.Management")); /// cn.Imports.Add(new CodeNamespaceImport("System.Collections")); /// /// // Add class to the namespace /// cn.Types.Add (ClsDom); /// /// //Now create the filestream (output file) /// TextWriter tw = new StreamWriter(new /// FileStream (strFilePath,FileMode.Create)); /// /// // And write it to the file /// cg.GenerateCodeFromNamespace (cn, tw, new CodeGeneratorOptions()); /// /// tw.Close(); /// } /// </code> /// </example> public CodeTypeDeclaration GetStronglyTypedClassCode(bool includeSystemClassInClassDef, bool systemPropertyClass) { // Ensure that the object is valid Get(); ManagementClassGenerator classGen = new ManagementClassGenerator(this); return classGen.GenerateCode(includeSystemClassInClassDef, systemPropertyClass); } /// <summary> /// <para>Generates a strongly-typed class for a given WMI class. This function generates code for Visual Basic, /// C#, or JScript, depending on the input parameters.</para> /// </summary> /// <param name='lang'>The language of the code to be generated.</param> /// <param name='filePath'>The path of the file where the code is to be written.</param> /// <param name='classNamespace'>The .NET namespace into which the class should be generated. If this is empty, the namespace will be generated from the WMI namespace.</param> /// <returns> /// <para><see langword='true'/>, if the method succeeded; /// otherwise, <see langword='false'/> .</para> /// </returns> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// ManagementClass cls = new ManagementClass(null,"Win32_LogicalDisk",null,""); /// cls.GetStronglyTypedClassCode(CodeLanguage.CSharp,"C:\temp\Logicaldisk.cs",String.Empty); /// </code> /// </example> public bool GetStronglyTypedClassCode(CodeLanguage lang, string filePath, string classNamespace) { // Ensure that the object is valid Get(); ManagementClassGenerator classGen = new ManagementClassGenerator(this); return classGen.GenerateCode(lang, filePath, classNamespace); } }//ManagementClass }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Threading.Timer/ref/System.Threading.Timer.Forwards.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Threading.Timer))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Threading.TimerCallback))]
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Threading.Timer))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Threading.TimerCallback))]
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathParser.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.Xml; using System.Xml.XPath; namespace MS.Internal.Xml.XPath { internal struct XPathParser { private XPathScanner _scanner; private XPathParser(string xpathExpr) { _scanner = new XPathScanner(xpathExpr); _parseDepth = 0; } public static AstNode ParseXPathExpression(string xpathExpression) { XPathParser parser = new XPathParser(xpathExpression); AstNode result = parser.ParseExpression(null); if (parser._scanner.Kind != XPathScanner.LexKind.Eof) { throw XPathException.Create(SR.Xp_InvalidToken, parser._scanner.SourceText); } return result; } public static AstNode ParseXPathPattern(string xpathPattern) { XPathParser parser = new XPathParser(xpathPattern); AstNode result = parser.ParsePattern(); if (parser._scanner.Kind != XPathScanner.LexKind.Eof) { throw XPathException.Create(SR.Xp_InvalidToken, parser._scanner.SourceText); } return result; } // --------------- Expression Parsing ---------------------- //The recursive is like //ParseOrExpr->ParseAndExpr->ParseEqualityExpr->ParseRelationalExpr...->ParseFilterExpr->ParsePredicate->ParseExpression //So put 200 limitation here will max cause about 2000~3000 depth stack. private int _parseDepth; private const int MaxParseDepth = 200; private AstNode ParseExpression(AstNode? qyInput) { if (++_parseDepth > MaxParseDepth) { throw XPathException.Create(SR.Xp_QueryTooComplex); } AstNode result = ParseOrExpr(qyInput); --_parseDepth; return result; } //>> OrExpr ::= ( OrExpr 'or' )? AndExpr private AstNode ParseOrExpr(AstNode? qyInput) { AstNode opnd = ParseAndExpr(qyInput); do { if (!TestOp("or")) { return opnd; } NextLex(); opnd = new Operator(Operator.Op.OR, opnd, ParseAndExpr(qyInput)); } while (true); } //>> AndExpr ::= ( AndExpr 'and' )? EqualityExpr private AstNode ParseAndExpr(AstNode? qyInput) { AstNode opnd = ParseEqualityExpr(qyInput); do { if (!TestOp("and")) { return opnd; } NextLex(); opnd = new Operator(Operator.Op.AND, opnd, ParseEqualityExpr(qyInput)); } while (true); } //>> EqualityOp ::= '=' | '!=' //>> EqualityExpr ::= ( EqualityExpr EqualityOp )? RelationalExpr private AstNode ParseEqualityExpr(AstNode? qyInput) { AstNode opnd = ParseRelationalExpr(qyInput); do { Operator.Op op = ( _scanner.Kind == XPathScanner.LexKind.Eq ? Operator.Op.EQ : _scanner.Kind == XPathScanner.LexKind.Ne ? Operator.Op.NE : /*default :*/ Operator.Op.INVALID ); if (op == Operator.Op.INVALID) { return opnd; } NextLex(); opnd = new Operator(op, opnd, ParseRelationalExpr(qyInput)); } while (true); } //>> RelationalOp ::= '<' | '>' | '<=' | '>=' //>> RelationalExpr ::= ( RelationalExpr RelationalOp )? AdditiveExpr private AstNode ParseRelationalExpr(AstNode? qyInput) { AstNode opnd = ParseAdditiveExpr(qyInput); do { Operator.Op op = ( _scanner.Kind == XPathScanner.LexKind.Lt ? Operator.Op.LT : _scanner.Kind == XPathScanner.LexKind.Le ? Operator.Op.LE : _scanner.Kind == XPathScanner.LexKind.Gt ? Operator.Op.GT : _scanner.Kind == XPathScanner.LexKind.Ge ? Operator.Op.GE : /*default :*/ Operator.Op.INVALID ); if (op == Operator.Op.INVALID) { return opnd; } NextLex(); opnd = new Operator(op, opnd, ParseAdditiveExpr(qyInput)); } while (true); } //>> AdditiveOp ::= '+' | '-' //>> AdditiveExpr ::= ( AdditiveExpr AdditiveOp )? MultiplicativeExpr private AstNode ParseAdditiveExpr(AstNode? qyInput) { AstNode opnd = ParseMultiplicativeExpr(qyInput); do { Operator.Op op = ( _scanner.Kind == XPathScanner.LexKind.Plus ? Operator.Op.PLUS : _scanner.Kind == XPathScanner.LexKind.Minus ? Operator.Op.MINUS : /*default :*/ Operator.Op.INVALID ); if (op == Operator.Op.INVALID) { return opnd; } NextLex(); opnd = new Operator(op, opnd, ParseMultiplicativeExpr(qyInput)); } while (true); } //>> MultiplicativeOp ::= '*' | 'div' | 'mod' //>> MultiplicativeExpr ::= ( MultiplicativeExpr MultiplicativeOp )? UnaryExpr private AstNode ParseMultiplicativeExpr(AstNode? qyInput) { AstNode opnd = ParseUnaryExpr(qyInput); do { Operator.Op op = ( _scanner.Kind == XPathScanner.LexKind.Star ? Operator.Op.MUL : TestOp("div") ? Operator.Op.DIV : TestOp("mod") ? Operator.Op.MOD : /*default :*/ Operator.Op.INVALID ); if (op == Operator.Op.INVALID) { return opnd; } NextLex(); opnd = new Operator(op, opnd, ParseUnaryExpr(qyInput)); } while (true); } //>> UnaryExpr ::= UnionExpr | '-' UnaryExpr private AstNode ParseUnaryExpr(AstNode? qyInput) { bool minus = false; while (_scanner.Kind == XPathScanner.LexKind.Minus) { NextLex(); minus = !minus; } if (minus) { return new Operator(Operator.Op.MUL, ParseUnionExpr(qyInput), new Operand(-1)); } else { return ParseUnionExpr(qyInput); } } //>> UnionExpr ::= ( UnionExpr '|' )? PathExpr private AstNode ParseUnionExpr(AstNode? qyInput) { AstNode opnd = ParsePathExpr(qyInput); do { if (_scanner.Kind != XPathScanner.LexKind.Union) { return opnd; } NextLex(); AstNode opnd2 = ParsePathExpr(qyInput); CheckNodeSet(opnd.ReturnType); CheckNodeSet(opnd2.ReturnType); opnd = new Operator(Operator.Op.UNION, opnd, opnd2); } while (true); } private bool IsNodeType => _scanner.Prefix.Length == 0 && (_scanner.Name == "node" || _scanner.Name == "text" || _scanner.Name == "processing-instruction" || _scanner.Name == "comment"); //>> PathOp ::= '/' | '//' //>> PathExpr ::= LocationPath | //>> FilterExpr ( PathOp RelativeLocationPath )? private AstNode ParsePathExpr(AstNode? qyInput) { AstNode opnd; if (IsPrimaryExpr) { // in this moment we should distinct LocationPas vs FilterExpr (which starts from is PrimaryExpr) opnd = ParseFilterExpr(qyInput); if (_scanner.Kind == XPathScanner.LexKind.Slash) { NextLex(); opnd = ParseRelativeLocationPath(opnd); } else if (_scanner.Kind == XPathScanner.LexKind.SlashSlash) { NextLex(); opnd = ParseRelativeLocationPath(new Axis(Axis.AxisType.DescendantOrSelf, opnd)); } } else { opnd = ParseLocationPath(null); } return opnd; } //>> FilterExpr ::= PrimaryExpr | FilterExpr Predicate private AstNode ParseFilterExpr(AstNode? qyInput) { AstNode opnd = ParsePrimaryExpr(qyInput); while (_scanner.Kind == XPathScanner.LexKind.LBracket) { // opnd must be a query opnd = new Filter(opnd, ParsePredicate(opnd)); } return opnd; } //>> Predicate ::= '[' Expr ']' private AstNode ParsePredicate(AstNode qyInput) { AstNode opnd; // we have predicates. Check that input type is NodeSet CheckNodeSet(qyInput.ReturnType); PassToken(XPathScanner.LexKind.LBracket); opnd = ParseExpression(qyInput); PassToken(XPathScanner.LexKind.RBracket); return opnd; } //>> LocationPath ::= RelativeLocationPath | AbsoluteLocationPath private AstNode ParseLocationPath(AstNode? qyInput) { if (_scanner.Kind == XPathScanner.LexKind.Slash) { NextLex(); AstNode opnd = new Root(); if (IsStep(_scanner.Kind)) { opnd = ParseRelativeLocationPath(opnd); } return opnd; } else if (_scanner.Kind == XPathScanner.LexKind.SlashSlash) { NextLex(); return ParseRelativeLocationPath(new Axis(Axis.AxisType.DescendantOrSelf, new Root())); } else { return ParseRelativeLocationPath(qyInput); } } // ParseLocationPath //>> PathOp ::= '/' | '//' //>> RelativeLocationPath ::= ( RelativeLocationPath PathOp )? Step private AstNode ParseRelativeLocationPath(AstNode? qyInput) { AstNode? opnd = qyInput; do { opnd = ParseStep(opnd); if (XPathScanner.LexKind.SlashSlash == _scanner.Kind) { NextLex(); opnd = new Axis(Axis.AxisType.DescendantOrSelf, opnd); } else if (XPathScanner.LexKind.Slash == _scanner.Kind) { NextLex(); } else { break; } } while (true); return opnd; } private static bool IsStep(XPathScanner.LexKind lexKind) { return ( lexKind == XPathScanner.LexKind.Dot || lexKind == XPathScanner.LexKind.DotDot || lexKind == XPathScanner.LexKind.At || lexKind == XPathScanner.LexKind.Axe || lexKind == XPathScanner.LexKind.Star || lexKind == XPathScanner.LexKind.Name // NodeTest is also Name ); } //>> Step ::= '.' | '..' | ( AxisName '::' | '@' )? NodeTest Predicate* private AstNode ParseStep(AstNode? qyInput) { AstNode opnd; if (XPathScanner.LexKind.Dot == _scanner.Kind) { //>> '.' NextLex(); opnd = new Axis(Axis.AxisType.Self, qyInput); } else if (XPathScanner.LexKind.DotDot == _scanner.Kind) { //>> '..' NextLex(); opnd = new Axis(Axis.AxisType.Parent, qyInput); } else { //>> ( AxisName '::' | '@' )? NodeTest Predicate* Axis.AxisType axisType = Axis.AxisType.Child; switch (_scanner.Kind) { case XPathScanner.LexKind.At: //>> '@' axisType = Axis.AxisType.Attribute; NextLex(); break; case XPathScanner.LexKind.Axe: //>> AxisName '::' axisType = GetAxis(); NextLex(); break; } XPathNodeType nodeType = ( axisType == Axis.AxisType.Attribute ? XPathNodeType.Attribute : // axisType == Axis.AxisType.Namespace ? XPathNodeType.Namespace : // No Idea why it's this way but otherwise Axes doesn't work /* default: */ XPathNodeType.Element ); opnd = ParseNodeTest(qyInput, axisType, nodeType); while (XPathScanner.LexKind.LBracket == _scanner.Kind) { opnd = new Filter(opnd, ParsePredicate(opnd)); } } return opnd; } //>> NodeTest ::= NameTest | 'comment ()' | 'text ()' | 'node ()' | 'processing-instruction (' Literal ? ')' private AstNode ParseNodeTest(AstNode? qyInput, Axis.AxisType axisType, XPathNodeType nodeType) { string nodeName, nodePrefix; switch (_scanner.Kind) { case XPathScanner.LexKind.Name: if (_scanner.CanBeFunction && IsNodeType) { nodePrefix = string.Empty; nodeName = string.Empty; nodeType = ( _scanner.Name == "comment" ? XPathNodeType.Comment : _scanner.Name == "text" ? XPathNodeType.Text : _scanner.Name == "node" ? XPathNodeType.All : _scanner.Name == "processing-instruction" ? XPathNodeType.ProcessingInstruction : /* default: */ XPathNodeType.Root ); Debug.Assert(nodeType != XPathNodeType.Root); NextLex(); PassToken(XPathScanner.LexKind.LParens); if (nodeType == XPathNodeType.ProcessingInstruction) { if (_scanner.Kind != XPathScanner.LexKind.RParens) { //>> 'processing-instruction (' Literal ')' CheckToken(XPathScanner.LexKind.String); nodeName = _scanner.StringValue; NextLex(); } } PassToken(XPathScanner.LexKind.RParens); } else { nodePrefix = _scanner.Prefix; nodeName = _scanner.Name; NextLex(); if (nodeName == "*") { nodeName = string.Empty; } } break; case XPathScanner.LexKind.Star: nodePrefix = string.Empty; nodeName = string.Empty; NextLex(); break; default: throw XPathException.Create(SR.Xp_NodeSetExpected, _scanner.SourceText); } return new Axis(axisType, qyInput, nodePrefix, nodeName, nodeType); } private bool IsPrimaryExpr => _scanner.Kind == XPathScanner.LexKind.String || _scanner.Kind == XPathScanner.LexKind.Number || _scanner.Kind == XPathScanner.LexKind.Dollar || _scanner.Kind == XPathScanner.LexKind.LParens || _scanner.Kind == XPathScanner.LexKind.Name && _scanner.CanBeFunction && !IsNodeType; //>> PrimaryExpr ::= Literal | Number | VariableReference | '(' Expr ')' | FunctionCall private AstNode ParsePrimaryExpr(AstNode? qyInput) { Debug.Assert(IsPrimaryExpr); AstNode? opnd = null; switch (_scanner.Kind) { case XPathScanner.LexKind.String: opnd = new Operand(_scanner.StringValue); NextLex(); break; case XPathScanner.LexKind.Number: opnd = new Operand(_scanner.NumberValue); NextLex(); break; case XPathScanner.LexKind.Dollar: NextLex(); CheckToken(XPathScanner.LexKind.Name); opnd = new Variable(_scanner.Name, _scanner.Prefix); NextLex(); break; case XPathScanner.LexKind.LParens: NextLex(); opnd = ParseExpression(qyInput); if (opnd.Type != AstNode.AstType.ConstantOperand) { opnd = new Group(opnd); } PassToken(XPathScanner.LexKind.RParens); break; case XPathScanner.LexKind.Name: if (_scanner.CanBeFunction && !IsNodeType) { opnd = ParseMethod(null); } break; } Debug.Assert(opnd != null, "IsPrimaryExpr() was true. We should recognize this lex."); return opnd; } private AstNode ParseMethod(AstNode? qyInput) { List<AstNode> argList = new List<AstNode>(); string name = _scanner.Name; string prefix = _scanner.Prefix; PassToken(XPathScanner.LexKind.Name); PassToken(XPathScanner.LexKind.LParens); if (_scanner.Kind != XPathScanner.LexKind.RParens) { do { argList.Add(ParseExpression(qyInput)); if (_scanner.Kind == XPathScanner.LexKind.RParens) { break; } PassToken(XPathScanner.LexKind.Comma); } while (true); } PassToken(XPathScanner.LexKind.RParens); if (prefix.Length == 0) { ParamInfo? pi; if (s_functionTable.TryGetValue(name, out pi)) { int argCount = argList.Count; if (argCount < pi.Minargs) { throw XPathException.Create(SR.Xp_InvalidNumArgs, name, _scanner.SourceText); } if (pi.FType == Function.FunctionType.FuncConcat) { for (int i = 0; i < argCount; i++) { AstNode arg = (AstNode)argList[i]; if (arg.ReturnType != XPathResultType.String) { arg = new Function(Function.FunctionType.FuncString, arg); } argList[i] = arg; } } else { if (pi.Maxargs < argCount) { throw XPathException.Create(SR.Xp_InvalidNumArgs, name, _scanner.SourceText); } if (pi.ArgTypes.Length < argCount) { argCount = pi.ArgTypes.Length; // argument we have the type specified (can be < pi.Minargs) } for (int i = 0; i < argCount; i++) { AstNode arg = (AstNode)argList[i]; if ( pi.ArgTypes[i] != XPathResultType.Any && pi.ArgTypes[i] != arg.ReturnType ) { switch (pi.ArgTypes[i]) { case XPathResultType.NodeSet: if (!(arg is Variable) && !(arg is Function && arg.ReturnType == XPathResultType.Any)) { throw XPathException.Create(SR.Xp_InvalidArgumentType, name, _scanner.SourceText); } break; case XPathResultType.String: arg = new Function(Function.FunctionType.FuncString, arg); break; case XPathResultType.Number: arg = new Function(Function.FunctionType.FuncNumber, arg); break; case XPathResultType.Boolean: arg = new Function(Function.FunctionType.FuncBoolean, arg); break; } argList[i] = arg; } } } return new Function(pi.FType, argList); } } return new Function(prefix, name, argList); } // --------------- Pattern Parsing ---------------------- //>> Pattern ::= ( Pattern '|' )? LocationPathPattern private AstNode ParsePattern() { AstNode opnd = ParseLocationPathPattern(); do { if (_scanner.Kind != XPathScanner.LexKind.Union) { return opnd; } NextLex(); opnd = new Operator(Operator.Op.UNION, opnd, ParseLocationPathPattern()); } while (true); } //>> LocationPathPattern ::= '/' | RelativePathPattern | '//' RelativePathPattern | '/' RelativePathPattern //>> | IdKeyPattern (('/' | '//') RelativePathPattern)? private AstNode ParseLocationPathPattern() { AstNode? opnd = null; switch (_scanner.Kind) { case XPathScanner.LexKind.Slash: NextLex(); opnd = new Root(); if (_scanner.Kind == XPathScanner.LexKind.Eof || _scanner.Kind == XPathScanner.LexKind.Union) { return opnd; } break; case XPathScanner.LexKind.SlashSlash: NextLex(); opnd = new Axis(Axis.AxisType.DescendantOrSelf, new Root()); break; case XPathScanner.LexKind.Name: if (_scanner.CanBeFunction) { opnd = ParseIdKeyPattern(); if (opnd != null) { switch (_scanner.Kind) { case XPathScanner.LexKind.Slash: NextLex(); break; case XPathScanner.LexKind.SlashSlash: NextLex(); opnd = new Axis(Axis.AxisType.DescendantOrSelf, opnd); break; default: return opnd; } } } break; } return ParseRelativePathPattern(opnd); } //>> IdKeyPattern ::= 'id' '(' Literal ')' | 'key' '(' Literal ',' Literal ')' private AstNode? ParseIdKeyPattern() { Debug.Assert(_scanner.CanBeFunction); List<AstNode> argList = new List<AstNode>(); if (_scanner.Prefix.Length == 0) { if (_scanner.Name == "id") { ParamInfo pi = (ParamInfo)s_functionTable["id"]; NextLex(); PassToken(XPathScanner.LexKind.LParens); CheckToken(XPathScanner.LexKind.String); argList.Add(new Operand(_scanner.StringValue)); NextLex(); PassToken(XPathScanner.LexKind.RParens); return new Function(pi.FType, argList); } if (_scanner.Name == "key") { NextLex(); PassToken(XPathScanner.LexKind.LParens); CheckToken(XPathScanner.LexKind.String); argList.Add(new Operand(_scanner.StringValue)); NextLex(); PassToken(XPathScanner.LexKind.Comma); CheckToken(XPathScanner.LexKind.String); argList.Add(new Operand(_scanner.StringValue)); NextLex(); PassToken(XPathScanner.LexKind.RParens); return new Function("", "key", argList); } } return null; } //>> PathOp ::= '/' | '//' //>> RelativePathPattern ::= ( RelativePathPattern PathOp )? StepPattern private AstNode ParseRelativePathPattern(AstNode? qyInput) { AstNode opnd = ParseStepPattern(qyInput); if (XPathScanner.LexKind.SlashSlash == _scanner.Kind) { NextLex(); opnd = ParseRelativePathPattern(new Axis(Axis.AxisType.DescendantOrSelf, opnd)); } else if (XPathScanner.LexKind.Slash == _scanner.Kind) { NextLex(); opnd = ParseRelativePathPattern(opnd); } return opnd; } //>> StepPattern ::= ChildOrAttributeAxisSpecifier NodeTest Predicate* //>> ChildOrAttributeAxisSpecifier ::= @ ? | ('child' | 'attribute') '::' private AstNode ParseStepPattern(AstNode? qyInput) { AstNode opnd; Axis.AxisType axisType = Axis.AxisType.Child; switch (_scanner.Kind) { case XPathScanner.LexKind.At: //>> '@' axisType = Axis.AxisType.Attribute; NextLex(); break; case XPathScanner.LexKind.Axe: //>> AxisName '::' axisType = GetAxis(); if (axisType != Axis.AxisType.Child && axisType != Axis.AxisType.Attribute) { throw XPathException.Create(SR.Xp_InvalidToken, _scanner.SourceText); } NextLex(); break; } XPathNodeType nodeType = ( axisType == Axis.AxisType.Attribute ? XPathNodeType.Attribute : /* default: */ XPathNodeType.Element ); opnd = ParseNodeTest(qyInput, axisType, nodeType); while (XPathScanner.LexKind.LBracket == _scanner.Kind) { opnd = new Filter(opnd, ParsePredicate(opnd)); } return opnd; } // --------------- Helper methods ---------------------- private void CheckToken(XPathScanner.LexKind t) { if (_scanner.Kind != t) { throw XPathException.Create(SR.Xp_InvalidToken, _scanner.SourceText); } } private void PassToken(XPathScanner.LexKind t) { CheckToken(t); NextLex(); } private void NextLex() { _scanner.NextLex(); } private bool TestOp(string op) { return ( _scanner.Kind == XPathScanner.LexKind.Name && _scanner.Prefix.Length == 0 && _scanner.Name.Equals(op) ); } private void CheckNodeSet(XPathResultType t) { if (t != XPathResultType.NodeSet && t != XPathResultType.Any) { throw XPathException.Create(SR.Xp_NodeSetExpected, _scanner.SourceText); } } // ---------------------------------------------------------------- private static readonly XPathResultType[] s_temparray1 = Array.Empty<XPathResultType>(); private static readonly XPathResultType[] s_temparray2 = { XPathResultType.NodeSet }; private static readonly XPathResultType[] s_temparray3 = { XPathResultType.Any }; private static readonly XPathResultType[] s_temparray4 = { XPathResultType.String }; private static readonly XPathResultType[] s_temparray5 = { XPathResultType.String, XPathResultType.String }; private static readonly XPathResultType[] s_temparray6 = { XPathResultType.String, XPathResultType.Number, XPathResultType.Number }; private static readonly XPathResultType[] s_temparray7 = { XPathResultType.String, XPathResultType.String, XPathResultType.String }; private static readonly XPathResultType[] s_temparray8 = { XPathResultType.Boolean }; private static readonly XPathResultType[] s_temparray9 = { XPathResultType.Number }; private sealed class ParamInfo { private readonly Function.FunctionType _ftype; private readonly int _minargs; private readonly int _maxargs; private readonly XPathResultType[] _argTypes; public Function.FunctionType FType { get { return _ftype; } } public int Minargs { get { return _minargs; } } public int Maxargs { get { return _maxargs; } } public XPathResultType[] ArgTypes { get { return _argTypes; } } internal ParamInfo(Function.FunctionType ftype, int minargs, int maxargs, XPathResultType[] argTypes) { _ftype = ftype; _minargs = minargs; _maxargs = maxargs; _argTypes = argTypes; } } //ParamInfo private static readonly Dictionary<string, ParamInfo> s_functionTable = CreateFunctionTable(); private static Dictionary<string, ParamInfo> CreateFunctionTable() { Dictionary<string, ParamInfo> table = new Dictionary<string, ParamInfo>(36); table.Add("last", new ParamInfo(Function.FunctionType.FuncLast, 0, 0, s_temparray1)); table.Add("position", new ParamInfo(Function.FunctionType.FuncPosition, 0, 0, s_temparray1)); table.Add("name", new ParamInfo(Function.FunctionType.FuncName, 0, 1, s_temparray2)); table.Add("namespace-uri", new ParamInfo(Function.FunctionType.FuncNameSpaceUri, 0, 1, s_temparray2)); table.Add("local-name", new ParamInfo(Function.FunctionType.FuncLocalName, 0, 1, s_temparray2)); table.Add("count", new ParamInfo(Function.FunctionType.FuncCount, 1, 1, s_temparray2)); table.Add("id", new ParamInfo(Function.FunctionType.FuncID, 1, 1, s_temparray3)); table.Add("string", new ParamInfo(Function.FunctionType.FuncString, 0, 1, s_temparray3)); table.Add("concat", new ParamInfo(Function.FunctionType.FuncConcat, 2, 100, s_temparray4)); table.Add("starts-with", new ParamInfo(Function.FunctionType.FuncStartsWith, 2, 2, s_temparray5)); table.Add("contains", new ParamInfo(Function.FunctionType.FuncContains, 2, 2, s_temparray5)); table.Add("substring-before", new ParamInfo(Function.FunctionType.FuncSubstringBefore, 2, 2, s_temparray5)); table.Add("substring-after", new ParamInfo(Function.FunctionType.FuncSubstringAfter, 2, 2, s_temparray5)); table.Add("substring", new ParamInfo(Function.FunctionType.FuncSubstring, 2, 3, s_temparray6)); table.Add("string-length", new ParamInfo(Function.FunctionType.FuncStringLength, 0, 1, s_temparray4)); table.Add("normalize-space", new ParamInfo(Function.FunctionType.FuncNormalize, 0, 1, s_temparray4)); table.Add("translate", new ParamInfo(Function.FunctionType.FuncTranslate, 3, 3, s_temparray7)); table.Add("boolean", new ParamInfo(Function.FunctionType.FuncBoolean, 1, 1, s_temparray3)); table.Add("not", new ParamInfo(Function.FunctionType.FuncNot, 1, 1, s_temparray8)); table.Add("true", new ParamInfo(Function.FunctionType.FuncTrue, 0, 0, s_temparray8)); table.Add("false", new ParamInfo(Function.FunctionType.FuncFalse, 0, 0, s_temparray8)); table.Add("lang", new ParamInfo(Function.FunctionType.FuncLang, 1, 1, s_temparray4)); table.Add("number", new ParamInfo(Function.FunctionType.FuncNumber, 0, 1, s_temparray3)); table.Add("sum", new ParamInfo(Function.FunctionType.FuncSum, 1, 1, s_temparray2)); table.Add("floor", new ParamInfo(Function.FunctionType.FuncFloor, 1, 1, s_temparray9)); table.Add("ceiling", new ParamInfo(Function.FunctionType.FuncCeiling, 1, 1, s_temparray9)); table.Add("round", new ParamInfo(Function.FunctionType.FuncRound, 1, 1, s_temparray9)); return table; } private static readonly Dictionary<string, Axis.AxisType> s_AxesTable = CreateAxesTable(); private static Dictionary<string, Axis.AxisType> CreateAxesTable() { Dictionary<string, Axis.AxisType> table = new Dictionary<string, Axis.AxisType>(13); table.Add("ancestor", Axis.AxisType.Ancestor); table.Add("ancestor-or-self", Axis.AxisType.AncestorOrSelf); table.Add("attribute", Axis.AxisType.Attribute); table.Add("child", Axis.AxisType.Child); table.Add("descendant", Axis.AxisType.Descendant); table.Add("descendant-or-self", Axis.AxisType.DescendantOrSelf); table.Add("following", Axis.AxisType.Following); table.Add("following-sibling", Axis.AxisType.FollowingSibling); table.Add("namespace", Axis.AxisType.Namespace); table.Add("parent", Axis.AxisType.Parent); table.Add("preceding", Axis.AxisType.Preceding); table.Add("preceding-sibling", Axis.AxisType.PrecedingSibling); table.Add("self", Axis.AxisType.Self); return table; } private Axis.AxisType GetAxis() { Debug.Assert(_scanner.Kind == XPathScanner.LexKind.Axe); Axis.AxisType axis; if (!s_AxesTable.TryGetValue(_scanner.Name, out axis)) { throw XPathException.Create(SR.Xp_InvalidToken, _scanner.SourceText); } return axis; } } }
// 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.Xml; using System.Xml.XPath; namespace MS.Internal.Xml.XPath { internal struct XPathParser { private XPathScanner _scanner; private XPathParser(string xpathExpr) { _scanner = new XPathScanner(xpathExpr); _parseDepth = 0; } public static AstNode ParseXPathExpression(string xpathExpression) { XPathParser parser = new XPathParser(xpathExpression); AstNode result = parser.ParseExpression(null); if (parser._scanner.Kind != XPathScanner.LexKind.Eof) { throw XPathException.Create(SR.Xp_InvalidToken, parser._scanner.SourceText); } return result; } public static AstNode ParseXPathPattern(string xpathPattern) { XPathParser parser = new XPathParser(xpathPattern); AstNode result = parser.ParsePattern(); if (parser._scanner.Kind != XPathScanner.LexKind.Eof) { throw XPathException.Create(SR.Xp_InvalidToken, parser._scanner.SourceText); } return result; } // --------------- Expression Parsing ---------------------- //The recursive is like //ParseOrExpr->ParseAndExpr->ParseEqualityExpr->ParseRelationalExpr...->ParseFilterExpr->ParsePredicate->ParseExpression //So put 200 limitation here will max cause about 2000~3000 depth stack. private int _parseDepth; private const int MaxParseDepth = 200; private AstNode ParseExpression(AstNode? qyInput) { if (++_parseDepth > MaxParseDepth) { throw XPathException.Create(SR.Xp_QueryTooComplex); } AstNode result = ParseOrExpr(qyInput); --_parseDepth; return result; } //>> OrExpr ::= ( OrExpr 'or' )? AndExpr private AstNode ParseOrExpr(AstNode? qyInput) { AstNode opnd = ParseAndExpr(qyInput); do { if (!TestOp("or")) { return opnd; } NextLex(); opnd = new Operator(Operator.Op.OR, opnd, ParseAndExpr(qyInput)); } while (true); } //>> AndExpr ::= ( AndExpr 'and' )? EqualityExpr private AstNode ParseAndExpr(AstNode? qyInput) { AstNode opnd = ParseEqualityExpr(qyInput); do { if (!TestOp("and")) { return opnd; } NextLex(); opnd = new Operator(Operator.Op.AND, opnd, ParseEqualityExpr(qyInput)); } while (true); } //>> EqualityOp ::= '=' | '!=' //>> EqualityExpr ::= ( EqualityExpr EqualityOp )? RelationalExpr private AstNode ParseEqualityExpr(AstNode? qyInput) { AstNode opnd = ParseRelationalExpr(qyInput); do { Operator.Op op = ( _scanner.Kind == XPathScanner.LexKind.Eq ? Operator.Op.EQ : _scanner.Kind == XPathScanner.LexKind.Ne ? Operator.Op.NE : /*default :*/ Operator.Op.INVALID ); if (op == Operator.Op.INVALID) { return opnd; } NextLex(); opnd = new Operator(op, opnd, ParseRelationalExpr(qyInput)); } while (true); } //>> RelationalOp ::= '<' | '>' | '<=' | '>=' //>> RelationalExpr ::= ( RelationalExpr RelationalOp )? AdditiveExpr private AstNode ParseRelationalExpr(AstNode? qyInput) { AstNode opnd = ParseAdditiveExpr(qyInput); do { Operator.Op op = ( _scanner.Kind == XPathScanner.LexKind.Lt ? Operator.Op.LT : _scanner.Kind == XPathScanner.LexKind.Le ? Operator.Op.LE : _scanner.Kind == XPathScanner.LexKind.Gt ? Operator.Op.GT : _scanner.Kind == XPathScanner.LexKind.Ge ? Operator.Op.GE : /*default :*/ Operator.Op.INVALID ); if (op == Operator.Op.INVALID) { return opnd; } NextLex(); opnd = new Operator(op, opnd, ParseAdditiveExpr(qyInput)); } while (true); } //>> AdditiveOp ::= '+' | '-' //>> AdditiveExpr ::= ( AdditiveExpr AdditiveOp )? MultiplicativeExpr private AstNode ParseAdditiveExpr(AstNode? qyInput) { AstNode opnd = ParseMultiplicativeExpr(qyInput); do { Operator.Op op = ( _scanner.Kind == XPathScanner.LexKind.Plus ? Operator.Op.PLUS : _scanner.Kind == XPathScanner.LexKind.Minus ? Operator.Op.MINUS : /*default :*/ Operator.Op.INVALID ); if (op == Operator.Op.INVALID) { return opnd; } NextLex(); opnd = new Operator(op, opnd, ParseMultiplicativeExpr(qyInput)); } while (true); } //>> MultiplicativeOp ::= '*' | 'div' | 'mod' //>> MultiplicativeExpr ::= ( MultiplicativeExpr MultiplicativeOp )? UnaryExpr private AstNode ParseMultiplicativeExpr(AstNode? qyInput) { AstNode opnd = ParseUnaryExpr(qyInput); do { Operator.Op op = ( _scanner.Kind == XPathScanner.LexKind.Star ? Operator.Op.MUL : TestOp("div") ? Operator.Op.DIV : TestOp("mod") ? Operator.Op.MOD : /*default :*/ Operator.Op.INVALID ); if (op == Operator.Op.INVALID) { return opnd; } NextLex(); opnd = new Operator(op, opnd, ParseUnaryExpr(qyInput)); } while (true); } //>> UnaryExpr ::= UnionExpr | '-' UnaryExpr private AstNode ParseUnaryExpr(AstNode? qyInput) { bool minus = false; while (_scanner.Kind == XPathScanner.LexKind.Minus) { NextLex(); minus = !minus; } if (minus) { return new Operator(Operator.Op.MUL, ParseUnionExpr(qyInput), new Operand(-1)); } else { return ParseUnionExpr(qyInput); } } //>> UnionExpr ::= ( UnionExpr '|' )? PathExpr private AstNode ParseUnionExpr(AstNode? qyInput) { AstNode opnd = ParsePathExpr(qyInput); do { if (_scanner.Kind != XPathScanner.LexKind.Union) { return opnd; } NextLex(); AstNode opnd2 = ParsePathExpr(qyInput); CheckNodeSet(opnd.ReturnType); CheckNodeSet(opnd2.ReturnType); opnd = new Operator(Operator.Op.UNION, opnd, opnd2); } while (true); } private bool IsNodeType => _scanner.Prefix.Length == 0 && (_scanner.Name == "node" || _scanner.Name == "text" || _scanner.Name == "processing-instruction" || _scanner.Name == "comment"); //>> PathOp ::= '/' | '//' //>> PathExpr ::= LocationPath | //>> FilterExpr ( PathOp RelativeLocationPath )? private AstNode ParsePathExpr(AstNode? qyInput) { AstNode opnd; if (IsPrimaryExpr) { // in this moment we should distinct LocationPas vs FilterExpr (which starts from is PrimaryExpr) opnd = ParseFilterExpr(qyInput); if (_scanner.Kind == XPathScanner.LexKind.Slash) { NextLex(); opnd = ParseRelativeLocationPath(opnd); } else if (_scanner.Kind == XPathScanner.LexKind.SlashSlash) { NextLex(); opnd = ParseRelativeLocationPath(new Axis(Axis.AxisType.DescendantOrSelf, opnd)); } } else { opnd = ParseLocationPath(null); } return opnd; } //>> FilterExpr ::= PrimaryExpr | FilterExpr Predicate private AstNode ParseFilterExpr(AstNode? qyInput) { AstNode opnd = ParsePrimaryExpr(qyInput); while (_scanner.Kind == XPathScanner.LexKind.LBracket) { // opnd must be a query opnd = new Filter(opnd, ParsePredicate(opnd)); } return opnd; } //>> Predicate ::= '[' Expr ']' private AstNode ParsePredicate(AstNode qyInput) { AstNode opnd; // we have predicates. Check that input type is NodeSet CheckNodeSet(qyInput.ReturnType); PassToken(XPathScanner.LexKind.LBracket); opnd = ParseExpression(qyInput); PassToken(XPathScanner.LexKind.RBracket); return opnd; } //>> LocationPath ::= RelativeLocationPath | AbsoluteLocationPath private AstNode ParseLocationPath(AstNode? qyInput) { if (_scanner.Kind == XPathScanner.LexKind.Slash) { NextLex(); AstNode opnd = new Root(); if (IsStep(_scanner.Kind)) { opnd = ParseRelativeLocationPath(opnd); } return opnd; } else if (_scanner.Kind == XPathScanner.LexKind.SlashSlash) { NextLex(); return ParseRelativeLocationPath(new Axis(Axis.AxisType.DescendantOrSelf, new Root())); } else { return ParseRelativeLocationPath(qyInput); } } // ParseLocationPath //>> PathOp ::= '/' | '//' //>> RelativeLocationPath ::= ( RelativeLocationPath PathOp )? Step private AstNode ParseRelativeLocationPath(AstNode? qyInput) { AstNode? opnd = qyInput; do { opnd = ParseStep(opnd); if (XPathScanner.LexKind.SlashSlash == _scanner.Kind) { NextLex(); opnd = new Axis(Axis.AxisType.DescendantOrSelf, opnd); } else if (XPathScanner.LexKind.Slash == _scanner.Kind) { NextLex(); } else { break; } } while (true); return opnd; } private static bool IsStep(XPathScanner.LexKind lexKind) { return ( lexKind == XPathScanner.LexKind.Dot || lexKind == XPathScanner.LexKind.DotDot || lexKind == XPathScanner.LexKind.At || lexKind == XPathScanner.LexKind.Axe || lexKind == XPathScanner.LexKind.Star || lexKind == XPathScanner.LexKind.Name // NodeTest is also Name ); } //>> Step ::= '.' | '..' | ( AxisName '::' | '@' )? NodeTest Predicate* private AstNode ParseStep(AstNode? qyInput) { AstNode opnd; if (XPathScanner.LexKind.Dot == _scanner.Kind) { //>> '.' NextLex(); opnd = new Axis(Axis.AxisType.Self, qyInput); } else if (XPathScanner.LexKind.DotDot == _scanner.Kind) { //>> '..' NextLex(); opnd = new Axis(Axis.AxisType.Parent, qyInput); } else { //>> ( AxisName '::' | '@' )? NodeTest Predicate* Axis.AxisType axisType = Axis.AxisType.Child; switch (_scanner.Kind) { case XPathScanner.LexKind.At: //>> '@' axisType = Axis.AxisType.Attribute; NextLex(); break; case XPathScanner.LexKind.Axe: //>> AxisName '::' axisType = GetAxis(); NextLex(); break; } XPathNodeType nodeType = ( axisType == Axis.AxisType.Attribute ? XPathNodeType.Attribute : // axisType == Axis.AxisType.Namespace ? XPathNodeType.Namespace : // No Idea why it's this way but otherwise Axes doesn't work /* default: */ XPathNodeType.Element ); opnd = ParseNodeTest(qyInput, axisType, nodeType); while (XPathScanner.LexKind.LBracket == _scanner.Kind) { opnd = new Filter(opnd, ParsePredicate(opnd)); } } return opnd; } //>> NodeTest ::= NameTest | 'comment ()' | 'text ()' | 'node ()' | 'processing-instruction (' Literal ? ')' private AstNode ParseNodeTest(AstNode? qyInput, Axis.AxisType axisType, XPathNodeType nodeType) { string nodeName, nodePrefix; switch (_scanner.Kind) { case XPathScanner.LexKind.Name: if (_scanner.CanBeFunction && IsNodeType) { nodePrefix = string.Empty; nodeName = string.Empty; nodeType = ( _scanner.Name == "comment" ? XPathNodeType.Comment : _scanner.Name == "text" ? XPathNodeType.Text : _scanner.Name == "node" ? XPathNodeType.All : _scanner.Name == "processing-instruction" ? XPathNodeType.ProcessingInstruction : /* default: */ XPathNodeType.Root ); Debug.Assert(nodeType != XPathNodeType.Root); NextLex(); PassToken(XPathScanner.LexKind.LParens); if (nodeType == XPathNodeType.ProcessingInstruction) { if (_scanner.Kind != XPathScanner.LexKind.RParens) { //>> 'processing-instruction (' Literal ')' CheckToken(XPathScanner.LexKind.String); nodeName = _scanner.StringValue; NextLex(); } } PassToken(XPathScanner.LexKind.RParens); } else { nodePrefix = _scanner.Prefix; nodeName = _scanner.Name; NextLex(); if (nodeName == "*") { nodeName = string.Empty; } } break; case XPathScanner.LexKind.Star: nodePrefix = string.Empty; nodeName = string.Empty; NextLex(); break; default: throw XPathException.Create(SR.Xp_NodeSetExpected, _scanner.SourceText); } return new Axis(axisType, qyInput, nodePrefix, nodeName, nodeType); } private bool IsPrimaryExpr => _scanner.Kind == XPathScanner.LexKind.String || _scanner.Kind == XPathScanner.LexKind.Number || _scanner.Kind == XPathScanner.LexKind.Dollar || _scanner.Kind == XPathScanner.LexKind.LParens || _scanner.Kind == XPathScanner.LexKind.Name && _scanner.CanBeFunction && !IsNodeType; //>> PrimaryExpr ::= Literal | Number | VariableReference | '(' Expr ')' | FunctionCall private AstNode ParsePrimaryExpr(AstNode? qyInput) { Debug.Assert(IsPrimaryExpr); AstNode? opnd = null; switch (_scanner.Kind) { case XPathScanner.LexKind.String: opnd = new Operand(_scanner.StringValue); NextLex(); break; case XPathScanner.LexKind.Number: opnd = new Operand(_scanner.NumberValue); NextLex(); break; case XPathScanner.LexKind.Dollar: NextLex(); CheckToken(XPathScanner.LexKind.Name); opnd = new Variable(_scanner.Name, _scanner.Prefix); NextLex(); break; case XPathScanner.LexKind.LParens: NextLex(); opnd = ParseExpression(qyInput); if (opnd.Type != AstNode.AstType.ConstantOperand) { opnd = new Group(opnd); } PassToken(XPathScanner.LexKind.RParens); break; case XPathScanner.LexKind.Name: if (_scanner.CanBeFunction && !IsNodeType) { opnd = ParseMethod(null); } break; } Debug.Assert(opnd != null, "IsPrimaryExpr() was true. We should recognize this lex."); return opnd; } private AstNode ParseMethod(AstNode? qyInput) { List<AstNode> argList = new List<AstNode>(); string name = _scanner.Name; string prefix = _scanner.Prefix; PassToken(XPathScanner.LexKind.Name); PassToken(XPathScanner.LexKind.LParens); if (_scanner.Kind != XPathScanner.LexKind.RParens) { do { argList.Add(ParseExpression(qyInput)); if (_scanner.Kind == XPathScanner.LexKind.RParens) { break; } PassToken(XPathScanner.LexKind.Comma); } while (true); } PassToken(XPathScanner.LexKind.RParens); if (prefix.Length == 0) { ParamInfo? pi; if (s_functionTable.TryGetValue(name, out pi)) { int argCount = argList.Count; if (argCount < pi.Minargs) { throw XPathException.Create(SR.Xp_InvalidNumArgs, name, _scanner.SourceText); } if (pi.FType == Function.FunctionType.FuncConcat) { for (int i = 0; i < argCount; i++) { AstNode arg = (AstNode)argList[i]; if (arg.ReturnType != XPathResultType.String) { arg = new Function(Function.FunctionType.FuncString, arg); } argList[i] = arg; } } else { if (pi.Maxargs < argCount) { throw XPathException.Create(SR.Xp_InvalidNumArgs, name, _scanner.SourceText); } if (pi.ArgTypes.Length < argCount) { argCount = pi.ArgTypes.Length; // argument we have the type specified (can be < pi.Minargs) } for (int i = 0; i < argCount; i++) { AstNode arg = (AstNode)argList[i]; if ( pi.ArgTypes[i] != XPathResultType.Any && pi.ArgTypes[i] != arg.ReturnType ) { switch (pi.ArgTypes[i]) { case XPathResultType.NodeSet: if (!(arg is Variable) && !(arg is Function && arg.ReturnType == XPathResultType.Any)) { throw XPathException.Create(SR.Xp_InvalidArgumentType, name, _scanner.SourceText); } break; case XPathResultType.String: arg = new Function(Function.FunctionType.FuncString, arg); break; case XPathResultType.Number: arg = new Function(Function.FunctionType.FuncNumber, arg); break; case XPathResultType.Boolean: arg = new Function(Function.FunctionType.FuncBoolean, arg); break; } argList[i] = arg; } } } return new Function(pi.FType, argList); } } return new Function(prefix, name, argList); } // --------------- Pattern Parsing ---------------------- //>> Pattern ::= ( Pattern '|' )? LocationPathPattern private AstNode ParsePattern() { AstNode opnd = ParseLocationPathPattern(); do { if (_scanner.Kind != XPathScanner.LexKind.Union) { return opnd; } NextLex(); opnd = new Operator(Operator.Op.UNION, opnd, ParseLocationPathPattern()); } while (true); } //>> LocationPathPattern ::= '/' | RelativePathPattern | '//' RelativePathPattern | '/' RelativePathPattern //>> | IdKeyPattern (('/' | '//') RelativePathPattern)? private AstNode ParseLocationPathPattern() { AstNode? opnd = null; switch (_scanner.Kind) { case XPathScanner.LexKind.Slash: NextLex(); opnd = new Root(); if (_scanner.Kind == XPathScanner.LexKind.Eof || _scanner.Kind == XPathScanner.LexKind.Union) { return opnd; } break; case XPathScanner.LexKind.SlashSlash: NextLex(); opnd = new Axis(Axis.AxisType.DescendantOrSelf, new Root()); break; case XPathScanner.LexKind.Name: if (_scanner.CanBeFunction) { opnd = ParseIdKeyPattern(); if (opnd != null) { switch (_scanner.Kind) { case XPathScanner.LexKind.Slash: NextLex(); break; case XPathScanner.LexKind.SlashSlash: NextLex(); opnd = new Axis(Axis.AxisType.DescendantOrSelf, opnd); break; default: return opnd; } } } break; } return ParseRelativePathPattern(opnd); } //>> IdKeyPattern ::= 'id' '(' Literal ')' | 'key' '(' Literal ',' Literal ')' private AstNode? ParseIdKeyPattern() { Debug.Assert(_scanner.CanBeFunction); List<AstNode> argList = new List<AstNode>(); if (_scanner.Prefix.Length == 0) { if (_scanner.Name == "id") { ParamInfo pi = (ParamInfo)s_functionTable["id"]; NextLex(); PassToken(XPathScanner.LexKind.LParens); CheckToken(XPathScanner.LexKind.String); argList.Add(new Operand(_scanner.StringValue)); NextLex(); PassToken(XPathScanner.LexKind.RParens); return new Function(pi.FType, argList); } if (_scanner.Name == "key") { NextLex(); PassToken(XPathScanner.LexKind.LParens); CheckToken(XPathScanner.LexKind.String); argList.Add(new Operand(_scanner.StringValue)); NextLex(); PassToken(XPathScanner.LexKind.Comma); CheckToken(XPathScanner.LexKind.String); argList.Add(new Operand(_scanner.StringValue)); NextLex(); PassToken(XPathScanner.LexKind.RParens); return new Function("", "key", argList); } } return null; } //>> PathOp ::= '/' | '//' //>> RelativePathPattern ::= ( RelativePathPattern PathOp )? StepPattern private AstNode ParseRelativePathPattern(AstNode? qyInput) { AstNode opnd = ParseStepPattern(qyInput); if (XPathScanner.LexKind.SlashSlash == _scanner.Kind) { NextLex(); opnd = ParseRelativePathPattern(new Axis(Axis.AxisType.DescendantOrSelf, opnd)); } else if (XPathScanner.LexKind.Slash == _scanner.Kind) { NextLex(); opnd = ParseRelativePathPattern(opnd); } return opnd; } //>> StepPattern ::= ChildOrAttributeAxisSpecifier NodeTest Predicate* //>> ChildOrAttributeAxisSpecifier ::= @ ? | ('child' | 'attribute') '::' private AstNode ParseStepPattern(AstNode? qyInput) { AstNode opnd; Axis.AxisType axisType = Axis.AxisType.Child; switch (_scanner.Kind) { case XPathScanner.LexKind.At: //>> '@' axisType = Axis.AxisType.Attribute; NextLex(); break; case XPathScanner.LexKind.Axe: //>> AxisName '::' axisType = GetAxis(); if (axisType != Axis.AxisType.Child && axisType != Axis.AxisType.Attribute) { throw XPathException.Create(SR.Xp_InvalidToken, _scanner.SourceText); } NextLex(); break; } XPathNodeType nodeType = ( axisType == Axis.AxisType.Attribute ? XPathNodeType.Attribute : /* default: */ XPathNodeType.Element ); opnd = ParseNodeTest(qyInput, axisType, nodeType); while (XPathScanner.LexKind.LBracket == _scanner.Kind) { opnd = new Filter(opnd, ParsePredicate(opnd)); } return opnd; } // --------------- Helper methods ---------------------- private void CheckToken(XPathScanner.LexKind t) { if (_scanner.Kind != t) { throw XPathException.Create(SR.Xp_InvalidToken, _scanner.SourceText); } } private void PassToken(XPathScanner.LexKind t) { CheckToken(t); NextLex(); } private void NextLex() { _scanner.NextLex(); } private bool TestOp(string op) { return ( _scanner.Kind == XPathScanner.LexKind.Name && _scanner.Prefix.Length == 0 && _scanner.Name.Equals(op) ); } private void CheckNodeSet(XPathResultType t) { if (t != XPathResultType.NodeSet && t != XPathResultType.Any) { throw XPathException.Create(SR.Xp_NodeSetExpected, _scanner.SourceText); } } // ---------------------------------------------------------------- private static readonly XPathResultType[] s_temparray1 = Array.Empty<XPathResultType>(); private static readonly XPathResultType[] s_temparray2 = { XPathResultType.NodeSet }; private static readonly XPathResultType[] s_temparray3 = { XPathResultType.Any }; private static readonly XPathResultType[] s_temparray4 = { XPathResultType.String }; private static readonly XPathResultType[] s_temparray5 = { XPathResultType.String, XPathResultType.String }; private static readonly XPathResultType[] s_temparray6 = { XPathResultType.String, XPathResultType.Number, XPathResultType.Number }; private static readonly XPathResultType[] s_temparray7 = { XPathResultType.String, XPathResultType.String, XPathResultType.String }; private static readonly XPathResultType[] s_temparray8 = { XPathResultType.Boolean }; private static readonly XPathResultType[] s_temparray9 = { XPathResultType.Number }; private sealed class ParamInfo { private readonly Function.FunctionType _ftype; private readonly int _minargs; private readonly int _maxargs; private readonly XPathResultType[] _argTypes; public Function.FunctionType FType { get { return _ftype; } } public int Minargs { get { return _minargs; } } public int Maxargs { get { return _maxargs; } } public XPathResultType[] ArgTypes { get { return _argTypes; } } internal ParamInfo(Function.FunctionType ftype, int minargs, int maxargs, XPathResultType[] argTypes) { _ftype = ftype; _minargs = minargs; _maxargs = maxargs; _argTypes = argTypes; } } //ParamInfo private static readonly Dictionary<string, ParamInfo> s_functionTable = CreateFunctionTable(); private static Dictionary<string, ParamInfo> CreateFunctionTable() { Dictionary<string, ParamInfo> table = new Dictionary<string, ParamInfo>(36); table.Add("last", new ParamInfo(Function.FunctionType.FuncLast, 0, 0, s_temparray1)); table.Add("position", new ParamInfo(Function.FunctionType.FuncPosition, 0, 0, s_temparray1)); table.Add("name", new ParamInfo(Function.FunctionType.FuncName, 0, 1, s_temparray2)); table.Add("namespace-uri", new ParamInfo(Function.FunctionType.FuncNameSpaceUri, 0, 1, s_temparray2)); table.Add("local-name", new ParamInfo(Function.FunctionType.FuncLocalName, 0, 1, s_temparray2)); table.Add("count", new ParamInfo(Function.FunctionType.FuncCount, 1, 1, s_temparray2)); table.Add("id", new ParamInfo(Function.FunctionType.FuncID, 1, 1, s_temparray3)); table.Add("string", new ParamInfo(Function.FunctionType.FuncString, 0, 1, s_temparray3)); table.Add("concat", new ParamInfo(Function.FunctionType.FuncConcat, 2, 100, s_temparray4)); table.Add("starts-with", new ParamInfo(Function.FunctionType.FuncStartsWith, 2, 2, s_temparray5)); table.Add("contains", new ParamInfo(Function.FunctionType.FuncContains, 2, 2, s_temparray5)); table.Add("substring-before", new ParamInfo(Function.FunctionType.FuncSubstringBefore, 2, 2, s_temparray5)); table.Add("substring-after", new ParamInfo(Function.FunctionType.FuncSubstringAfter, 2, 2, s_temparray5)); table.Add("substring", new ParamInfo(Function.FunctionType.FuncSubstring, 2, 3, s_temparray6)); table.Add("string-length", new ParamInfo(Function.FunctionType.FuncStringLength, 0, 1, s_temparray4)); table.Add("normalize-space", new ParamInfo(Function.FunctionType.FuncNormalize, 0, 1, s_temparray4)); table.Add("translate", new ParamInfo(Function.FunctionType.FuncTranslate, 3, 3, s_temparray7)); table.Add("boolean", new ParamInfo(Function.FunctionType.FuncBoolean, 1, 1, s_temparray3)); table.Add("not", new ParamInfo(Function.FunctionType.FuncNot, 1, 1, s_temparray8)); table.Add("true", new ParamInfo(Function.FunctionType.FuncTrue, 0, 0, s_temparray8)); table.Add("false", new ParamInfo(Function.FunctionType.FuncFalse, 0, 0, s_temparray8)); table.Add("lang", new ParamInfo(Function.FunctionType.FuncLang, 1, 1, s_temparray4)); table.Add("number", new ParamInfo(Function.FunctionType.FuncNumber, 0, 1, s_temparray3)); table.Add("sum", new ParamInfo(Function.FunctionType.FuncSum, 1, 1, s_temparray2)); table.Add("floor", new ParamInfo(Function.FunctionType.FuncFloor, 1, 1, s_temparray9)); table.Add("ceiling", new ParamInfo(Function.FunctionType.FuncCeiling, 1, 1, s_temparray9)); table.Add("round", new ParamInfo(Function.FunctionType.FuncRound, 1, 1, s_temparray9)); return table; } private static readonly Dictionary<string, Axis.AxisType> s_AxesTable = CreateAxesTable(); private static Dictionary<string, Axis.AxisType> CreateAxesTable() { Dictionary<string, Axis.AxisType> table = new Dictionary<string, Axis.AxisType>(13); table.Add("ancestor", Axis.AxisType.Ancestor); table.Add("ancestor-or-self", Axis.AxisType.AncestorOrSelf); table.Add("attribute", Axis.AxisType.Attribute); table.Add("child", Axis.AxisType.Child); table.Add("descendant", Axis.AxisType.Descendant); table.Add("descendant-or-self", Axis.AxisType.DescendantOrSelf); table.Add("following", Axis.AxisType.Following); table.Add("following-sibling", Axis.AxisType.FollowingSibling); table.Add("namespace", Axis.AxisType.Namespace); table.Add("parent", Axis.AxisType.Parent); table.Add("preceding", Axis.AxisType.Preceding); table.Add("preceding-sibling", Axis.AxisType.PrecedingSibling); table.Add("self", Axis.AxisType.Self); return table; } private Axis.AxisType GetAxis() { Debug.Assert(_scanner.Kind == XPathScanner.LexKind.Axe); Axis.AxisType axis; if (!s_AxesTable.TryGetValue(_scanner.Name, out axis)) { throw XPathException.Create(SR.Xp_InvalidToken, _scanner.SourceText); } return axis; } } }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/tests/baseservices/threading/generics/threadstart/thread17.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; interface IGen { void Target<U>(); } struct Gen : IGen { public void Target<U>() { //dummy line to avoid warnings Test_thread17.Eval(typeof(U)!=null); Interlocked.Increment(ref Test_thread17.Xcounter); } public static void ThreadPoolTest<U>() { Thread[] threads = new Thread[Test_thread17.nThreads]; IGen obj = new Gen(); for (int i = 0; i < Test_thread17.nThreads; i++) { threads[i] = new Thread(new ThreadStart(obj.Target<U>)); threads[i].Start(); } for (int i = 0; i < Test_thread17.nThreads; i++) { threads[i].Join(); } Test_thread17.Eval(Test_thread17.Xcounter==Test_thread17.nThreads); Test_thread17.Xcounter = 0; } } public class Test_thread17 { public static int nThreads =50; public static int counter = 0; public static int Xcounter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { Gen.ThreadPoolTest<object>(); Gen.ThreadPoolTest<string>(); Gen.ThreadPoolTest<Guid>(); Gen.ThreadPoolTest<int>(); Gen.ThreadPoolTest<double>(); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; interface IGen { void Target<U>(); } struct Gen : IGen { public void Target<U>() { //dummy line to avoid warnings Test_thread17.Eval(typeof(U)!=null); Interlocked.Increment(ref Test_thread17.Xcounter); } public static void ThreadPoolTest<U>() { Thread[] threads = new Thread[Test_thread17.nThreads]; IGen obj = new Gen(); for (int i = 0; i < Test_thread17.nThreads; i++) { threads[i] = new Thread(new ThreadStart(obj.Target<U>)); threads[i].Start(); } for (int i = 0; i < Test_thread17.nThreads; i++) { threads[i].Join(); } Test_thread17.Eval(Test_thread17.Xcounter==Test_thread17.nThreads); Test_thread17.Xcounter = 0; } } public class Test_thread17 { public static int nThreads =50; public static int counter = 0; public static int Xcounter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { Gen.ThreadPoolTest<object>(); Gen.ThreadPoolTest<string>(); Gen.ThreadPoolTest<Guid>(); Gen.ThreadPoolTest<int>(); Gen.ThreadPoolTest<double>(); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
-1
dotnet/runtime
66,292
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete
Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
rzikm
2022-03-07T12:54:44Z
2022-03-08T17:44:17Z
627851323fe8f15539c163aabd7d7c644766c549
00ed84ae9ba5c68ada6041ca4aa8083cc89e0669
Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545 I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome.
./src/tests/JIT/Performance/CodeQuality/Bytemark/neuraljagged.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /* ** This program was translated to C# and adapted for xunit-performance. ** New variants of several tests were added to compare class versus ** struct and to compare jagged arrays vs multi-dimensional arrays. */ /* ** BYTEmark (tm) ** BYTE Magazine's Native Mode benchmarks ** Rick Grehan, BYTE Magazine ** ** Create: ** Revision: 3/95 ** ** DISCLAIMER ** The source, executable, and documentation files that comprise ** the BYTEmark benchmarks are made available on an "as is" basis. ** This means that we at BYTE Magazine have made every reasonable ** effort to verify that the there are no errors in the source and ** executable code. We cannot, however, guarantee that the programs ** are error-free. Consequently, McGraw-HIll and BYTE Magazine make ** no claims in regard to the fitness of the source code, executable ** code, and documentation of the BYTEmark. ** ** Furthermore, BYTE Magazine, McGraw-Hill, and all employees ** of McGraw-Hill cannot be held responsible for any damages resulting ** from the use of this code or the results obtained from using ** this code. */ /******************************** ** BACK PROPAGATION NEURAL NET ** ********************************* ** This code is a modified version of the code ** that was submitted to BYTE Magazine by ** Maureen Caudill. It accomanied an article ** that I CANNOT NOW RECALL. ** The author's original heading/comment was ** as follows: ** ** Backpropagation Network ** Written by Maureen Caudill ** in Think C 4.0 on a Macintosh ** ** (c) Maureen Caudill 1988-1991 ** This network will accept 5x7 input patterns ** and produce 8 bit output patterns. ** The source code may be copied or modified without restriction, ** but no fee may be charged for its use. ** ** ++++++++++++++ ** I have modified the code so that it will work ** on systems other than a Macintosh -- RG */ /*********** ** DoNNet ** ************ ** Perform the neural net benchmark. ** Note that this benchmark is one of the few that ** requires an input file. That file is "NNET.DAT" and ** should be on the local directory (from which the ** benchmark program in launched). */ using System; using System.IO; public class NeuralJagged : NNetStruct { public override string Name() { return "NEURAL NET(jagged)"; } /* ** DEFINES */ public static int T = 1; /* TRUE */ public static int F = 0; /* FALSE */ public static int ERR = -1; public static int MAXPATS = 10; /* max number of patterns in data file */ public static int IN_X_SIZE = 5; /* number of neurodes/row of input layer */ public static int IN_Y_SIZE = 7; /* number of neurodes/col of input layer */ public static int IN_SIZE = 35; /* equals IN_X_SIZE*IN_Y_SIZE */ public static int MID_SIZE = 8; /* number of neurodes in middle layer */ public static int OUT_SIZE = 8; /* number of neurodes in output layer */ public static double MARGIN = 0.1; /* how near to 1,0 do we have to come to stop? */ public static double BETA = 0.09; /* beta learning constant */ public static double ALPHA = 0.09; /* momentum term constant */ public static double STOP = 0.1; /* when worst_error less than STOP, training is done */ /* ** MAXNNETLOOPS ** ** This constant sets the max number of loops through the neural ** net that the system will attempt before giving up. This ** is not a critical constant. You can alter it if your system ** has sufficient horsepower. */ public static int MAXNNETLOOPS = 50000; /* ** GLOBALS */ public static double[][] mid_wts = new double[MID_SIZE][]; public static double[][] out_wts = new double[OUT_SIZE][]; public static double[] mid_out = new double[MID_SIZE]; public static double[] out_out = new double[OUT_SIZE]; public static double[] mid_error = new double[MID_SIZE]; public static double[] out_error = new double[OUT_SIZE]; public static double[][] mid_wt_change = new double[MID_SIZE][]; public static double[][] out_wt_change = new double[OUT_SIZE][]; public static double[][] in_pats = new double[MAXPATS][]; public static double[][] out_pats = new double[MAXPATS][]; public static double[] tot_out_error = new double[MAXPATS]; public static double[][] out_wt_cum_change = new double[OUT_SIZE][]; public static double[][] mid_wt_cum_change = new double[MID_SIZE][]; public static double worst_error = 0.0; /* worst error each pass through the data */ public static double average_error = 0.0; /* average error each pass through the data */ public static double[] avg_out_error = new double[MAXPATS]; public static int iteration_count = 0; /* number of passes thru network so far */ public static int numpats = 0; /* number of patterns in data file */ public static int numpasses = 0; /* number of training passes through data file */ public static int learned = 0; /* flag--if TRUE, network has learned all patterns */ /* ** The Neural Net test requires an input data file. ** The name is specified here. */ public static string inpath = "NNET.DAT"; public static void Init() { for (int i = 0; i < MID_SIZE; i++) { mid_wts[i] = new double[IN_SIZE]; mid_wt_cum_change[i] = new double[IN_SIZE]; mid_wt_change[i] = new double[IN_SIZE]; } for (int i = 0; i < OUT_SIZE; i++) { out_wt_change[i] = new double[MID_SIZE]; out_wts[i] = new double[MID_SIZE]; out_wt_cum_change[i] = new double[MID_SIZE]; } for (int i = 0; i < MAXPATS; i++) { in_pats[i] = new double[IN_SIZE]; out_pats[i] = new double[OUT_SIZE]; } } public override double Run() { Init(); return DoNNET(this); } /********************* ** read_data_file() ** ********************** ** Read in the input data file and store the patterns in ** in_pats and out_pats. ** The format for the data file is as follows: ** ** line# data expected ** ----- ------------------------------ ** 1 In-X-size,in-y-size,out-size ** 2 number of patterns in file ** 3 1st X row of 1st input pattern ** 4.. following rows of 1st input pattern pattern ** in-x+2 y-out pattern ** 1st X row of 2nd pattern ** etc. ** ** Each row of data is separated by commas or spaces. ** The data is expected to be ascii text corresponding to ** either a +1 or a 0. ** ** Sample input for a 1-pattern file (The comments to the ** right may NOT be in the file unless more sophisticated ** parsing of the input is done.): ** ** 5,7,8 input is 5x7 grid, output is 8 bits ** 1 one pattern in file ** 0,1,1,1,0 beginning of pattern for "O" ** 1,0,0,0,1 ** 1,0,0,0,1 ** 1,0,0,0,1 ** 1,0,0,0,1 ** 1,0,0,0,0 ** 0,1,1,1,0 ** 0,1,0,0,1,1,1,1 ASCII code for "O" -- 0100 1111 ** ** Clearly, this simple scheme can be expanded or enhanced ** any way you like. ** ** Returns -1 if any file error occurred, otherwise 0. **/ private void read_data_file() { int xinsize = 0, yinsize = 0, youtsize = 0; int patt = 0, element = 0, i = 0, row = 0; int vals_read = 0; int val1 = 0, val2 = 0, val3 = 0, val4 = 0, val5 = 0, val6 = 0, val7 = 0, val8 = 0; Object[] results = new Object[8]; string input = NeuralData.Input; StringReader infile = new StringReader(input); vals_read = Utility.fscanf(infile, "%d %d %d", results); xinsize = (int)results[0]; yinsize = (int)results[1]; youtsize = (int)results[2]; if (vals_read != 3) { throw new Exception("NNET: error reading input"); } vals_read = Utility.fscanf(infile, "%d", results); numpats = (int)results[0]; if (vals_read != 1) { throw new Exception("NNET: error reading input"); } if (numpats > MAXPATS) numpats = MAXPATS; for (patt = 0; patt < numpats; patt++) { element = 0; for (row = 0; row < yinsize; row++) { vals_read = Utility.fscanf(infile, "%d %d %d %d %d", results); val1 = (int)results[0]; val2 = (int)results[1]; val3 = (int)results[2]; val4 = (int)results[3]; val5 = (int)results[4]; if (vals_read != 5) { throw new Exception("NNET: error reading input"); } element = row * xinsize; in_pats[patt][element] = (double)val1; element++; in_pats[patt][element] = (double)val2; element++; in_pats[patt][element] = (double)val3; element++; in_pats[patt][element] = (double)val4; element++; in_pats[patt][element] = (double)val5; element++; } for (i = 0; i < IN_SIZE; i++) { if (in_pats[patt][i] >= 0.9) in_pats[patt][i] = 0.9; if (in_pats[patt][i] <= 0.1) in_pats[patt][i] = 0.1; } element = 0; vals_read = Utility.fscanf(infile, "%d %d %d %d %d %d %d %d", results); val1 = (int)results[0]; val2 = (int)results[1]; val3 = (int)results[2]; val4 = (int)results[3]; val5 = (int)results[4]; val6 = (int)results[5]; val7 = (int)results[6]; val8 = (int)results[7]; out_pats[patt][element] = (double)val1; element++; out_pats[patt][element] = (double)val2; element++; out_pats[patt][element] = (double)val3; element++; out_pats[patt][element] = (double)val4; element++; out_pats[patt][element] = (double)val5; element++; out_pats[patt][element] = (double)val6; element++; out_pats[patt][element] = (double)val7; element++; out_pats[patt][element] = (double)val8; element++; } } private double DoNNET(NNetStruct locnnetstruct) { // string errorcontext = "CPU:NNET"; // int systemerror = 0; long accumtime = 0; double iterations = 0.0; /* ** Init random number generator. ** NOTE: It is important that the random number generator ** be re-initialized for every pass through this test. ** The NNET algorithm uses the random number generator ** to initialize the net. Results are sensitive to ** the initial neural net state. */ ByteMark.randnum(3); /* ** Read in the input and output patterns. We'll do this ** only once here at the beginning. These values don't ** change once loaded. */ read_data_file(); /* ** See if we need to perform self adjustment loop. */ if (locnnetstruct.adjust == 0) { /* ** Do self-adjustment. This involves initializing the ** # of loops and increasing the loop count until we ** get a number of loops that we can use. */ for (locnnetstruct.loops = 1; locnnetstruct.loops < MAXNNETLOOPS; locnnetstruct.loops++) { ByteMark.randnum(3); if (DoNNetIteration(locnnetstruct.loops) > global.min_ticks) break; } } /* ** All's well if we get here. Do the test. */ accumtime = 0L; iterations = (double)0.0; do { ByteMark.randnum(3); /* Gotta do this for Neural Net */ accumtime += DoNNetIteration(locnnetstruct.loops); iterations += (double)locnnetstruct.loops; } while (ByteMark.TicksToSecs(accumtime) < locnnetstruct.request_secs); /* ** Clean up, calculate results, and go home. Be sure to ** show that we don't have to rerun adjustment code. */ locnnetstruct.iterspersec = iterations / ByteMark.TicksToFracSecs(accumtime); if (locnnetstruct.adjust == 0) locnnetstruct.adjust = 1; return locnnetstruct.iterspersec; } /******************** ** DoNNetIteration ** ********************* ** Do a single iteration of the neural net benchmark. ** By iteration, we mean a "learning" pass. */ public static long DoNNetIteration(long nloops) { long elapsed; /* Elapsed time */ int patt; /* ** Run nloops learning cycles. Notice that, counted with ** the learning cycle is the weight randomization and ** zeroing of changes. This should reduce clock jitter, ** since we don't have to stop and start the clock for ** each iteration. */ elapsed = ByteMark.StartStopwatch(); while (nloops-- != 0) { randomize_wts(); zero_changes(); iteration_count = 1; learned = F; numpasses = 0; while (learned == F) { for (patt = 0; patt < numpats; patt++) { worst_error = 0.0; /* reset this every pass through data */ move_wt_changes(); /* move last pass's wt changes to momentum array */ do_forward_pass(patt); do_back_pass(patt); iteration_count++; } numpasses++; learned = check_out_error(); } } return (ByteMark.StopStopwatch(elapsed)); } /************************* ** do_mid_forward(patt) ** ************************** ** Process the middle layer's forward pass ** The activation of middle layer's neurode is the weighted ** sum of the inputs from the input pattern, with sigmoid ** function applied to the inputs. **/ public static void do_mid_forward(int patt) { double sum; int neurode, i; for (neurode = 0; neurode < MID_SIZE; neurode++) { sum = 0.0; for (i = 0; i < IN_SIZE; i++) { /* compute weighted sum of input signals */ sum += mid_wts[neurode][i] * in_pats[patt][i]; } /* ** apply sigmoid function f(x) = 1/(1+exp(-x)) to weighted sum */ sum = 1.0 / (1.0 + Math.Exp(-sum)); mid_out[neurode] = sum; } return; } /********************* ** do_out_forward() ** ********************** ** process the forward pass through the output layer ** The activation of the output layer is the weighted sum of ** the inputs (outputs from middle layer), modified by the ** sigmoid function. **/ public static void do_out_forward() { double sum; int neurode, i; for (neurode = 0; neurode < OUT_SIZE; neurode++) { sum = 0.0; for (i = 0; i < MID_SIZE; i++) { /* ** compute weighted sum of input signals ** from middle layer */ sum += out_wts[neurode][i] * mid_out[i]; } /* ** Apply f(x) = 1/(1+Math.Exp(-x)) to weighted input */ sum = 1.0 / (1.0 + Math.Exp(-sum)); out_out[neurode] = sum; } return; } /************************* ** display_output(patt) ** ************************** ** Display the actual output vs. the desired output of the ** network. ** Once the training is complete, and the "learned" flag set ** to TRUE, then display_output sends its output to both ** the screen and to a text output file. ** ** NOTE: This routine has been disabled in the benchmark ** version. -- RG **/ /* public static void display_output(int patt) { int i; fprintf(outfile,"\n Iteration # %d",iteration_count); fprintf(outfile,"\n Desired Output: "); for (i=0; i<OUT_SIZE; i++) { fprintf(outfile,"%6.3f ",out_pats[patt][i]); } fprintf(outfile,"\n Actual Output: "); for (i=0; i<OUT_SIZE; i++) { fprintf(outfile,"%6.3f ",out_out[i]); } fprintf(outfile,"\n"); return; } */ /********************** ** do_forward_pass() ** *********************** ** control function for the forward pass through the network ** NOTE: I have disabled the call to display_output() in ** the benchmark version -- RG. **/ public static void do_forward_pass(int patt) { do_mid_forward(patt); /* process forward pass, middle layer */ do_out_forward(); /* process forward pass, output layer */ /* display_output(patt); ** display results of forward pass */ return; } /*********************** ** do_out_error(patt) ** ************************ ** Compute the error for the output layer neurodes. ** This is simply Desired - Actual. **/ public static void do_out_error(int patt) { int neurode; double error, tot_error, sum; tot_error = 0.0; sum = 0.0; for (neurode = 0; neurode < OUT_SIZE; neurode++) { out_error[neurode] = out_pats[patt][neurode] - out_out[neurode]; /* ** while we're here, also compute magnitude ** of total error and worst error in this pass. ** We use these to decide if we are done yet. */ error = out_error[neurode]; if (error < 0.0) { sum += -error; if (-error > tot_error) tot_error = -error; /* worst error this pattern */ } else { sum += error; if (error > tot_error) tot_error = error; /* worst error this pattern */ } } avg_out_error[patt] = sum / OUT_SIZE; tot_out_error[patt] = tot_error; return; } /*********************** ** worst_pass_error() ** ************************ ** Find the worst and average error in the pass and save it **/ public static void worst_pass_error() { double error, sum; int i; error = 0.0; sum = 0.0; for (i = 0; i < numpats; i++) { if (tot_out_error[i] > error) error = tot_out_error[i]; sum += avg_out_error[i]; } worst_error = error; average_error = sum / numpats; return; } /******************* ** do_mid_error() ** ******************** ** Compute the error for the middle layer neurodes ** This is based on the output errors computed above. ** Note that the derivative of the sigmoid f(x) is ** f'(x) = f(x)(1 - f(x)) ** Recall that f(x) is merely the output of the middle ** layer neurode on the forward pass. **/ public static void do_mid_error() { double sum; int neurode, i; for (neurode = 0; neurode < MID_SIZE; neurode++) { sum = 0.0; for (i = 0; i < OUT_SIZE; i++) sum += out_wts[i][neurode] * out_error[i]; /* ** apply the derivative of the sigmoid here ** Because of the choice of sigmoid f(I), the derivative ** of the sigmoid is f'(I) = f(I)(1 - f(I)) */ mid_error[neurode] = mid_out[neurode] * (1 - mid_out[neurode]) * sum; } return; } /********************* ** adjust_out_wts() ** ********************** ** Adjust the weights of the output layer. The error for ** the output layer has been previously propagated back to ** the middle layer. ** Use the Delta Rule with momentum term to adjust the weights. **/ public static void adjust_out_wts() { int weight, neurode; double learn, delta, alph; learn = BETA; alph = ALPHA; for (neurode = 0; neurode < OUT_SIZE; neurode++) { for (weight = 0; weight < MID_SIZE; weight++) { /* standard delta rule */ delta = learn * out_error[neurode] * mid_out[weight]; /* now the momentum term */ delta += alph * out_wt_change[neurode][weight]; out_wts[neurode][weight] += delta; /* keep track of this pass's cum wt changes for next pass's momentum */ out_wt_cum_change[neurode][weight] += delta; } } return; } /************************* ** adjust_mid_wts(patt) ** ************************** ** Adjust the middle layer weights using the previously computed ** errors. ** We use the Generalized Delta Rule with momentum term **/ public static void adjust_mid_wts(int patt) { int weight, neurode; double learn, alph, delta; learn = BETA; alph = ALPHA; for (neurode = 0; neurode < MID_SIZE; neurode++) { for (weight = 0; weight < IN_SIZE; weight++) { /* first the basic delta rule */ delta = learn * mid_error[neurode] * in_pats[patt][weight]; /* with the momentum term */ delta += alph * mid_wt_change[neurode][weight]; mid_wts[neurode][weight] += delta; /* keep track of this pass's cum wt changes for next pass's momentum */ mid_wt_cum_change[neurode][weight] += delta; } } return; } /******************* ** do_back_pass() ** ******************** ** Process the backward propagation of error through network. **/ public static void do_back_pass(int patt) { do_out_error(patt); do_mid_error(); adjust_out_wts(); adjust_mid_wts(patt); return; } /********************** ** move_wt_changes() ** *********************** ** Move the weight changes accumulated last pass into the wt-change ** array for use by the momentum term in this pass. Also zero out ** the accumulating arrays after the move. **/ public static void move_wt_changes() { int i, j; for (i = 0; i < MID_SIZE; i++) for (j = 0; j < IN_SIZE; j++) { mid_wt_change[i][j] = mid_wt_cum_change[i][j]; /* ** Zero it out for next pass accumulation. */ mid_wt_cum_change[i][j] = 0.0; } for (i = 0; i < OUT_SIZE; i++) for (j = 0; j < MID_SIZE; j++) { out_wt_change[i][j] = out_wt_cum_change[i][j]; out_wt_cum_change[i][j] = 0.0; } return; } /********************** ** check_out_error() ** *********************** ** Check to see if the error in the output layer is below ** MARGIN*OUT_SIZE for all output patterns. If so, then ** assume the network has learned acceptably well. This ** is simply an arbitrary measure of how well the network ** has learned -- many other standards are possible. **/ public static int check_out_error() { int result, i, error; result = T; error = F; worst_pass_error(); /* identify the worst error in this pass */ for (i = 0; i < numpats; i++) { if (worst_error >= STOP) result = F; if (tot_out_error[i] >= 16.0) error = T; } if (error == T) result = ERR; return (result); } /******************* ** zero_changes() ** ******************** ** Zero out all the wt change arrays **/ public static void zero_changes() { int i, j; for (i = 0; i < MID_SIZE; i++) { for (j = 0; j < IN_SIZE; j++) { mid_wt_change[i][j] = 0.0; mid_wt_cum_change[i][j] = 0.0; } } for (i = 0; i < OUT_SIZE; i++) { for (j = 0; j < MID_SIZE; j++) { out_wt_change[i][j] = 0.0; out_wt_cum_change[i][j] = 0.0; } } return; } /******************** ** randomize_wts() ** ********************* ** Intialize the weights in the middle and output layers to ** random values between -0.25..+0.25 ** Function rand() returns a value between 0 and 32767. ** ** NOTE: Had to make alterations to how the random numbers were ** created. -- RG. **/ public static void randomize_wts() { int neurode, i; double value; /* ** Following not used int benchmark version -- RG ** ** printf("\n Please enter a random number seed (1..32767): "); ** scanf("%d", &i); ** srand(i); */ for (neurode = 0; neurode < MID_SIZE; neurode++) { for (i = 0; i < IN_SIZE; i++) { value = (double)ByteMark.abs_randwc(100000); value = value / (double)100000.0 - (double)0.5; mid_wts[neurode][i] = value / 2; } } for (neurode = 0; neurode < OUT_SIZE; neurode++) { for (i = 0; i < MID_SIZE; i++) { value = (double)ByteMark.abs_randwc(100000); value = value / (double)10000.0 - (double)0.5; out_wts[neurode][i] = value / 2; } } return; } /********************** ** display_mid_wts() ** *********************** ** Display the weights on the middle layer neurodes ** NOTE: This routine is not used in the benchmark ** test -- RG **/ /* static void display_mid_wts() { int neurode, weight, row, col; fprintf(outfile,"\n Weights of Middle Layer neurodes:"); for (neurode=0; neurode<MID_SIZE; neurode++) { fprintf(outfile,"\n Mid Neurode # %d",neurode); for (row=0; row<IN_Y_SIZE; row++) { fprintf(outfile,"\n "); for (col=0; col<IN_X_SIZE; col++) { weight = IN_X_SIZE * row + col; fprintf(outfile," %8.3f ", mid_wts[neurode,weight]); } } } return; } */ /********************** ** display_out_wts() ** *********************** ** Display the weights on the output layer neurodes ** NOTE: This code is not used in the benchmark ** test -- RG */ /* void display_out_wts() { int neurode, weight; fprintf(outfile,"\n Weights of Output Layer neurodes:"); for (neurode=0; neurode<OUT_SIZE; neurode++) { fprintf(outfile,"\n Out Neurode # %d \n",neurode); for (weight=0; weight<MID_SIZE; weight++) { fprintf(outfile," %8.3f ", out_wts[neurode,weight]); } } return; } */ }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /* ** This program was translated to C# and adapted for xunit-performance. ** New variants of several tests were added to compare class versus ** struct and to compare jagged arrays vs multi-dimensional arrays. */ /* ** BYTEmark (tm) ** BYTE Magazine's Native Mode benchmarks ** Rick Grehan, BYTE Magazine ** ** Create: ** Revision: 3/95 ** ** DISCLAIMER ** The source, executable, and documentation files that comprise ** the BYTEmark benchmarks are made available on an "as is" basis. ** This means that we at BYTE Magazine have made every reasonable ** effort to verify that the there are no errors in the source and ** executable code. We cannot, however, guarantee that the programs ** are error-free. Consequently, McGraw-HIll and BYTE Magazine make ** no claims in regard to the fitness of the source code, executable ** code, and documentation of the BYTEmark. ** ** Furthermore, BYTE Magazine, McGraw-Hill, and all employees ** of McGraw-Hill cannot be held responsible for any damages resulting ** from the use of this code or the results obtained from using ** this code. */ /******************************** ** BACK PROPAGATION NEURAL NET ** ********************************* ** This code is a modified version of the code ** that was submitted to BYTE Magazine by ** Maureen Caudill. It accomanied an article ** that I CANNOT NOW RECALL. ** The author's original heading/comment was ** as follows: ** ** Backpropagation Network ** Written by Maureen Caudill ** in Think C 4.0 on a Macintosh ** ** (c) Maureen Caudill 1988-1991 ** This network will accept 5x7 input patterns ** and produce 8 bit output patterns. ** The source code may be copied or modified without restriction, ** but no fee may be charged for its use. ** ** ++++++++++++++ ** I have modified the code so that it will work ** on systems other than a Macintosh -- RG */ /*********** ** DoNNet ** ************ ** Perform the neural net benchmark. ** Note that this benchmark is one of the few that ** requires an input file. That file is "NNET.DAT" and ** should be on the local directory (from which the ** benchmark program in launched). */ using System; using System.IO; public class NeuralJagged : NNetStruct { public override string Name() { return "NEURAL NET(jagged)"; } /* ** DEFINES */ public static int T = 1; /* TRUE */ public static int F = 0; /* FALSE */ public static int ERR = -1; public static int MAXPATS = 10; /* max number of patterns in data file */ public static int IN_X_SIZE = 5; /* number of neurodes/row of input layer */ public static int IN_Y_SIZE = 7; /* number of neurodes/col of input layer */ public static int IN_SIZE = 35; /* equals IN_X_SIZE*IN_Y_SIZE */ public static int MID_SIZE = 8; /* number of neurodes in middle layer */ public static int OUT_SIZE = 8; /* number of neurodes in output layer */ public static double MARGIN = 0.1; /* how near to 1,0 do we have to come to stop? */ public static double BETA = 0.09; /* beta learning constant */ public static double ALPHA = 0.09; /* momentum term constant */ public static double STOP = 0.1; /* when worst_error less than STOP, training is done */ /* ** MAXNNETLOOPS ** ** This constant sets the max number of loops through the neural ** net that the system will attempt before giving up. This ** is not a critical constant. You can alter it if your system ** has sufficient horsepower. */ public static int MAXNNETLOOPS = 50000; /* ** GLOBALS */ public static double[][] mid_wts = new double[MID_SIZE][]; public static double[][] out_wts = new double[OUT_SIZE][]; public static double[] mid_out = new double[MID_SIZE]; public static double[] out_out = new double[OUT_SIZE]; public static double[] mid_error = new double[MID_SIZE]; public static double[] out_error = new double[OUT_SIZE]; public static double[][] mid_wt_change = new double[MID_SIZE][]; public static double[][] out_wt_change = new double[OUT_SIZE][]; public static double[][] in_pats = new double[MAXPATS][]; public static double[][] out_pats = new double[MAXPATS][]; public static double[] tot_out_error = new double[MAXPATS]; public static double[][] out_wt_cum_change = new double[OUT_SIZE][]; public static double[][] mid_wt_cum_change = new double[MID_SIZE][]; public static double worst_error = 0.0; /* worst error each pass through the data */ public static double average_error = 0.0; /* average error each pass through the data */ public static double[] avg_out_error = new double[MAXPATS]; public static int iteration_count = 0; /* number of passes thru network so far */ public static int numpats = 0; /* number of patterns in data file */ public static int numpasses = 0; /* number of training passes through data file */ public static int learned = 0; /* flag--if TRUE, network has learned all patterns */ /* ** The Neural Net test requires an input data file. ** The name is specified here. */ public static string inpath = "NNET.DAT"; public static void Init() { for (int i = 0; i < MID_SIZE; i++) { mid_wts[i] = new double[IN_SIZE]; mid_wt_cum_change[i] = new double[IN_SIZE]; mid_wt_change[i] = new double[IN_SIZE]; } for (int i = 0; i < OUT_SIZE; i++) { out_wt_change[i] = new double[MID_SIZE]; out_wts[i] = new double[MID_SIZE]; out_wt_cum_change[i] = new double[MID_SIZE]; } for (int i = 0; i < MAXPATS; i++) { in_pats[i] = new double[IN_SIZE]; out_pats[i] = new double[OUT_SIZE]; } } public override double Run() { Init(); return DoNNET(this); } /********************* ** read_data_file() ** ********************** ** Read in the input data file and store the patterns in ** in_pats and out_pats. ** The format for the data file is as follows: ** ** line# data expected ** ----- ------------------------------ ** 1 In-X-size,in-y-size,out-size ** 2 number of patterns in file ** 3 1st X row of 1st input pattern ** 4.. following rows of 1st input pattern pattern ** in-x+2 y-out pattern ** 1st X row of 2nd pattern ** etc. ** ** Each row of data is separated by commas or spaces. ** The data is expected to be ascii text corresponding to ** either a +1 or a 0. ** ** Sample input for a 1-pattern file (The comments to the ** right may NOT be in the file unless more sophisticated ** parsing of the input is done.): ** ** 5,7,8 input is 5x7 grid, output is 8 bits ** 1 one pattern in file ** 0,1,1,1,0 beginning of pattern for "O" ** 1,0,0,0,1 ** 1,0,0,0,1 ** 1,0,0,0,1 ** 1,0,0,0,1 ** 1,0,0,0,0 ** 0,1,1,1,0 ** 0,1,0,0,1,1,1,1 ASCII code for "O" -- 0100 1111 ** ** Clearly, this simple scheme can be expanded or enhanced ** any way you like. ** ** Returns -1 if any file error occurred, otherwise 0. **/ private void read_data_file() { int xinsize = 0, yinsize = 0, youtsize = 0; int patt = 0, element = 0, i = 0, row = 0; int vals_read = 0; int val1 = 0, val2 = 0, val3 = 0, val4 = 0, val5 = 0, val6 = 0, val7 = 0, val8 = 0; Object[] results = new Object[8]; string input = NeuralData.Input; StringReader infile = new StringReader(input); vals_read = Utility.fscanf(infile, "%d %d %d", results); xinsize = (int)results[0]; yinsize = (int)results[1]; youtsize = (int)results[2]; if (vals_read != 3) { throw new Exception("NNET: error reading input"); } vals_read = Utility.fscanf(infile, "%d", results); numpats = (int)results[0]; if (vals_read != 1) { throw new Exception("NNET: error reading input"); } if (numpats > MAXPATS) numpats = MAXPATS; for (patt = 0; patt < numpats; patt++) { element = 0; for (row = 0; row < yinsize; row++) { vals_read = Utility.fscanf(infile, "%d %d %d %d %d", results); val1 = (int)results[0]; val2 = (int)results[1]; val3 = (int)results[2]; val4 = (int)results[3]; val5 = (int)results[4]; if (vals_read != 5) { throw new Exception("NNET: error reading input"); } element = row * xinsize; in_pats[patt][element] = (double)val1; element++; in_pats[patt][element] = (double)val2; element++; in_pats[patt][element] = (double)val3; element++; in_pats[patt][element] = (double)val4; element++; in_pats[patt][element] = (double)val5; element++; } for (i = 0; i < IN_SIZE; i++) { if (in_pats[patt][i] >= 0.9) in_pats[patt][i] = 0.9; if (in_pats[patt][i] <= 0.1) in_pats[patt][i] = 0.1; } element = 0; vals_read = Utility.fscanf(infile, "%d %d %d %d %d %d %d %d", results); val1 = (int)results[0]; val2 = (int)results[1]; val3 = (int)results[2]; val4 = (int)results[3]; val5 = (int)results[4]; val6 = (int)results[5]; val7 = (int)results[6]; val8 = (int)results[7]; out_pats[patt][element] = (double)val1; element++; out_pats[patt][element] = (double)val2; element++; out_pats[patt][element] = (double)val3; element++; out_pats[patt][element] = (double)val4; element++; out_pats[patt][element] = (double)val5; element++; out_pats[patt][element] = (double)val6; element++; out_pats[patt][element] = (double)val7; element++; out_pats[patt][element] = (double)val8; element++; } } private double DoNNET(NNetStruct locnnetstruct) { // string errorcontext = "CPU:NNET"; // int systemerror = 0; long accumtime = 0; double iterations = 0.0; /* ** Init random number generator. ** NOTE: It is important that the random number generator ** be re-initialized for every pass through this test. ** The NNET algorithm uses the random number generator ** to initialize the net. Results are sensitive to ** the initial neural net state. */ ByteMark.randnum(3); /* ** Read in the input and output patterns. We'll do this ** only once here at the beginning. These values don't ** change once loaded. */ read_data_file(); /* ** See if we need to perform self adjustment loop. */ if (locnnetstruct.adjust == 0) { /* ** Do self-adjustment. This involves initializing the ** # of loops and increasing the loop count until we ** get a number of loops that we can use. */ for (locnnetstruct.loops = 1; locnnetstruct.loops < MAXNNETLOOPS; locnnetstruct.loops++) { ByteMark.randnum(3); if (DoNNetIteration(locnnetstruct.loops) > global.min_ticks) break; } } /* ** All's well if we get here. Do the test. */ accumtime = 0L; iterations = (double)0.0; do { ByteMark.randnum(3); /* Gotta do this for Neural Net */ accumtime += DoNNetIteration(locnnetstruct.loops); iterations += (double)locnnetstruct.loops; } while (ByteMark.TicksToSecs(accumtime) < locnnetstruct.request_secs); /* ** Clean up, calculate results, and go home. Be sure to ** show that we don't have to rerun adjustment code. */ locnnetstruct.iterspersec = iterations / ByteMark.TicksToFracSecs(accumtime); if (locnnetstruct.adjust == 0) locnnetstruct.adjust = 1; return locnnetstruct.iterspersec; } /******************** ** DoNNetIteration ** ********************* ** Do a single iteration of the neural net benchmark. ** By iteration, we mean a "learning" pass. */ public static long DoNNetIteration(long nloops) { long elapsed; /* Elapsed time */ int patt; /* ** Run nloops learning cycles. Notice that, counted with ** the learning cycle is the weight randomization and ** zeroing of changes. This should reduce clock jitter, ** since we don't have to stop and start the clock for ** each iteration. */ elapsed = ByteMark.StartStopwatch(); while (nloops-- != 0) { randomize_wts(); zero_changes(); iteration_count = 1; learned = F; numpasses = 0; while (learned == F) { for (patt = 0; patt < numpats; patt++) { worst_error = 0.0; /* reset this every pass through data */ move_wt_changes(); /* move last pass's wt changes to momentum array */ do_forward_pass(patt); do_back_pass(patt); iteration_count++; } numpasses++; learned = check_out_error(); } } return (ByteMark.StopStopwatch(elapsed)); } /************************* ** do_mid_forward(patt) ** ************************** ** Process the middle layer's forward pass ** The activation of middle layer's neurode is the weighted ** sum of the inputs from the input pattern, with sigmoid ** function applied to the inputs. **/ public static void do_mid_forward(int patt) { double sum; int neurode, i; for (neurode = 0; neurode < MID_SIZE; neurode++) { sum = 0.0; for (i = 0; i < IN_SIZE; i++) { /* compute weighted sum of input signals */ sum += mid_wts[neurode][i] * in_pats[patt][i]; } /* ** apply sigmoid function f(x) = 1/(1+exp(-x)) to weighted sum */ sum = 1.0 / (1.0 + Math.Exp(-sum)); mid_out[neurode] = sum; } return; } /********************* ** do_out_forward() ** ********************** ** process the forward pass through the output layer ** The activation of the output layer is the weighted sum of ** the inputs (outputs from middle layer), modified by the ** sigmoid function. **/ public static void do_out_forward() { double sum; int neurode, i; for (neurode = 0; neurode < OUT_SIZE; neurode++) { sum = 0.0; for (i = 0; i < MID_SIZE; i++) { /* ** compute weighted sum of input signals ** from middle layer */ sum += out_wts[neurode][i] * mid_out[i]; } /* ** Apply f(x) = 1/(1+Math.Exp(-x)) to weighted input */ sum = 1.0 / (1.0 + Math.Exp(-sum)); out_out[neurode] = sum; } return; } /************************* ** display_output(patt) ** ************************** ** Display the actual output vs. the desired output of the ** network. ** Once the training is complete, and the "learned" flag set ** to TRUE, then display_output sends its output to both ** the screen and to a text output file. ** ** NOTE: This routine has been disabled in the benchmark ** version. -- RG **/ /* public static void display_output(int patt) { int i; fprintf(outfile,"\n Iteration # %d",iteration_count); fprintf(outfile,"\n Desired Output: "); for (i=0; i<OUT_SIZE; i++) { fprintf(outfile,"%6.3f ",out_pats[patt][i]); } fprintf(outfile,"\n Actual Output: "); for (i=0; i<OUT_SIZE; i++) { fprintf(outfile,"%6.3f ",out_out[i]); } fprintf(outfile,"\n"); return; } */ /********************** ** do_forward_pass() ** *********************** ** control function for the forward pass through the network ** NOTE: I have disabled the call to display_output() in ** the benchmark version -- RG. **/ public static void do_forward_pass(int patt) { do_mid_forward(patt); /* process forward pass, middle layer */ do_out_forward(); /* process forward pass, output layer */ /* display_output(patt); ** display results of forward pass */ return; } /*********************** ** do_out_error(patt) ** ************************ ** Compute the error for the output layer neurodes. ** This is simply Desired - Actual. **/ public static void do_out_error(int patt) { int neurode; double error, tot_error, sum; tot_error = 0.0; sum = 0.0; for (neurode = 0; neurode < OUT_SIZE; neurode++) { out_error[neurode] = out_pats[patt][neurode] - out_out[neurode]; /* ** while we're here, also compute magnitude ** of total error and worst error in this pass. ** We use these to decide if we are done yet. */ error = out_error[neurode]; if (error < 0.0) { sum += -error; if (-error > tot_error) tot_error = -error; /* worst error this pattern */ } else { sum += error; if (error > tot_error) tot_error = error; /* worst error this pattern */ } } avg_out_error[patt] = sum / OUT_SIZE; tot_out_error[patt] = tot_error; return; } /*********************** ** worst_pass_error() ** ************************ ** Find the worst and average error in the pass and save it **/ public static void worst_pass_error() { double error, sum; int i; error = 0.0; sum = 0.0; for (i = 0; i < numpats; i++) { if (tot_out_error[i] > error) error = tot_out_error[i]; sum += avg_out_error[i]; } worst_error = error; average_error = sum / numpats; return; } /******************* ** do_mid_error() ** ******************** ** Compute the error for the middle layer neurodes ** This is based on the output errors computed above. ** Note that the derivative of the sigmoid f(x) is ** f'(x) = f(x)(1 - f(x)) ** Recall that f(x) is merely the output of the middle ** layer neurode on the forward pass. **/ public static void do_mid_error() { double sum; int neurode, i; for (neurode = 0; neurode < MID_SIZE; neurode++) { sum = 0.0; for (i = 0; i < OUT_SIZE; i++) sum += out_wts[i][neurode] * out_error[i]; /* ** apply the derivative of the sigmoid here ** Because of the choice of sigmoid f(I), the derivative ** of the sigmoid is f'(I) = f(I)(1 - f(I)) */ mid_error[neurode] = mid_out[neurode] * (1 - mid_out[neurode]) * sum; } return; } /********************* ** adjust_out_wts() ** ********************** ** Adjust the weights of the output layer. The error for ** the output layer has been previously propagated back to ** the middle layer. ** Use the Delta Rule with momentum term to adjust the weights. **/ public static void adjust_out_wts() { int weight, neurode; double learn, delta, alph; learn = BETA; alph = ALPHA; for (neurode = 0; neurode < OUT_SIZE; neurode++) { for (weight = 0; weight < MID_SIZE; weight++) { /* standard delta rule */ delta = learn * out_error[neurode] * mid_out[weight]; /* now the momentum term */ delta += alph * out_wt_change[neurode][weight]; out_wts[neurode][weight] += delta; /* keep track of this pass's cum wt changes for next pass's momentum */ out_wt_cum_change[neurode][weight] += delta; } } return; } /************************* ** adjust_mid_wts(patt) ** ************************** ** Adjust the middle layer weights using the previously computed ** errors. ** We use the Generalized Delta Rule with momentum term **/ public static void adjust_mid_wts(int patt) { int weight, neurode; double learn, alph, delta; learn = BETA; alph = ALPHA; for (neurode = 0; neurode < MID_SIZE; neurode++) { for (weight = 0; weight < IN_SIZE; weight++) { /* first the basic delta rule */ delta = learn * mid_error[neurode] * in_pats[patt][weight]; /* with the momentum term */ delta += alph * mid_wt_change[neurode][weight]; mid_wts[neurode][weight] += delta; /* keep track of this pass's cum wt changes for next pass's momentum */ mid_wt_cum_change[neurode][weight] += delta; } } return; } /******************* ** do_back_pass() ** ******************** ** Process the backward propagation of error through network. **/ public static void do_back_pass(int patt) { do_out_error(patt); do_mid_error(); adjust_out_wts(); adjust_mid_wts(patt); return; } /********************** ** move_wt_changes() ** *********************** ** Move the weight changes accumulated last pass into the wt-change ** array for use by the momentum term in this pass. Also zero out ** the accumulating arrays after the move. **/ public static void move_wt_changes() { int i, j; for (i = 0; i < MID_SIZE; i++) for (j = 0; j < IN_SIZE; j++) { mid_wt_change[i][j] = mid_wt_cum_change[i][j]; /* ** Zero it out for next pass accumulation. */ mid_wt_cum_change[i][j] = 0.0; } for (i = 0; i < OUT_SIZE; i++) for (j = 0; j < MID_SIZE; j++) { out_wt_change[i][j] = out_wt_cum_change[i][j]; out_wt_cum_change[i][j] = 0.0; } return; } /********************** ** check_out_error() ** *********************** ** Check to see if the error in the output layer is below ** MARGIN*OUT_SIZE for all output patterns. If so, then ** assume the network has learned acceptably well. This ** is simply an arbitrary measure of how well the network ** has learned -- many other standards are possible. **/ public static int check_out_error() { int result, i, error; result = T; error = F; worst_pass_error(); /* identify the worst error in this pass */ for (i = 0; i < numpats; i++) { if (worst_error >= STOP) result = F; if (tot_out_error[i] >= 16.0) error = T; } if (error == T) result = ERR; return (result); } /******************* ** zero_changes() ** ******************** ** Zero out all the wt change arrays **/ public static void zero_changes() { int i, j; for (i = 0; i < MID_SIZE; i++) { for (j = 0; j < IN_SIZE; j++) { mid_wt_change[i][j] = 0.0; mid_wt_cum_change[i][j] = 0.0; } } for (i = 0; i < OUT_SIZE; i++) { for (j = 0; j < MID_SIZE; j++) { out_wt_change[i][j] = 0.0; out_wt_cum_change[i][j] = 0.0; } } return; } /******************** ** randomize_wts() ** ********************* ** Intialize the weights in the middle and output layers to ** random values between -0.25..+0.25 ** Function rand() returns a value between 0 and 32767. ** ** NOTE: Had to make alterations to how the random numbers were ** created. -- RG. **/ public static void randomize_wts() { int neurode, i; double value; /* ** Following not used int benchmark version -- RG ** ** printf("\n Please enter a random number seed (1..32767): "); ** scanf("%d", &i); ** srand(i); */ for (neurode = 0; neurode < MID_SIZE; neurode++) { for (i = 0; i < IN_SIZE; i++) { value = (double)ByteMark.abs_randwc(100000); value = value / (double)100000.0 - (double)0.5; mid_wts[neurode][i] = value / 2; } } for (neurode = 0; neurode < OUT_SIZE; neurode++) { for (i = 0; i < MID_SIZE; i++) { value = (double)ByteMark.abs_randwc(100000); value = value / (double)10000.0 - (double)0.5; out_wts[neurode][i] = value / 2; } } return; } /********************** ** display_mid_wts() ** *********************** ** Display the weights on the middle layer neurodes ** NOTE: This routine is not used in the benchmark ** test -- RG **/ /* static void display_mid_wts() { int neurode, weight, row, col; fprintf(outfile,"\n Weights of Middle Layer neurodes:"); for (neurode=0; neurode<MID_SIZE; neurode++) { fprintf(outfile,"\n Mid Neurode # %d",neurode); for (row=0; row<IN_Y_SIZE; row++) { fprintf(outfile,"\n "); for (col=0; col<IN_X_SIZE; col++) { weight = IN_X_SIZE * row + col; fprintf(outfile," %8.3f ", mid_wts[neurode,weight]); } } } return; } */ /********************** ** display_out_wts() ** *********************** ** Display the weights on the output layer neurodes ** NOTE: This code is not used in the benchmark ** test -- RG */ /* void display_out_wts() { int neurode, weight; fprintf(outfile,"\n Weights of Output Layer neurodes:"); for (neurode=0; neurode<OUT_SIZE; neurode++) { fprintf(outfile,"\n Out Neurode # %d \n",neurode); for (weight=0; weight<MID_SIZE; weight++) { fprintf(outfile," %8.3f ", out_wts[neurode,weight]); } } return; } */ }
-1