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 |